1 /* Generates about 1 MB of random data that is then divided into
2 16 chunks. A separate subprocess sorts each chunk; the
3 subprocesses run in parallel. Then we merge the chunks and
4 verify that the result is what it should be. */
8 #include "tests/arc4.h"
10 #include "tests/main.h"
12 #define CHUNK_SIZE (128 * 1024)
13 #define CHUNK_CNT 8 /* Number of chunks. */
14 #define DATA_SIZE (CHUNK_CNT * CHUNK_SIZE) /* Buffer size. */
16 unsigned char buf1[DATA_SIZE], buf2[DATA_SIZE];
17 size_t histogram[256];
19 /* Initialize buf1 with random data,
20 then count the number of instances of each value within it. */
29 arc4_init (&arc4, "foobar", 6);
30 arc4_crypt (&arc4, buf1, sizeof buf1);
31 for (i = 0; i < sizeof buf1; i++)
35 /* Sort each chunk of buf1 using a subprocess. */
39 pid_t children[CHUNK_CNT];
42 for (i = 0; i < CHUNK_CNT; i++)
48 msg ("sort chunk %zu", i);
50 /* Write this chunk to a file. */
51 snprintf (fn, sizeof fn, "buf%zu", i);
52 create (fn, CHUNK_SIZE);
54 CHECK ((handle = open (fn)) > 1, "open \"%s\"", fn);
55 write (handle, buf1 + CHUNK_SIZE * i, CHUNK_SIZE);
58 /* Sort with subprocess. */
59 snprintf (cmd, sizeof cmd, "child-sort %s", fn);
60 CHECK ((children[i] = exec (cmd)) != -1, "exec \"%s\"", cmd);
64 for (i = 0; i < CHUNK_CNT; i++)
69 CHECK (wait (children[i]) == 123, "wait for child %zu", i);
71 /* Read chunk back from file. */
73 snprintf (fn, sizeof fn, "buf%zu", i);
74 CHECK ((handle = open (fn)) > 1, "open \"%s\"", fn);
75 read (handle, buf1 + CHUNK_SIZE * i, CHUNK_SIZE);
81 /* Merge the sorted chunks in buf1 into a fully sorted buf2. */
85 unsigned char *mp[CHUNK_CNT];
92 /* Initialize merge pointers. */
94 for (i = 0; i < CHUNK_CNT; i++)
95 mp[i] = buf1 + CHUNK_SIZE * i;
101 /* Find smallest value. */
103 for (i = 1; i < mp_left; i++)
104 if (*mp[i] < *mp[min])
107 /* Append value to buf2. */
110 /* Advance merge pointer.
111 Delete this chunk from the set if it's emptied. */
112 if ((++mp[min] - buf1) % CHUNK_SIZE == 0)
113 mp[min] = mp[--mp_left];
126 for (hist_idx = 0; hist_idx < sizeof histogram / sizeof *histogram;
129 while (histogram[hist_idx]-- > 0)
131 if (buf2[buf_idx] != hist_idx)
132 fail ("bad value %d in byte %zu", buf2[buf_idx], buf_idx);
137 msg ("success, buf_idx=%'zu", buf_idx);