]> git.sur5r.net Git - openldap/blob - servers/slapd/back-mdb/idl.c
f4cb11f9602db27a5bebf1b882967b64ad48efd2
[openldap] / servers / slapd / back-mdb / idl.c
1 /* idl.c - ldap id list handling routines */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2000-2011 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16
17 #include "portable.h"
18
19 #include <stdio.h>
20 #include <ac/string.h>
21
22 #include "back-mdb.h"
23 #include "idl.h"
24
25 #define IDL_MAX(x,y)    ( (x) > (y) ? (x) : (y) )
26 #define IDL_MIN(x,y)    ( (x) < (y) ? (x) : (y) )
27 #define IDL_CMP(x,y)    ( (x) < (y) ? -1 : (x) > (y) )
28
29 #if IDL_DEBUG > 0
30 static void idl_check( ID *ids )
31 {
32         if( MDB_IDL_IS_RANGE( ids ) ) {
33                 assert( MDB_IDL_RANGE_FIRST(ids) <= MDB_IDL_RANGE_LAST(ids) );
34         } else {
35                 ID i;
36                 for( i=1; i < ids[0]; i++ ) {
37                         assert( ids[i+1] > ids[i] );
38                 }
39         }
40 }
41
42 #if IDL_DEBUG > 1
43 static void idl_dump( ID *ids )
44 {
45         if( MDB_IDL_IS_RANGE( ids ) ) {
46                 Debug( LDAP_DEBUG_ANY,
47                         "IDL: range ( %ld - %ld )\n",
48                         (long) MDB_IDL_RANGE_FIRST( ids ),
49                         (long) MDB_IDL_RANGE_LAST( ids ) );
50
51         } else {
52                 ID i;
53                 Debug( LDAP_DEBUG_ANY, "IDL: size %ld", (long) ids[0], 0, 0 );
54
55                 for( i=1; i<=ids[0]; i++ ) {
56                         if( i % 16 == 1 ) {
57                                 Debug( LDAP_DEBUG_ANY, "\n", 0, 0, 0 );
58                         }
59                         Debug( LDAP_DEBUG_ANY, "  %02lx", (long) ids[i], 0, 0 );
60                 }
61
62                 Debug( LDAP_DEBUG_ANY, "\n", 0, 0, 0 );
63         }
64
65         idl_check( ids );
66 }
67 #endif /* IDL_DEBUG > 1 */
68 #endif /* IDL_DEBUG > 0 */
69
70 unsigned mdb_idl_search( ID *ids, ID id )
71 {
72 #define IDL_BINARY_SEARCH 1
73 #ifdef IDL_BINARY_SEARCH
74         /*
75          * binary search of id in ids
76          * if found, returns position of id
77          * if not found, returns first postion greater than id
78          */
79         unsigned base = 0;
80         unsigned cursor = 1;
81         int val = 0;
82         unsigned n = ids[0];
83
84 #if IDL_DEBUG > 0
85         idl_check( ids );
86 #endif
87
88         while( 0 < n ) {
89                 unsigned pivot = n >> 1;
90                 cursor = base + pivot + 1;
91                 val = IDL_CMP( id, ids[cursor] );
92
93                 if( val < 0 ) {
94                         n = pivot;
95
96                 } else if ( val > 0 ) {
97                         base = cursor;
98                         n -= pivot + 1;
99
100                 } else {
101                         return cursor;
102                 }
103         }
104         
105         if( val > 0 ) {
106                 ++cursor;
107         }
108         return cursor;
109
110 #else
111         /* (reverse) linear search */
112         int i;
113
114 #if IDL_DEBUG > 0
115         idl_check( ids );
116 #endif
117
118         for( i=ids[0]; i; i-- ) {
119                 if( id > ids[i] ) {
120                         break;
121                 }
122         }
123
124         return i+1;
125 #endif
126 }
127
128 int mdb_idl_insert( ID *ids, ID id )
129 {
130         unsigned x;
131
132 #if IDL_DEBUG > 1
133         Debug( LDAP_DEBUG_ANY, "insert: %04lx at %d\n", (long) id, x, 0 );
134         idl_dump( ids );
135 #elif IDL_DEBUG > 0
136         idl_check( ids );
137 #endif
138
139         if (MDB_IDL_IS_RANGE( ids )) {
140                 /* if already in range, treat as a dup */
141                 if (id >= MDB_IDL_RANGE_FIRST(ids) && id <= MDB_IDL_RANGE_LAST(ids))
142                         return -1;
143                 if (id < MDB_IDL_RANGE_FIRST(ids))
144                         ids[1] = id;
145                 else if (id > MDB_IDL_RANGE_LAST(ids))
146                         ids[2] = id;
147                 return 0;
148         }
149
150         x = mdb_idl_search( ids, id );
151         assert( x > 0 );
152
153         if( x < 1 ) {
154                 /* internal error */
155                 return -2;
156         }
157
158         if ( x <= ids[0] && ids[x] == id ) {
159                 /* duplicate */
160                 return -1;
161         }
162
163         if ( ++ids[0] >= MDB_IDL_DB_MAX ) {
164                 if( id < ids[1] ) {
165                         ids[1] = id;
166                         ids[2] = ids[ids[0]-1];
167                 } else if ( ids[ids[0]-1] < id ) {
168                         ids[2] = id;
169                 } else {
170                         ids[2] = ids[ids[0]-1];
171                 }
172                 ids[0] = NOID;
173         
174         } else {
175                 /* insert id */
176                 AC_MEMCPY( &ids[x+1], &ids[x], (ids[0]-x) * sizeof(ID) );
177                 ids[x] = id;
178         }
179
180 #if IDL_DEBUG > 1
181         idl_dump( ids );
182 #elif IDL_DEBUG > 0
183         idl_check( ids );
184 #endif
185
186         return 0;
187 }
188
189 static int mdb_idl_delete( ID *ids, ID id )
190 {
191         unsigned x;
192
193 #if IDL_DEBUG > 1
194         Debug( LDAP_DEBUG_ANY, "delete: %04lx at %d\n", (long) id, x, 0 );
195         idl_dump( ids );
196 #elif IDL_DEBUG > 0
197         idl_check( ids );
198 #endif
199
200         if (MDB_IDL_IS_RANGE( ids )) {
201                 /* If deleting a range boundary, adjust */
202                 if ( ids[1] == id )
203                         ids[1]++;
204                 else if ( ids[2] == id )
205                         ids[2]--;
206                 /* deleting from inside a range is a no-op */
207
208                 /* If the range has collapsed, re-adjust */
209                 if ( ids[1] > ids[2] )
210                         ids[0] = 0;
211                 else if ( ids[1] == ids[2] )
212                         ids[1] = 1;
213                 return 0;
214         }
215
216         x = mdb_idl_search( ids, id );
217         assert( x > 0 );
218
219         if( x <= 0 ) {
220                 /* internal error */
221                 return -2;
222         }
223
224         if( x > ids[0] || ids[x] != id ) {
225                 /* not found */
226                 return -1;
227
228         } else if ( --ids[0] == 0 ) {
229                 if( x != 1 ) {
230                         return -3;
231                 }
232
233         } else {
234                 AC_MEMCPY( &ids[x], &ids[x+1], (1+ids[0]-x) * sizeof(ID) );
235         }
236
237 #if IDL_DEBUG > 1
238         idl_dump( ids );
239 #elif IDL_DEBUG > 0
240         idl_check( ids );
241 #endif
242
243         return 0;
244 }
245
246 static char *
247 mdb_show_key(
248         char            *buf,
249         void            *val,
250         size_t          len )
251 {
252         if ( len == 4 /* LUTIL_HASH_BYTES */ ) {
253                 unsigned char *c = val;
254                 sprintf( buf, "[%02x%02x%02x%02x]", c[0], c[1], c[2], c[3] );
255                 return buf;
256         } else {
257                 return val;
258         }
259 }
260
261 int
262 mdb_idl_fetch_key(
263         BackendDB       *be,
264         MDB_txn         *txn,
265         MDB_dbi         dbi,
266         MDB_val         *key,
267         ID                      *ids,
268         MDB_cursor      **saved_cursor,
269         int                     get_flag )
270 {
271         MDB_val data, key2, *kptr;
272         MDB_cursor *cursor;
273         ID *i;
274         size_t len;
275         int rc;
276         MDB_cursor_op opflag;
277
278         char keybuf[16];
279
280         Debug( LDAP_DEBUG_ARGS,
281                 "mdb_idl_fetch_key: %s\n", 
282                 mdb_show_key( keybuf, key->mv_data, key->mv_size ), 0, 0 );
283
284         assert( ids != NULL );
285
286         if ( saved_cursor && *saved_cursor ) {
287                 opflag = MDB_NEXT;
288         } else if ( get_flag == LDAP_FILTER_GE ) {
289                 opflag = MDB_SET_RANGE;
290         } else if ( get_flag == LDAP_FILTER_LE ) {
291                 opflag = MDB_FIRST;
292         } else {
293                 opflag = MDB_SET;
294         }
295
296         /* If we're not reusing an existing cursor, get a new one */
297         if( opflag != MDB_NEXT ) {
298                 rc = mdb_cursor_open( txn, dbi, &cursor );
299                 if( rc != 0 ) {
300                         Debug( LDAP_DEBUG_ANY, "=> mdb_idl_fetch_key: "
301                                 "cursor failed: %s (%d)\n", mdb_strerror(rc), rc, 0 );
302                         return rc;
303                 }
304         } else {
305                 cursor = *saved_cursor;
306         }
307         
308         /* If this is a LE lookup, save original key so we can determine
309          * when to stop. If this is a GE lookup, save the key since it
310          * will be overwritten.
311          */
312         if ( get_flag == LDAP_FILTER_LE || get_flag == LDAP_FILTER_GE ) {
313                 key2.mv_data = keybuf;
314                 key2.mv_size = key->mv_size;
315                 AC_MEMCPY( keybuf, key->mv_data, key->mv_size );
316                 kptr = &key2;
317         } else {
318                 kptr = key;
319         }
320         len = key->mv_size;
321         rc = mdb_cursor_get( cursor, kptr, &data, opflag );
322
323         /* skip presence key on range inequality lookups */
324         while (rc == 0 && kptr->mv_size != len) {
325                 rc = mdb_cursor_get( cursor, kptr, &data, MDB_NEXT_NODUP );
326         }
327         /* If we're doing a LE compare and the new key is greater than
328          * our search key, we're done
329          */
330         if (rc == 0 && get_flag == LDAP_FILTER_LE && memcmp( kptr->mv_data,
331                 key->mv_data, key->mv_size ) > 0 ) {
332                 rc = MDB_NOTFOUND;
333         }
334         if (rc == 0) {
335                 i = ids+1;
336                 rc = mdb_cursor_get( cursor, key, &data, MDB_GET_MULTIPLE );
337                 while (rc == 0) {
338                         memcpy( i, data.mv_data, data.mv_size );
339                         i += data.mv_size / sizeof(ID);
340                         rc = mdb_cursor_get( cursor, key, &data, MDB_NEXT_MULTIPLE );
341                 }
342                 if ( rc == MDB_NOTFOUND ) rc = 0;
343                 ids[0] = i - &ids[1];
344                 /* On disk, a range is denoted by 0 in the first element */
345                 if (ids[1] == 0) {
346                         if (ids[0] != MDB_IDL_RANGE_SIZE) {
347                                 Debug( LDAP_DEBUG_ANY, "=> mdb_idl_fetch_key: "
348                                         "range size mismatch: expected %d, got %ld\n",
349                                         MDB_IDL_RANGE_SIZE, ids[0], 0 );
350                                 mdb_cursor_close( cursor );
351                                 return -1;
352                         }
353                         MDB_IDL_RANGE( ids, ids[2], ids[3] );
354                 }
355                 data.mv_size = MDB_IDL_SIZEOF(ids);
356         }
357
358         if ( saved_cursor && rc == 0 ) {
359                 if ( !*saved_cursor )
360                         *saved_cursor = cursor;
361         }
362         else
363                 mdb_cursor_close( cursor );
364
365         if( rc == MDB_NOTFOUND ) {
366                 return rc;
367
368         } else if( rc != 0 ) {
369                 Debug( LDAP_DEBUG_ANY, "=> mdb_idl_fetch_key: "
370                         "get failed: %s (%d)\n",
371                         mdb_strerror(rc), rc, 0 );
372                 return rc;
373
374         } else if ( data.mv_size == 0 || data.mv_size % sizeof( ID ) ) {
375                 /* size not multiple of ID size */
376                 Debug( LDAP_DEBUG_ANY, "=> mdb_idl_fetch_key: "
377                         "odd size: expected %ld multiple, got %ld\n",
378                         (long) sizeof( ID ), (long) data.mv_size, 0 );
379                 return -1;
380
381         } else if ( data.mv_size != MDB_IDL_SIZEOF(ids) ) {
382                 /* size mismatch */
383                 Debug( LDAP_DEBUG_ANY, "=> mdb_idl_fetch_key: "
384                         "get size mismatch: expected %ld, got %ld\n",
385                         (long) ((1 + ids[0]) * sizeof( ID )), (long) data.mv_size, 0 );
386                 return -1;
387         }
388
389         return rc;
390 }
391
392 int
393 mdb_idl_insert_keys(
394         MDB_cursor      *cursor,
395         struct berval *keys,
396         ID                      id )
397 {
398         MDB_val key, data;
399         ID lo, hi, *i;
400         char *err;
401         int     rc, k;
402         unsigned int flag = MDB_NODUPDATA;
403
404         {
405                 char buf[16];
406                 Debug( LDAP_DEBUG_ARGS,
407                         "mdb_idl_insert_keys: %lx %s\n", 
408                         (long) id, mdb_show_key( buf, keys->bv_val, keys->bv_len ), 0 );
409         }
410
411         assert( id != NOID );
412
413         if ( slapMode & SLAP_TOOL_QUICK )
414                 flag |= MDB_APPEND;
415
416         for ( k=0; keys[k].bv_val; k++ ) {
417         /* Fetch the first data item for this key, to see if it
418          * exists and if it's a range.
419          */
420         key.mv_size = keys[k].bv_len;
421         key.mv_data = keys[k].bv_val;
422         rc = mdb_cursor_get( cursor, &key, &data, MDB_SET );
423         err = "c_get";
424         if ( rc == 0 ) {
425                 i = data.mv_data;
426                 memcpy(&lo, data.mv_data, sizeof(ID));
427                 if ( lo != 0 ) {
428                         /* not a range, count the number of items */
429                         size_t count;
430                         rc = mdb_cursor_count( cursor, &count );
431                         if ( rc != 0 ) {
432                                 err = "c_count";
433                                 goto fail;
434                         }
435                         if ( count >= MDB_IDL_DB_MAX ) {
436                         /* No room, convert to a range */
437                                 lo = *i;
438                                 rc = mdb_cursor_get( cursor, &key, &data, MDB_LAST_DUP );
439                                 if ( rc != 0 && rc != MDB_NOTFOUND ) {
440                                         err = "c_get last_dup";
441                                         goto fail;
442                                 }
443                                 i = data.mv_data;
444                                 hi = *i;
445                                 /* Update hi/lo if needed */
446                                 if ( id < lo ) {
447                                         lo = id;
448                                 } else if ( id > hi ) {
449                                         hi = id;
450                                 }
451                                 /* delete the old key */
452                                 rc = mdb_cursor_del( cursor, MDB_NODUPDATA );
453                                 if ( rc != 0 ) {
454                                         err = "c_del dups";
455                                         goto fail;
456                                 }
457                                 /* Store the range */
458                                 data.mv_size = sizeof(ID);
459                                 data.mv_data = &id;
460                                 id = 0;
461                                 rc = mdb_cursor_put( cursor, &key, &data, 0 );
462                                 if ( rc != 0 ) {
463                                         err = "c_put range";
464                                         goto fail;
465                                 }
466                                 id = lo;
467                                 rc = mdb_cursor_put( cursor, &key, &data, 0 );
468                                 if ( rc != 0 ) {
469                                         err = "c_put lo";
470                                         goto fail;
471                                 }
472                                 id = hi;
473                                 rc = mdb_cursor_put( cursor, &key, &data, 0 );
474                                 if ( rc != 0 ) {
475                                         err = "c_put hi";
476                                         goto fail;
477                                 }
478                         } else {
479                         /* There's room, just store it */
480                                 goto put1;
481                         }
482                 } else {
483                         /* It's a range, see if we need to rewrite
484                          * the boundaries
485                          */
486                         lo = i[1];
487                         hi = i[2];
488                         if ( id < lo || id > hi ) {
489                                 /* position on lo */
490                                 rc = mdb_cursor_get( cursor, &key, &data, MDB_NEXT_DUP );
491                                 if ( id > hi ) {
492                                         /* position on hi */
493                                         rc = mdb_cursor_get( cursor, &key, &data, MDB_NEXT_DUP );
494                                 }
495                                 data.mv_size = sizeof(ID);
496                                 data.mv_data = &id;
497                                 /* Replace the current lo/hi */
498                                 rc = mdb_cursor_put( cursor, &key, &data, MDB_CURRENT );
499                                 if ( rc != 0 ) {
500                                         err = "c_put lo/hi";
501                                         goto fail;
502                                 }
503                         }
504                 }
505         } else if ( rc == MDB_NOTFOUND ) {
506 put1:   data.mv_data = &id;
507                 data.mv_size = sizeof(ID);
508                 rc = mdb_cursor_put( cursor, &key, &data, flag );
509                 /* Don't worry if it's already there */
510                 if ( rc == MDB_KEYEXIST )
511                         rc = 0;
512                 if ( rc ) {
513                         err = "c_put id";
514                         goto fail;
515                 }
516         } else {
517                 /* initial c_get failed, nothing was done */
518 fail:
519                 Debug( LDAP_DEBUG_ANY, "=> mdb_idl_insert_keys: "
520                         "%s failed: %s (%d)\n", err, mdb_strerror(rc), rc );
521                 break;
522         }
523         }
524         return rc;
525 }
526
527 int
528 mdb_idl_delete_keys(
529         MDB_cursor      *cursor,
530         struct berval *keys,
531         ID                      id )
532 {
533         int     rc, k;
534         MDB_val key, data;
535         ID lo, hi, tmp, *i;
536         char *err;
537
538         {
539                 char buf[16];
540                 Debug( LDAP_DEBUG_ARGS,
541                         "mdb_idl_delete_keys: %lx %s\n", 
542                         (long) id, mdb_show_key( buf, keys->bv_val, keys->bv_len ), 0 );
543         }
544         assert( id != NOID );
545
546         for ( k=0; keys[k].bv_val; k++) {
547         /* Fetch the first data item for this key, to see if it
548          * exists and if it's a range.
549          */
550         key.mv_size = keys[k].bv_len;
551         key.mv_data = keys[k].bv_val;
552         rc = mdb_cursor_get( cursor, &key, &data, MDB_SET );
553         err = "c_get";
554         if ( rc == 0 ) {
555                 memcpy( &tmp, data.mv_data, sizeof(ID) );
556                 i = data.mv_data;
557                 if ( tmp != 0 ) {
558                         /* Not a range, just delete it */
559                         data.mv_data = &id;
560                         rc = mdb_cursor_get( cursor, &key, &data, MDB_GET_BOTH );
561                         if ( rc != 0 ) {
562                                 err = "c_get id";
563                                 goto fail;
564                         }
565                         rc = mdb_cursor_del( cursor, 0 );
566                         if ( rc != 0 ) {
567                                 err = "c_del id";
568                                 goto fail;
569                         }
570                 } else {
571                         /* It's a range, see if we need to rewrite
572                          * the boundaries
573                          */
574                         lo = i[1];
575                         hi = i[2];
576                         if ( id == lo || id == hi ) {
577                                 ID lo2 = lo, hi2 = hi;
578                                 if ( id == lo ) {
579                                         lo2++;
580                                 } else if ( id == hi ) {
581                                         hi2--;
582                                 }
583                                 if ( lo2 >= hi2 ) {
584                                 /* The range has collapsed... */
585                                         rc = mdb_cursor_del( cursor, MDB_NODUPDATA );
586                                         if ( rc != 0 ) {
587                                                 err = "c_del dup";
588                                                 goto fail;
589                                         }
590                                 } else {
591                                         /* position on lo */
592                                         rc = mdb_cursor_get( cursor, &key, &data, MDB_NEXT_DUP );
593                                         if ( id == lo )
594                                                 data.mv_data = &lo2;
595                                         else {
596                                                 /* position on hi */
597                                                 rc = mdb_cursor_get( cursor, &key, &data, MDB_NEXT_DUP );
598                                                 data.mv_data = &hi2;
599                                         }
600                                         /* Replace the current lo/hi */
601                                         data.mv_size = sizeof(ID);
602                                         rc = mdb_cursor_put( cursor, &key, &data, MDB_CURRENT );
603                                         if ( rc != 0 ) {
604                                                 err = "c_put lo/hi";
605                                                 goto fail;
606                                         }
607                                 }
608                         }
609                 }
610         } else {
611                 /* initial c_get failed, nothing was done */
612 fail:
613                 if ( rc == MDB_NOTFOUND )
614                         rc = 0;
615                 if ( rc ) {
616                         Debug( LDAP_DEBUG_ANY, "=> mdb_idl_delete_key: "
617                                 "%s failed: %s (%d)\n", err, mdb_strerror(rc), rc );
618                         break;
619                 }
620         }
621         }
622         return rc;
623 }
624
625
626 /*
627  * idl_intersection - return a = a intersection b
628  */
629 int
630 mdb_idl_intersection(
631         ID *a,
632         ID *b )
633 {
634         ID ida, idb;
635         ID idmax, idmin;
636         ID cursora = 0, cursorb = 0, cursorc;
637         int swap = 0;
638
639         if ( MDB_IDL_IS_ZERO( a ) || MDB_IDL_IS_ZERO( b ) ) {
640                 a[0] = 0;
641                 return 0;
642         }
643
644         idmin = IDL_MAX( MDB_IDL_FIRST(a), MDB_IDL_FIRST(b) );
645         idmax = IDL_MIN( MDB_IDL_LAST(a), MDB_IDL_LAST(b) );
646         if ( idmin > idmax ) {
647                 a[0] = 0;
648                 return 0;
649         } else if ( idmin == idmax ) {
650                 a[0] = 1;
651                 a[1] = idmin;
652                 return 0;
653         }
654
655         if ( MDB_IDL_IS_RANGE( a ) ) {
656                 if ( MDB_IDL_IS_RANGE(b) ) {
657                 /* If both are ranges, just shrink the boundaries */
658                         a[1] = idmin;
659                         a[2] = idmax;
660                         return 0;
661                 } else {
662                 /* Else swap so that b is the range, a is a list */
663                         ID *tmp = a;
664                         a = b;
665                         b = tmp;
666                         swap = 1;
667                 }
668         }
669
670         /* If a range completely covers the list, the result is
671          * just the list. If idmin to idmax is contiguous, just
672          * turn it into a range.
673          */
674         if ( MDB_IDL_IS_RANGE( b )
675                 && MDB_IDL_RANGE_FIRST( b ) <= MDB_IDL_RANGE_FIRST( a )
676                 && MDB_IDL_RANGE_LAST( b ) >= MDB_IDL_RANGE_LAST( a ) ) {
677                 if (idmax - idmin + 1 == a[0])
678                 {
679                         a[0] = NOID;
680                         a[1] = idmin;
681                         a[2] = idmax;
682                 }
683                 goto done;
684         }
685
686         /* Fine, do the intersection one element at a time.
687          * First advance to idmin in both IDLs.
688          */
689         cursora = cursorb = idmin;
690         ida = mdb_idl_first( a, &cursora );
691         idb = mdb_idl_first( b, &cursorb );
692         cursorc = 0;
693
694         while( ida <= idmax || idb <= idmax ) {
695                 if( ida == idb ) {
696                         a[++cursorc] = ida;
697                         ida = mdb_idl_next( a, &cursora );
698                         idb = mdb_idl_next( b, &cursorb );
699                 } else if ( ida < idb ) {
700                         ida = mdb_idl_next( a, &cursora );
701                 } else {
702                         idb = mdb_idl_next( b, &cursorb );
703                 }
704         }
705         a[0] = cursorc;
706 done:
707         if (swap)
708                 MDB_IDL_CPY( b, a );
709
710         return 0;
711 }
712
713
714 /*
715  * idl_union - return a = a union b
716  */
717 int
718 mdb_idl_union(
719         ID      *a,
720         ID      *b )
721 {
722         ID ida, idb;
723         ID cursora = 0, cursorb = 0, cursorc;
724
725         if ( MDB_IDL_IS_ZERO( b ) ) {
726                 return 0;
727         }
728
729         if ( MDB_IDL_IS_ZERO( a ) ) {
730                 MDB_IDL_CPY( a, b );
731                 return 0;
732         }
733
734         if ( MDB_IDL_IS_RANGE( a ) || MDB_IDL_IS_RANGE(b) ) {
735 over:           ida = IDL_MIN( MDB_IDL_FIRST(a), MDB_IDL_FIRST(b) );
736                 idb = IDL_MAX( MDB_IDL_LAST(a), MDB_IDL_LAST(b) );
737                 a[0] = NOID;
738                 a[1] = ida;
739                 a[2] = idb;
740                 return 0;
741         }
742
743         ida = mdb_idl_first( a, &cursora );
744         idb = mdb_idl_first( b, &cursorb );
745
746         cursorc = b[0];
747
748         /* The distinct elements of a are cat'd to b */
749         while( ida != NOID || idb != NOID ) {
750                 if ( ida < idb ) {
751                         if( ++cursorc > MDB_IDL_UM_MAX ) {
752                                 goto over;
753                         }
754                         b[cursorc] = ida;
755                         ida = mdb_idl_next( a, &cursora );
756
757                 } else {
758                         if ( ida == idb )
759                                 ida = mdb_idl_next( a, &cursora );
760                         idb = mdb_idl_next( b, &cursorb );
761                 }
762         }
763
764         /* b is copied back to a in sorted order */
765         a[0] = cursorc;
766         cursora = 1;
767         cursorb = 1;
768         cursorc = b[0]+1;
769         while (cursorb <= b[0] || cursorc <= a[0]) {
770                 if (cursorc > a[0])
771                         idb = NOID;
772                 else
773                         idb = b[cursorc];
774                 if (cursorb <= b[0] && b[cursorb] < idb)
775                         a[cursora++] = b[cursorb++];
776                 else {
777                         a[cursora++] = idb;
778                         cursorc++;
779                 }
780         }
781
782         return 0;
783 }
784
785
786 #if 0
787 /*
788  * mdb_idl_notin - return a intersection ~b (or a minus b)
789  */
790 int
791 mdb_idl_notin(
792         ID      *a,
793         ID      *b,
794         ID *ids )
795 {
796         ID ida, idb;
797         ID cursora = 0, cursorb = 0;
798
799         if( MDB_IDL_IS_ZERO( a ) ||
800                 MDB_IDL_IS_ZERO( b ) ||
801                 MDB_IDL_IS_RANGE( b ) )
802         {
803                 MDB_IDL_CPY( ids, a );
804                 return 0;
805         }
806
807         if( MDB_IDL_IS_RANGE( a ) ) {
808                 MDB_IDL_CPY( ids, a );
809                 return 0;
810         }
811
812         ida = mdb_idl_first( a, &cursora ),
813         idb = mdb_idl_first( b, &cursorb );
814
815         ids[0] = 0;
816
817         while( ida != NOID ) {
818                 if ( idb == NOID ) {
819                         /* we could shortcut this */
820                         ids[++ids[0]] = ida;
821                         ida = mdb_idl_next( a, &cursora );
822
823                 } else if ( ida < idb ) {
824                         ids[++ids[0]] = ida;
825                         ida = mdb_idl_next( a, &cursora );
826
827                 } else if ( ida > idb ) {
828                         idb = mdb_idl_next( b, &cursorb );
829
830                 } else {
831                         ida = mdb_idl_next( a, &cursora );
832                         idb = mdb_idl_next( b, &cursorb );
833                 }
834         }
835
836         return 0;
837 }
838 #endif
839
840 ID mdb_idl_first( ID *ids, ID *cursor )
841 {
842         ID pos;
843
844         if ( ids[0] == 0 ) {
845                 *cursor = NOID;
846                 return NOID;
847         }
848
849         if ( MDB_IDL_IS_RANGE( ids ) ) {
850                 if( *cursor < ids[1] ) {
851                         *cursor = ids[1];
852                 }
853                 return *cursor;
854         }
855
856         if ( *cursor == 0 )
857                 pos = 1;
858         else
859                 pos = mdb_idl_search( ids, *cursor );
860
861         if( pos > ids[0] ) {
862                 return NOID;
863         }
864
865         *cursor = pos;
866         return ids[pos];
867 }
868
869 ID mdb_idl_next( ID *ids, ID *cursor )
870 {
871         if ( MDB_IDL_IS_RANGE( ids ) ) {
872                 if( ids[2] < ++(*cursor) ) {
873                         return NOID;
874                 }
875                 return *cursor;
876         }
877
878         if ( ++(*cursor) <= ids[0] ) {
879                 return ids[*cursor];
880         }
881
882         return NOID;
883 }
884
885 /* Add one ID to an unsorted list. We ensure that the first element is the
886  * minimum and the last element is the maximum, for fast range compaction.
887  *   this means IDLs up to length 3 are always sorted...
888  */
889 int mdb_idl_append_one( ID *ids, ID id )
890 {
891         if (MDB_IDL_IS_RANGE( ids )) {
892                 /* if already in range, treat as a dup */
893                 if (id >= MDB_IDL_RANGE_FIRST(ids) && id <= MDB_IDL_RANGE_LAST(ids))
894                         return -1;
895                 if (id < MDB_IDL_RANGE_FIRST(ids))
896                         ids[1] = id;
897                 else if (id > MDB_IDL_RANGE_LAST(ids))
898                         ids[2] = id;
899                 return 0;
900         }
901         if ( ids[0] ) {
902                 ID tmp;
903
904                 if (id < ids[1]) {
905                         tmp = ids[1];
906                         ids[1] = id;
907                         id = tmp;
908                 }
909                 if ( ids[0] > 1 && id < ids[ids[0]] ) {
910                         tmp = ids[ids[0]];
911                         ids[ids[0]] = id;
912                         id = tmp;
913                 }
914         }
915         ids[0]++;
916         if ( ids[0] >= MDB_IDL_UM_MAX ) {
917                 ids[0] = NOID;
918                 ids[2] = id;
919         } else {
920                 ids[ids[0]] = id;
921         }
922         return 0;
923 }
924
925 /* Append sorted list b to sorted list a. The result is unsorted but
926  * a[1] is the min of the result and a[a[0]] is the max.
927  */
928 int mdb_idl_append( ID *a, ID *b )
929 {
930         ID ida, idb, tmp, swap = 0;
931
932         if ( MDB_IDL_IS_ZERO( b ) ) {
933                 return 0;
934         }
935
936         if ( MDB_IDL_IS_ZERO( a ) ) {
937                 MDB_IDL_CPY( a, b );
938                 return 0;
939         }
940
941         ida = MDB_IDL_LAST( a );
942         idb = MDB_IDL_LAST( b );
943         if ( MDB_IDL_IS_RANGE( a ) || MDB_IDL_IS_RANGE(b) ||
944                 a[0] + b[0] >= MDB_IDL_UM_MAX ) {
945                 a[2] = IDL_MAX( ida, idb );
946                 a[1] = IDL_MIN( a[1], b[1] );
947                 a[0] = NOID;
948                 return 0;
949         }
950
951         if ( b[0] > 1 && ida > idb ) {
952                 swap = idb;
953                 a[a[0]] = idb;
954                 b[b[0]] = ida;
955         }
956
957         if ( b[1] < a[1] ) {
958                 tmp = a[1];
959                 a[1] = b[1];
960         } else {
961                 tmp = b[1];
962         }
963         a[0]++;
964         a[a[0]] = tmp;
965
966         if ( b[0] > 1 ) {
967                 int i = b[0] - 1;
968                 AC_MEMCPY(a+a[0]+1, b+2, i * sizeof(ID));
969                 a[0] += i;
970         }
971         if ( swap ) {
972                 b[b[0]] = swap;
973         }
974         return 0;
975 }
976
977 #if 1
978
979 /* Quicksort + Insertion sort for small arrays */
980
981 #define SMALL   8
982 #define SWAP(a,b)       itmp=(a);(a)=(b);(b)=itmp
983
984 void
985 mdb_idl_sort( ID *ids, ID *tmp )
986 {
987         int *istack = (int *)tmp; /* Private stack, not used by caller */
988         int i,j,k,l,ir,jstack;
989         ID a, itmp;
990
991         if ( MDB_IDL_IS_RANGE( ids ))
992                 return;
993
994         ir = ids[0];
995         l = 1;
996         jstack = 0;
997         for(;;) {
998                 if (ir - l < SMALL) {   /* Insertion sort */
999                         for (j=l+1;j<=ir;j++) {
1000                                 a = ids[j];
1001                                 for (i=j-1;i>=1;i--) {
1002                                         if (ids[i] <= a) break;
1003                                         ids[i+1] = ids[i];
1004                                 }
1005                                 ids[i+1] = a;
1006                         }
1007                         if (jstack == 0) break;
1008                         ir = istack[jstack--];
1009                         l = istack[jstack--];
1010                 } else {
1011                         k = (l + ir) >> 1;      /* Choose median of left, center, right */
1012                         SWAP(ids[k], ids[l+1]);
1013                         if (ids[l] > ids[ir]) {
1014                                 SWAP(ids[l], ids[ir]);
1015                         }
1016                         if (ids[l+1] > ids[ir]) {
1017                                 SWAP(ids[l+1], ids[ir]);
1018                         }
1019                         if (ids[l] > ids[l+1]) {
1020                                 SWAP(ids[l], ids[l+1]);
1021                         }
1022                         i = l+1;
1023                         j = ir;
1024                         a = ids[l+1];
1025                         for(;;) {
1026                                 do i++; while(ids[i] < a);
1027                                 do j--; while(ids[j] > a);
1028                                 if (j < i) break;
1029                                 SWAP(ids[i],ids[j]);
1030                         }
1031                         ids[l+1] = ids[j];
1032                         ids[j] = a;
1033                         jstack += 2;
1034                         if (ir-i+1 >= j-1) {
1035                                 istack[jstack] = ir;
1036                                 istack[jstack-1] = i;
1037                                 ir = j-1;
1038                         } else {
1039                                 istack[jstack] = j-1;
1040                                 istack[jstack-1] = l;
1041                                 l = i;
1042                         }
1043                 }
1044         }
1045 }
1046
1047 #else
1048
1049 /* 8 bit Radix sort + insertion sort
1050  * 
1051  * based on code from http://www.cubic.org/docs/radix.htm
1052  * with improvements by mbackes@symas.com and hyc@symas.com
1053  *
1054  * This code is O(n) but has a relatively high constant factor. For lists
1055  * up to ~50 Quicksort is slightly faster; up to ~100 they are even.
1056  * Much faster than quicksort for lists longer than ~100. Insertion
1057  * sort is actually superior for lists <50.
1058  */
1059
1060 #define BUCKETS (1<<8)
1061 #define SMALL   50
1062
1063 void
1064 mdb_idl_sort( ID *ids, ID *tmp )
1065 {
1066         int count, soft_limit, phase = 0, size = ids[0];
1067         ID *idls[2];
1068         unsigned char *maxv = (unsigned char *)&ids[size];
1069
1070         if ( MDB_IDL_IS_RANGE( ids ))
1071                 return;
1072
1073         /* Use insertion sort for small lists */
1074         if ( size <= SMALL ) {
1075                 int i,j;
1076                 ID a;
1077
1078                 for (j=1;j<=size;j++) {
1079                         a = ids[j];
1080                         for (i=j-1;i>=1;i--) {
1081                                 if (ids[i] <= a) break;
1082                                 ids[i+1] = ids[i];
1083                         }
1084                         ids[i+1] = a;
1085                 }
1086                 return;
1087         }
1088
1089         tmp[0] = size;
1090         idls[0] = ids;
1091         idls[1] = tmp;
1092
1093 #if BYTE_ORDER == BIG_ENDIAN
1094     for (soft_limit = 0; !maxv[soft_limit]; soft_limit++);
1095 #else
1096     for (soft_limit = sizeof(ID)-1; !maxv[soft_limit]; soft_limit--);
1097 #endif
1098
1099         for (
1100 #if BYTE_ORDER == BIG_ENDIAN
1101         count = sizeof(ID)-1; count >= soft_limit; --count
1102 #else
1103         count = 0; count <= soft_limit; ++count
1104 #endif
1105         ) {
1106                 unsigned int num[BUCKETS], * np, n, sum;
1107                 int i;
1108         ID *sp, *source, *dest;
1109         unsigned char *bp, *source_start;
1110
1111                 source = idls[phase]+1;
1112                 dest = idls[phase^1]+1;
1113                 source_start =  ((unsigned char *) source) + count;
1114
1115         np = num;
1116         for ( i = BUCKETS; i > 0; --i ) *np++ = 0;
1117
1118                 /* count occurences of every byte value */
1119                 bp = source_start;
1120         for ( i = size; i > 0; --i, bp += sizeof(ID) )
1121                                 num[*bp]++;
1122
1123                 /* transform count into index by summing elements and storing
1124                  * into same array
1125                  */
1126         sum = 0;
1127         np = num;
1128         for ( i = BUCKETS; i > 0; --i ) {
1129                 n = *np;
1130                 *np++ = sum;
1131                 sum += n;
1132         }
1133
1134                 /* fill dest with the right values in the right place */
1135                 bp = source_start;
1136         sp = source;
1137         for ( i = size; i > 0; --i, bp += sizeof(ID) ) {
1138                 np = num + *bp;
1139                 dest[*np] = *sp++;
1140                 ++(*np);
1141         }
1142                 phase ^= 1;
1143         }
1144
1145         /* copy back from temp if needed */
1146         if ( phase ) {
1147                 ids++; tmp++;
1148                 for ( count = 0; count < size; ++count ) 
1149                         *ids++ = *tmp++;
1150         }
1151 }
1152 #endif  /* Quick vs Radix */
1153
1154 unsigned mdb_id2l_search( ID2L ids, ID id )
1155 {
1156         /*
1157          * binary search of id in ids
1158          * if found, returns position of id
1159          * if not found, returns first position greater than id
1160          */
1161         unsigned base = 0;
1162         unsigned cursor = 1;
1163         int val = 0;
1164         unsigned n = ids[0].mid;
1165
1166         while( 0 < n ) {
1167                 unsigned pivot = n >> 1;
1168                 cursor = base + pivot + 1;
1169                 val = IDL_CMP( id, ids[cursor].mid );
1170
1171                 if( val < 0 ) {
1172                         n = pivot;
1173
1174                 } else if ( val > 0 ) {
1175                         base = cursor;
1176                         n -= pivot + 1;
1177
1178                 } else {
1179                         return cursor;
1180                 }
1181         }
1182
1183         if( val > 0 ) {
1184                 ++cursor;
1185         }
1186         return cursor;
1187 }
1188
1189 int mdb_id2l_insert( ID2L ids, ID2 *id )
1190 {
1191         unsigned x, i;
1192
1193         x = mdb_id2l_search( ids, id->mid );
1194         assert( x > 0 );
1195
1196         if( x < 1 ) {
1197                 /* internal error */
1198                 return -2;
1199         }
1200
1201         if ( x <= ids[0].mid && ids[x].mid == id->mid ) {
1202                 /* duplicate */
1203                 return -1;
1204         }
1205
1206         if ( ids[0].mid >= MDB_IDL_UM_MAX ) {
1207                 /* too big */
1208                 return -2;
1209
1210         } else {
1211                 /* insert id */
1212                 ids[0].mid++;
1213                 for (i=ids[0].mid; i>x; i--)
1214                         ids[i] = ids[i-1];
1215                 ids[x] = *id;
1216         }
1217
1218         return 0;
1219 }