]> mj.ucw.cz Git - libucw.git/blob - lib/sorter.h
taken much faster implementation of Adler32 and put into a separate source-code
[libucw.git] / lib / sorter.h
1 /*
2  *      Sherlock Library -- Universal Sorter
3  *
4  *      (c) 2001--2004 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 /*
11  *  This is not a normal header file, it's a generator of sorting
12  *  routines.  Each time you include it with parameters set in the
13  *  corresponding preprocessor macros, it generates a file sorter
14  *  with the parameters given.
15  *
16  *  Recognized parameter macros: (those marked with [*] are mandatory)
17  *
18  *  SORT_KEY        [*] data type capable of storing a single key
19  *  SORT_PREFIX(x)  [*] add a name prefix (used on all global names
20  *                      defined by the sorter)
21  *  SORT_PRESORT        include an in-core presorting pass. Beware, when in
22  *                      the pre-sorting mode, it's quite possible that the
23  *                      comparison function will be called with both arguments
24  *                      identical.
25  *  SORT_UNIFY          merge items with identical keys
26  *  SORT_UNIQUE         all items have distinct keys (checked in debug mode)
27  *  SORT_REGULAR        all items are equally long and they don't contain
28  *                      anything else than the key. In this case, the sorter
29  *                      automatically supplies fetch_key, copy_data, fetch_item
30  *                      and store_item functions. Item size is also expected
31  *                      to be small.
32  *  SORT_DELETE_INPUT   a C expression, if true, the input files are
33  *                      deleted as soon as possible
34  *  SORT_INPUT_FILE     input is a file with this name
35  *  SORT_INPUT_FB       input is a fastbuf stream
36  *                      (can be safely NULL if you want to treat original
37  *                      input in a different way by file read functions)
38  *  SORT_INPUT_FBPAIR   input is a pair of fastbuf streams
39  *                      (not supported by the presorter)
40  *  SORT_OUTPUT_FILE    output is a file with this name
41  *  SORT_OUTPUT_FB      output is a temporary fastbuf stream
42  *
43  *  You also need to define some (usually inline) functions which
44  *  are called by the sorter to process your data:
45  *
46  *  int PREFIX_compare(SORT_KEY *a, *b)
47  *                      compare two keys, result like strcmp
48  *  int PREFIX_fetch_key(struct fastbuf *f, SORT_KEY *k)
49  *                      fetch next key, returns 1=ok, 0=eof
50  *  void PREFIX_copy_data(struct fastbuf *src, *dest, SORT_KEY *k)
51  *                      write just fetched key k to dest and copy all data
52  *                      belonging to this key from src to dest.
53  *  void PREFIX_merge_data(struct fastbuf *src1, *src2, *dest, SORT_KEY *k1, *k2)
54  *                      [used only in case SORT_UNIFY is defined]
55  *                      write just fetched key k to dest and merge data from
56  *                      two records with the same key (k1 and k2 are key occurences
57  *                      in the corresponding streams).
58  *  byte * PREFIX_fetch_item(struct fastbuf *f, SORT_KEY *k, byte *limit)
59  *                      [used only with SORT_PRESORT]
60  *                      fetch data belonging to a just fetched key and store
61  *                      them to memory following the key, but not over limit.
62  *                      Returns a pointer to first byte after the data
63  *                      or NULL if the data don't fit. For variable-length
64  *                      keys, it can use the rest of SORT_KEY and even return
65  *                      pointer before end of the key.
66  *                      Important: before PREFIX_fetch_item() succeeds, the key
67  *                      must be position independent, the sorter can copy it.
68  *  void PREFIX_store_item(struct fastbuf *f, SORT_KEY *k)
69  *                      [used only with SORT_PRESORT]
70  *                      write key and all its data read with PREFIX_fetch_data
71  *                      to the stream given.
72  *  SORT_KEY * PREFIX_merge_items(SORT_KEY *a, SORT_KEY *b)
73  *                      [used only with SORT_PRESORT && SORT_UNIFY]
74  *                      merge two items with the same key, returns pointer
75  *                      to at most one of the items, the rest will be removed
76  *                      from the list of items, but not deallocated, so
77  *                      the remaining item can freely reference data of the
78  *                      other one.
79  *
80  *  After including this file, all parameter macros are automatically
81  *  undef'd.
82  */
83
84 /* Declarations of externals from sorter.c */
85
86 #ifndef SORT_DECLS_READ
87 #define SORT_DECLS_READ
88
89 extern uns sorter_trace;
90 extern uns sorter_presort_bufsize;
91 extern uns sorter_stream_bufsize;
92
93 extern uns sorter_pass_counter;
94
95 #endif          /* !SORT_DECLS_READ */
96
97 /* The sorter proper */
98
99 #ifndef SORT_DECLARE_ONLY
100
101 #include "lib/fastbuf.h"
102 #include <unistd.h>
103 #include <fcntl.h>
104 #include <string.h>
105
106 #if !defined(SORT_KEY) || !defined(SORT_PREFIX)
107 #error Some of the mandatory configuration macros are missing.
108 #endif
109
110 #define P(x) SORT_PREFIX(x)
111 #define SWAP(x,y,z) do { z=x; x=y; y=z; } while(0)
112
113 #if defined(SORT_UNIFY) || defined(SORT_UNIQUE)
114 #define LESS <
115 #else
116 #define LESS <=
117 #endif
118
119 #if defined(SORT_UNIQUE) && defined(DEBUG)
120 #define SORT_ASSERT_UNIQUE
121 #endif
122
123 #ifdef SORT_REGULAR
124
125 static inline int
126 P(fetch_key)(struct fastbuf *in, SORT_KEY *x)
127 {
128   return breadb(in, x, sizeof(*x));
129 }
130
131 static inline void
132 P(copy_data)(struct fastbuf *in UNUSED, struct fastbuf *out, SORT_KEY *x)
133 {
134   bwrite(out, x, sizeof(*x));
135 }
136
137 static inline byte *
138 P(fetch_item)(struct fastbuf *in UNUSED, SORT_KEY *x UNUSED, byte *limit UNUSED)
139 {
140   return (byte *)(x+1);
141 }
142
143 static inline void
144 P(store_item)(struct fastbuf *out, SORT_KEY *x)
145 {
146   bwrite(out, x, sizeof(*x));
147 }
148
149 #endif
150
151 static struct fastbuf *
152 P(flush_out)(struct fastbuf *out)
153 {
154   if (out)
155     brewind(out);
156   return out;
157 }
158
159 static void
160 P(pass)(struct fastbuf **fb1, struct fastbuf **fb2)
161 {
162   struct fastbuf *in1 = *fb1;
163   struct fastbuf *in2 = *fb2;
164   struct fastbuf *out1 = NULL;
165   struct fastbuf *out2 = NULL;
166   SORT_KEY kbuf1, kbuf2, kbuf3, kbuf4;
167   SORT_KEY *kin1 = &kbuf1;
168   SORT_KEY *kprev1 = &kbuf2;
169   SORT_KEY *kin2 = &kbuf3;
170   SORT_KEY *kprev2 = &kbuf4;
171   SORT_KEY *kout = NULL;
172   SORT_KEY *ktmp;
173   int next1, next2, comp;
174   int run1, run2;
175   uns run_count = 0;
176
177   run1 = next1 = in1 ? P(fetch_key)(in1, kin1) : 0;
178   run2 = next2 = in2 ? P(fetch_key)(in2, kin2) : 0;
179   while (next1 || next2)
180     {
181       if (!run1)
182         comp = 1;
183       else if (!run2)
184         comp = -1;
185       else
186         comp = P(compare)(kin1, kin2);
187       ktmp = (comp <= 0) ? kin1 : kin2;
188       if (!kout || !(P(compare)(kout, ktmp) LESS 0))
189         {
190           struct fastbuf *t;
191           SWAP(out1, out2, t);
192           if (!out1)
193             out1 = bopen_tmp(sorter_stream_bufsize);
194           run_count++;
195         }
196       if (comp LESS 0)
197         {
198           P(copy_data)(in1, out1, kin1);
199           SWAP(kin1, kprev1, ktmp);
200           next1 = P(fetch_key)(in1, kin1);
201           run1 = next1 && (P(compare)(kprev1, kin1) LESS 0);
202           kout = kprev1;
203         }
204 #ifdef SORT_UNIFY
205       else if (comp == 0)
206         {
207           P(merge_data)(in1, in2, out1, kin1, kin2);
208           SWAP(kin1, kprev1, ktmp);
209           next1 = P(fetch_key)(in1, kin1);
210           run1 = next1 && (P(compare)(kprev1, kin1) LESS 0);
211           SWAP(kin2, kprev2, ktmp);
212           next2 = P(fetch_key)(in2, kin2);
213           run2 = next2 && (P(compare)(kprev2, kin2) LESS 0);
214           kout = kprev2;
215         }
216 #endif
217 #ifdef SORT_ASSERT_UNIQUE
218       else if (unlikely(comp == 0))
219         ASSERT(0);
220 #endif
221       else
222         {
223           P(copy_data)(in2, out1, kin2);
224           SWAP(kin2, kprev2, ktmp);
225           next2 = P(fetch_key)(in2, kin2);
226           run2 = next2 && (P(compare)(kprev2, kin2) LESS 0);
227           kout = kprev2;
228         }
229       if (!run1 && !run2)
230         {
231           run1 = next1;
232           run2 = next2;
233         }
234     }
235   bclose(in1);
236   bclose(in2);
237   if (sorter_trace)
238     log(L_INFO, "Pass %d: %d runs, %d+%d KB", sorter_pass_counter, run_count,
239         (out1 ? (int)((btell(out1) + 1023) / 1024) : 0),
240         (out2 ? (int)((btell(out2) + 1023) / 1024) : 0));
241   *fb1 = P(flush_out)(out1);
242   *fb2 = P(flush_out)(out2);
243   sorter_pass_counter++;
244 }
245
246 #ifdef SORT_PRESORT
247
248 #if defined(SORT_REGULAR) && !defined(SORT_UNIFY)
249
250 /* If we are doing a simple sort on a regular file, we can use a faster presorting strategy */
251
252 static SORT_KEY *P(array);
253
254 #define ASORT_PREFIX(x) SORT_PREFIX(x##_array)
255 #define ASORT_KEY_TYPE SORT_KEY
256 #define ASORT_ELT(i) P(array)[i]
257 #define ASORT_LT(x,y) (P(compare)(&(x),&(y)) < 0)
258
259 #include "lib/arraysort.h"
260
261 static void
262 P(presort)(struct fastbuf **fb1, struct fastbuf **fb2)
263 {
264   struct fastbuf *in = *fb1;
265   struct fastbuf *out1 = NULL;
266   struct fastbuf *out2 = NULL;
267   struct fastbuf *tbuf;
268   uns buf_items = sorter_presort_bufsize / sizeof(SORT_KEY);
269   uns run_count = 0;
270   SORT_KEY last_out, *array;
271
272   ASSERT(!*fb2);
273   if (buf_items < 2)
274     die("PresortBuffer set too low");
275   P(array) = array = xmalloc(buf_items * sizeof(SORT_KEY));
276
277   for(;;)
278     {
279       uns s = bread(in, array, buf_items * sizeof(SORT_KEY));
280       uns n = s / sizeof(SORT_KEY);
281       ASSERT(!(s % sizeof(SORT_KEY)));
282       if (!n)
283         break;
284       P(sort_array)(n);
285 #ifdef SORT_ASSERT_UNIQUE
286       for (uns i=0; i<n-1; i++)
287         if (unlikely(P(compare)(&array[i], &array[i+1]) >= 0))
288           ASSERT(0);
289       ASSERT(!run_count || P(compare)(&last_out, &array[0]));
290 #endif
291       if (!run_count || P(compare)(&last_out, &array[0]) > 0)
292         {
293           run_count++;
294           SWAP(out1, out2, tbuf);
295           if (!out1)
296             out1 = bopen_tmp(sorter_stream_bufsize);
297         }
298       last_out = array[n-1];
299       bwrite(out1, array, n * sizeof(SORT_KEY));
300     }
301
302   bclose(in);
303   if (sorter_trace)
304     log(L_INFO, "Pass 0: %d runs, %d+%d KB",
305         run_count,
306         (out1 ? (int)((btell(out1) + 1023) / 1024) : 0),
307         (out2 ? (int)((btell(out2) + 1023) / 1024) : 0));
308   *fb1 = P(flush_out)(out1);
309   *fb2 = P(flush_out)(out2);
310   xfree(array);
311 }
312
313 #else
314
315 #define SORT_NODE struct P(presort_node)
316
317 SORT_NODE {
318   SORT_NODE *next;
319   SORT_KEY key;
320 };
321
322 static SORT_NODE *
323 P(mergesort)(SORT_NODE *x)
324 {
325   SORT_NODE *f1, **l1, *f2, **l2, **l;
326
327   l1 = &f1;
328   l2 = &f2;
329   while (x)
330     {
331       *l1 = x;
332       l1 = &x->next;
333       x = x->next;
334       if (!x)
335         break;
336       *l2 = x;
337       l2 = &x->next;
338       x = x->next;
339     }
340   *l1 = *l2 = NULL;
341
342   if (f1 && f1->next)
343     f1 = P(mergesort)(f1);
344   if (f2 && f2->next)
345     f2 = P(mergesort)(f2);
346   l = &x;
347   while (f1 && f2)
348     {
349       if (P(compare)(&f1->key, &f2->key) <= 0)
350         {
351           *l = f1;
352           l = &f1->next;
353           f1 = f1->next;
354         }
355       else
356         {
357           *l = f2;
358           l = &f2->next;
359           f2 = f2->next;
360         }
361     }
362   *l = f1 ? : f2;
363   return x;
364 }
365
366 static void
367 P(presort)(struct fastbuf **fb1, struct fastbuf **fb2)
368 {
369   struct fastbuf *in = *fb1;
370   struct fastbuf *out1 = NULL;
371   struct fastbuf *out2 = NULL;
372   struct fastbuf *tbuf;
373   byte *buffer, *bufend, *current;
374   SORT_NODE *first, **last, *this, *leftover;
375   int cont = 1;
376   uns run_count = 0;
377   uns giant_count = 0;
378   uns split_count = 0;
379
380   ASSERT(!*fb2);
381   if (sorter_presort_bufsize < 2*sizeof(SORT_NODE))
382     die("PresortBuffer set too low");
383   buffer = xmalloc(sorter_presort_bufsize);
384   bufend = buffer + sorter_presort_bufsize;
385   leftover = NULL;
386   while (cont)
387     {
388       SWAP(out1, out2, tbuf);
389       if (!out1)
390         out1 = bopen_tmp(sorter_stream_bufsize);
391       current = buffer;
392       last = &first;
393       if (leftover)
394         {
395           memmove(buffer, leftover, sizeof(SORT_NODE));
396           this = leftover = (SORT_NODE *) buffer;
397           split_count++;
398           goto get_data;
399         }
400       for(;;)
401         {
402           current = (byte *) ALIGN((addr_int_t) current, CPU_STRUCT_ALIGN);
403           if (current + sizeof(*this) > bufend)
404             break;
405           this = (SORT_NODE *) current;
406           cont = P(fetch_key)(in, &this->key);
407           if (!cont)
408             break;
409         get_data:
410           current = P(fetch_item)(in, &this->key, bufend);
411           if (!current)
412             {
413               if (leftover)             /* Single node too large */
414                 {
415                   P(copy_data)(in, out1, &leftover->key);
416                   leftover = NULL;
417                   run_count++;
418                   giant_count++;
419                 }
420               else                      /* Node will be left over to the next phase */
421                 leftover = this;
422               break;
423             }
424           *last = this;
425           last = &this->next;
426           leftover = NULL;
427         }
428       *last = NULL;
429       if (!first)
430         continue;
431
432       first = P(mergesort)(first);
433       run_count++;
434       while (first)
435         {
436 #ifdef SORT_UNIFY
437           SORT_NODE *second = first->next;
438           if (second && !P(compare)(&first->key, &second->key))
439             {
440               SORT_KEY *n = P(merge_items)(&first->key, &second->key);
441               if (n == &first->key)
442                 first->next = second->next;
443               else if (n)
444                 first = first->next;
445               else
446                 first = second->next;
447               continue;
448             }
449 #endif
450 #ifdef SORT_ASSERT_UNIQUE
451           ASSERT(!first->next || P(compare)(&first->key, &first->next->key));
452 #endif
453           P(store_item)(out1, &first->key);
454           first = first->next;
455         }
456     }
457
458   bclose(in);
459   if (sorter_trace)
460     log(L_INFO, "Pass 0: %d runs (%d giants, %d splits), %d+%d KB",
461         run_count, giant_count, split_count,
462         (out1 ? (int)((btell(out1) + 1023) / 1024) : 0),
463         (out2 ? (int)((btell(out2) + 1023) / 1024) : 0));
464   *fb1 = P(flush_out)(out1);
465   *fb2 = P(flush_out)(out2);
466   xfree(buffer);
467 }
468
469 #endif          /* SORT_REGULAR && !SORT_UNIFY */
470
471 #endif          /* SORT_PRESORT */
472
473 static
474 #ifdef SORT_OUTPUT_FB
475 struct fastbuf *
476 #elif defined(SORT_OUTPUT_FILE)
477 void
478 #else
479 #error No output defined.
480 #endif
481 P(sort)(
482 #ifdef SORT_INPUT_FILE
483 byte *inname
484 #elif defined(SORT_INPUT_FB)
485 struct fastbuf *fb1
486 #elif defined(SORT_INPUT_FBPAIR)
487 struct fastbuf *fb1, struct fastbuf *fb2
488 #else
489 #error No input defined.
490 #endif
491 #ifdef SORT_OUTPUT_FILE
492 ,byte *outname
493 #endif
494 )
495 {
496 #ifdef SORT_INPUT_FILE
497   struct fastbuf *fb1, *fb2;
498   fb1 = bopen(inname, O_RDONLY, sorter_stream_bufsize);
499   fb2 = NULL;
500 #elif defined(SORT_INPUT_FB)
501   struct fastbuf *fb2 = NULL;
502 #endif
503
504 #ifdef SORT_DELETE_INPUT
505   bconfig(fb1, BCONFIG_IS_TEMP_FILE, SORT_DELETE_INPUT);
506 #endif
507   sorter_pass_counter = 1;
508 #ifdef SORT_PRESORT
509   P(presort)(&fb1, &fb2);
510   if (fb2)
511 #endif
512     do P(pass)(&fb1, &fb2); while (fb1 && fb2);
513   if (!fb1)
514     fb1 = bopen_tmp(sorter_stream_bufsize);
515
516 #ifdef SORT_OUTPUT_FB
517   return fb1;
518 #else
519   bconfig(fb1, BCONFIG_IS_TEMP_FILE, 0);
520   if (rename(fb1->name, outname) < 0)
521     die("rename(%s,%s): %m", fb1->name, outname);
522   bclose(fb1);
523 #endif
524 }
525
526 #undef P
527 #undef LESS
528 #undef SWAP
529 #undef SORT_NODE
530 #undef SORT_KEY
531 #undef SORT_PREFIX
532 #undef SORT_UNIFY
533 #undef SORT_UNIQUE
534 #undef SORT_ASSERT_UNIQUE
535 #undef SORT_REGULAR
536 #undef SORT_DELETE_INPUT
537 #undef SORT_INPUT_FILE
538 #undef SORT_INPUT_FB
539 #undef SORT_INPUT_FBPAIR
540 #undef SORT_OUTPUT_FILE
541 #undef SORT_OUTPUT_FB
542
543 #endif          /* !SORT_DECLARE_ONLY */