00001
00002
00003
00004
00005
00006 #include <syscall.h>
00007 #include "tests/arc4.h"
00008 #include "tests/lib.h"
00009 #include "tests/main.h"
00010
00011
00012
00013
00014 #define CHUNK_SIZE (126 * 512)
00015 #define CHUNK_CNT 16
00016 #define DATA_SIZE (CHUNK_CNT * CHUNK_SIZE)
00017
00018 unsigned char buf1[DATA_SIZE], buf2[DATA_SIZE];
00019 size_t histogram[256];
00020
00021
00022
00023 static void
00024 init (void)
00025 {
00026 struct arc4 arc4;
00027 size_t i;
00028
00029 msg ("init");
00030
00031 arc4_init (&arc4, "foobar", 6);
00032 arc4_crypt (&arc4, buf1, sizeof buf1);
00033 for (i = 0; i < sizeof buf1; i++)
00034 histogram[buf1[i]]++;
00035 }
00036
00037
00038 static void
00039 sort_chunks (void)
00040 {
00041 size_t i;
00042
00043 create ("buffer", CHUNK_SIZE);
00044 for (i = 0; i < CHUNK_CNT; i++)
00045 {
00046 pid_t child;
00047 int handle;
00048
00049 msg ("sort chunk %zu", i);
00050
00051
00052 quiet = true;
00053 CHECK ((handle = open ("buffer")) > 1, "open \"buffer\"");
00054 write (handle, buf1 + CHUNK_SIZE * i, CHUNK_SIZE);
00055 close (handle);
00056
00057
00058 CHECK ((child = exec ("child-sort buffer")) != -1,
00059 "exec \"child-sort buffer\"");
00060 CHECK (wait (child) == 123, "wait for child-sort");
00061
00062
00063 CHECK ((handle = open ("buffer")) > 1, "open \"buffer\"");
00064 read (handle, buf1 + CHUNK_SIZE * i, CHUNK_SIZE);
00065 close (handle);
00066
00067 quiet = false;
00068 }
00069 }
00070
00071
00072 static void
00073 merge (void)
00074 {
00075 unsigned char *mp[CHUNK_CNT];
00076 size_t mp_left;
00077 unsigned char *op;
00078 size_t i;
00079
00080 msg ("merge");
00081
00082
00083 mp_left = CHUNK_CNT;
00084 for (i = 0; i < CHUNK_CNT; i++)
00085 mp[i] = buf1 + CHUNK_SIZE * i;
00086
00087
00088 op = buf2;
00089 while (mp_left > 0)
00090 {
00091
00092 size_t min = 0;
00093 for (i = 1; i < mp_left; i++)
00094 if (*mp[i] < *mp[min])
00095 min = i;
00096
00097
00098 *op++ = *mp[min];
00099
00100
00101
00102 if ((++mp[min] - buf1) % CHUNK_SIZE == 0)
00103 mp[min] = mp[--mp_left];
00104 }
00105 }
00106
00107 static void
00108 verify (void)
00109 {
00110 size_t buf_idx;
00111 size_t hist_idx;
00112
00113 msg ("verify");
00114
00115 buf_idx = 0;
00116 for (hist_idx = 0; hist_idx < sizeof histogram / sizeof *histogram;
00117 hist_idx++)
00118 {
00119 while (histogram[hist_idx]-- > 0)
00120 {
00121 if (buf2[buf_idx] != hist_idx)
00122 fail ("bad value %d in byte %zu", buf2[buf_idx], buf_idx);
00123 buf_idx++;
00124 }
00125 }
00126
00127 msg ("success, buf_idx=%'zu", buf_idx);
00128 }
00129
00130 void
00131 test_main (void)
00132 {
00133 init ();
00134 sort_chunks ();
00135 merge ();
00136 verify ();
00137 }