]> mj.ucw.cz Git - libucw.git/blob - lib/sorter.h
Added bitsig_free().
[libucw.git] / lib / sorter.h
1 /*
2  *      Sherlock Library -- Universal Sorter
3  *
4  *      (c) 2001 Martin Mares <mj@ucw.cz>
5  */
6
7 /*
8  *  This is not a normal header file, it's a generator of sorting
9  *  routines.  Each time you include it with parameters set in the
10  *  corresponding preprocessor macros, it generates a file sorter
11  *  with the parameters given.
12  *
13  *  Recognized parameter macros: (those marked with [*] are mandatory)
14  *
15  *  SORT_KEY        [*] data type capable of storing a single key
16  *  SORT_PREFIX(x)  [*] add a name prefix (used on all global names
17  *                      defined by the sorter)
18  *  SORT_PRESORT        include an in-core presorting pass
19  *  SORT_UNIFY          merge items with identical keys
20  *  SORT_DELETE_INPUT   a C expression, if true, the input files are
21  *                      deleted as soon as possible
22  *  SORT_INPUT_FILE     input is a file with this name
23  *  SORT_INPUT_FB       input is a fastbuf stream
24  *                      (can be safely NULL if you want to treat original
25  *                      input in a different way by file read functions)
26  *  SORT_INPUT_FBPAIR   input is a pair of fastbuf streams
27  *                      (not supported by the presorter)
28  *  SORT_OUTPUT_FILE    output is a file with this name
29  *  SORT_OUTPUT_FB      output is a temporary fastbuf stream
30  *
31  *  You also need to define some (usually inline) functions which
32  *  are called by the sorter to process your data:
33  *
34  *  int PREFIX_compare(SORT_KEY *a, *b)
35  *                      compare two keys, result like strcmp
36  *  int PREFIX_fetch_key(struct fastbuf *f, SORT_KEY *k)
37  *                      fetch next key, returns 1=ok, 0=eof
38  *  void PREFIX_copy_data(struct fastbuf *src, *dest, SORT_KEY *k)
39  *                      write just fetched key k to dest and copy all data
40  *                      belonging to this key from src to dest.
41  *  void PREFIX_merge_data(struct fastbuf *src1, *src2, *dest, SORT_KEY *k1, *k2)
42  *                      [used only in case SORT_UNIFY is defined]
43  *                      write just fetched key k to dest and merge data from
44  *                      two records with the same key (k1 and k2 are key occurences
45  *                      in the corresponding streams).
46  *  byte * PREFIX_fetch_item(struct fastbuf *f, SORT_KEY *k, byte *limit)
47  *                      [used only with SORT_PRESORT]
48  *                      fetch data belonging to a just fetched key and store
49  *                      them to memory following the key, but not over limit.
50  *                      Returns a pointer to first byte after the data
51  *                      or NULL if the data don't fit. For variable-length
52  *                      keys, it can use the rest of SORT_KEY and even return
53  *                      pointer before end of the key.
54  *                      Important: before PREFIX_fetch_item() succeeds, the key
55  *                      must be position independent, the sorter can copy it.
56  *  void PREFIX_store_item(struct fastbuf *f, SORT_KEY *k)
57  *                      [used only with SORT_PRESORT]
58  *                      write key and all its data read with PREFIX_fetch_data
59  *                      to the stream given.
60  *  SORT_KEY * PREFIX_merge_items(SORT_KEY *a, SORT_KEY *b)
61  *                      [used only with SORT_PRESORT && SORT_UNIFY]
62  *                      merge two items with the same key, returns pointer
63  *                      to at most one of the items, the rest will be removed
64  *                      from the list of items, but not deallocated, so
65  *                      the remaining item can freely reference data of the
66  *                      other one.
67  */
68
69 /* Declarations of externals from sorter.c */
70
71 #ifndef SORT_DECLS_READ
72 #define SORT_DECLS_READ
73
74 extern uns sorter_trace;
75 extern uns sorter_presort_bufsize;
76 extern uns sorter_stream_bufsize;
77
78 extern uns sorter_pass_counter, sorter_file_counter;
79 struct fastbuf *sorter_open_tmp(void);
80
81 #endif          /* !SORT_DECLS_READ */
82
83 /* The sorter proper */
84
85 #ifndef SORT_DECLARE_ONLY
86
87 #include "lib/fastbuf.h"
88 #include <unistd.h>
89 #include <fcntl.h>
90 #include <string.h>
91
92 #if !defined(SORT_KEY) || !defined(SORT_PREFIX)
93 #error Some of the mandatory configuration macros are missing.
94 #endif
95
96 #define P(x) SORT_PREFIX(x)
97 #define SWAP(x,y,z) do { z=x; x=y; y=z; } while(0)
98
99 #if defined(SORT_UNIFY) || defined(SORT_UNIQUE)
100 #define LESS <
101 #else
102 #define LESS <=
103 #endif
104
105 static struct fastbuf *
106 P(flush_out)(struct fastbuf *out)
107 {
108   if (out)
109     {
110       bflush(out);
111       bsetpos(out, 0);
112     }
113   return out;
114 }
115
116 static void
117 P(pass)(struct fastbuf **fb1, struct fastbuf **fb2)
118 {
119   struct fastbuf *in1 = *fb1;
120   struct fastbuf *in2 = *fb2;
121   struct fastbuf *out1 = NULL;
122   struct fastbuf *out2 = NULL;
123   SORT_KEY kbuf1, kbuf2, kbuf3, kbuf4;
124   SORT_KEY *kin1 = &kbuf1;
125   SORT_KEY *kprev1 = &kbuf2;
126   SORT_KEY *kin2 = &kbuf3;
127   SORT_KEY *kprev2 = &kbuf4;
128   SORT_KEY *kout = NULL;
129   SORT_KEY *ktmp;
130   int next1, next2, comp;
131   int run1, run2;
132   uns run_count = 0;
133
134   run1 = next1 = in1 ? P(fetch_key)(in1, kin1) : 0;
135   run2 = next2 = in2 ? P(fetch_key)(in2, kin2) : 0;
136   while (next1 || next2)
137     {
138       if (!run1)
139         comp = 1;
140       else if (!run2)
141         comp = -1;
142       else
143         comp = P(compare)(kin1, kin2);
144       ktmp = (comp <= 0) ? kin1 : kin2;
145       if (!kout || !(P(compare)(kout, ktmp) LESS 0))
146         {
147           struct fastbuf *t;
148           SWAP(out1, out2, t);
149           if (!out1)
150             out1 = sorter_open_tmp();
151           run_count++;
152         }
153       if (comp LESS 0)
154         {
155           P(copy_data)(in1, out1, kin1);
156           SWAP(kin1, kprev1, ktmp);
157           next1 = P(fetch_key)(in1, kin1);
158           run1 = next1 && (P(compare)(kprev1, kin1) LESS 0);
159           kout = kprev1;
160         }
161 #ifdef SORT_UNIFY
162       else if (comp == 0)
163         {
164           P(merge_data)(in1, in2, out1, kin1, kin2);
165           SWAP(kin1, kprev1, ktmp);
166           next1 = P(fetch_key)(in1, kin1);
167           run1 = next1 && (P(compare)(kprev1, kin1) LESS 0);
168           SWAP(kin2, kprev2, ktmp);
169           next2 = P(fetch_key)(in2, kin2);
170           run2 = next2 && (P(compare)(kprev2, kin2) LESS 0);
171           kout = kprev2;
172         }
173 #endif
174       else
175         {
176           P(copy_data)(in2, out1, kin2);
177           SWAP(kin2, kprev2, ktmp);
178           next2 = P(fetch_key)(in2, kin2);
179           run2 = next2 && (P(compare)(kprev2, kin2) LESS 0);
180           kout = kprev2;
181         }
182       if (!run1 && !run2)
183         {
184           run1 = next1;
185           run2 = next2;
186         }
187     }
188   bclose(in1);
189   bclose(in2);
190   if (sorter_trace)
191     log(L_INFO, "Pass %d: %d runs, %d+%d KB", sorter_pass_counter, run_count,
192         (out1 ? (int)((btell(out1) + 1023) / 1024) : 0),
193         (out2 ? (int)((btell(out2) + 1023) / 1024) : 0));
194   *fb1 = P(flush_out)(out1);
195   *fb2 = P(flush_out)(out2);
196   sorter_pass_counter++;
197 }
198
199 #ifdef SORT_PRESORT
200
201 #define SORT_NODE struct P(presort_node)
202
203 SORT_NODE {
204   SORT_NODE *next;
205   SORT_KEY key;
206 };
207
208 static SORT_NODE *
209 P(mergesort)(SORT_NODE *x)
210 {
211   SORT_NODE *f1, **l1, *f2, **l2, **l;
212
213   l1 = &f1;
214   l2 = &f2;
215   while (x)
216     {
217       *l1 = x;
218       l1 = &x->next;
219       x = x->next;
220       if (!x)
221         break;
222       *l2 = x;
223       l2 = &x->next;
224       x = x->next;
225     }
226   *l1 = *l2 = NULL;
227
228   if (f1 && f1->next)
229     f1 = P(mergesort)(f1);
230   if (f2 && f2->next)
231     f2 = P(mergesort)(f2);
232   l = &x;
233   while (f1 && f2)
234     {
235       if (P(compare)(&f1->key, &f2->key) <= 0)
236         {
237           *l = f1;
238           l = &f1->next;
239           f1 = f1->next;
240         }
241       else
242         {
243           *l = f2;
244           l = &f2->next;
245           f2 = f2->next;
246         }
247     }
248   *l = f1 ? : f2;
249   return x;
250 }
251
252 static void
253 P(presort)(struct fastbuf **fb1, struct fastbuf **fb2)
254 {
255   struct fastbuf *in = *fb1;
256   struct fastbuf *out1 = NULL;
257   struct fastbuf *out2 = NULL;
258   struct fastbuf *tbuf;
259   byte *buffer, *bufend, *current;
260   SORT_NODE *first, **last, *this, *leftover;
261   int cont = 1;
262   uns run_count = 0;
263   uns giant_count = 0;
264   uns split_count = 0;
265
266   ASSERT(!*fb2);
267   if (sorter_presort_bufsize < 2*sizeof(SORT_NODE))
268     die("PresortBuffer set too low");
269   buffer = xmalloc(sorter_presort_bufsize);
270   bufend = buffer + sorter_presort_bufsize;
271   leftover = NULL;
272   while (cont)
273     {
274       SWAP(out1, out2, tbuf);
275       if (!out1)
276         out1 = sorter_open_tmp();
277       current = buffer;
278       last = &first;
279       if (leftover)
280         {
281           memmove(buffer, leftover, sizeof(SORT_NODE));
282           this = leftover = (SORT_NODE *) buffer;
283           split_count++;
284           goto get_data;
285         }
286       for(;;)
287         {
288           current = (byte *) ALIGN((addr_int_t) current, CPU_STRUCT_ALIGN);
289           if (current + sizeof(*this) > bufend)
290             break;
291           this = (SORT_NODE *) current;
292           cont = P(fetch_key)(in, &this->key);
293           if (!cont)
294             break;
295         get_data:
296           current = P(fetch_item)(in, &this->key, bufend);
297           if (!current)
298             {
299               if (leftover)             /* Single node too large */
300                 {
301                   P(copy_data)(in, out1, &leftover->key);
302                   leftover = NULL;
303                   run_count++;
304                   giant_count++;
305                 }
306               else                      /* Node will be left over to the next phase */
307                 leftover = this;
308               break;
309             }
310           *last = this;
311           last = &this->next;
312           leftover = NULL;
313         }
314       *last = NULL;
315       if (!first)
316         continue;
317
318       first = P(mergesort)(first);
319       run_count++;
320       while (first)
321         {
322 #ifdef SORT_UNIFY
323           SORT_NODE *second = first->next;
324           if (second && !P(compare)(&first->key, &second->key))
325             {
326               SORT_KEY *n = P(merge_items)(&first->key, &second->key);
327               if (n == &first->key)
328                 first->next = second->next;
329               else if (n)
330                 first = first->next;
331               else
332                 first = second->next;
333               continue;
334             }
335 #endif
336           P(store_item)(out1, &first->key);
337           first = first->next;
338         }
339     }
340
341   bclose(in);
342   if (sorter_trace)
343     log(L_INFO, "Pass 0: %d runs (%d giants, %d splits), %d+%d KB",
344         run_count, giant_count, split_count,
345         (out1 ? (int)((btell(out1) + 1023) / 1024) : 0),
346         (out2 ? (int)((btell(out2) + 1023) / 1024) : 0));
347   *fb1 = P(flush_out)(out1);
348   *fb2 = P(flush_out)(out2);
349 }
350
351 #endif          /* SORT_PRESORT */
352
353 static
354 #ifdef SORT_OUTPUT_FB
355 struct fastbuf *
356 #elif defined(SORT_OUTPUT_FILE)
357 void
358 #else
359 #error No output defined.
360 #endif
361 P(sort)(
362 #ifdef SORT_INPUT_FILE
363 byte *inname
364 #elif defined(SORT_INPUT_FB)
365 struct fastbuf *fb1
366 #elif defined(SORT_INPUT_FBPAIR)
367 struct fastbuf *fb1, struct fastbuf *fb2
368 #else
369 #error No input defined.
370 #endif
371 #ifdef SORT_OUTPUT_FILE
372 ,byte *outname
373 #endif
374 )
375 {
376 #ifdef SORT_INPUT_FILE
377   struct fastbuf *fb1, *fb2;
378   fb1 = bopen(inname, O_RDONLY, sorter_stream_bufsize);
379   fb2 = NULL;
380 #elif defined(SORT_INPUT_FB)
381   struct fastbuf *fb2 = NULL;
382 #endif
383
384 #ifdef SORT_DELETE_INPUT
385   fb1->is_temp_file = SORT_DELETE_INPUT;
386 #endif
387   sorter_pass_counter = 1;
388 #ifdef SORT_PRESORT
389   P(presort)(&fb1, &fb2);
390   if (fb2)
391 #endif
392     do P(pass)(&fb1, &fb2); while (fb1 && fb2);
393   if (!fb1)
394     fb1 = sorter_open_tmp();
395
396 #ifdef SORT_OUTPUT_FB
397   return fb1;
398 #else
399   fb1->is_temp_file = 0;
400   if (rename(fb1->name, outname) < 0)
401     die("rename(%s,%s): %m", fb1->name, outname);
402   bclose(fb1);
403 #endif
404 }
405
406 #undef P
407 #undef LESS
408 #undef SWAP
409 #undef SORT_NODE
410
411 #endif          /* !SORT_DECLARE_ONLY */