]> git.sur5r.net Git - openldap/blob - servers/slapd/back-mdb/idl.c
78ad09956b4571132f4f037456fa2be2fe27d002
[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-2012 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         BackendDB       *be,
395         MDB_cursor      *cursor,
396         struct berval *keys,
397         ID                      id )
398 {
399         struct mdb_info *mdb = be->be_private;
400         MDB_val key, data;
401         ID lo, hi, *i;
402         char *err;
403         int     rc = 0, k;
404         unsigned int flag = MDB_NODUPDATA;
405 #ifndef MISALIGNED_OK
406         int kbuf[2];
407 #endif
408
409         {
410                 char buf[16];
411                 Debug( LDAP_DEBUG_ARGS,
412                         "mdb_idl_insert_keys: %lx %s\n", 
413                         (long) id, mdb_show_key( buf, keys->bv_val, keys->bv_len ), 0 );
414         }
415
416         assert( id != NOID );
417
418 #ifndef MISALIGNED_OK
419         if (keys[0].bv_len & ALIGNER)
420                 kbuf[1] = 0;
421 #endif
422         for ( k=0; keys[k].bv_val; k++ ) {
423         /* Fetch the first data item for this key, to see if it
424          * exists and if it's a range.
425          */
426 #ifndef MISALIGNED_OK
427         if (keys[k].bv_len & ALIGNER) {
428                 key.mv_size = sizeof(kbuf);
429                 key.mv_data = kbuf;
430                 memcpy(key.mv_data, keys[k].bv_val, keys[k].bv_len);
431         } else
432 #endif
433         {
434                 key.mv_size = keys[k].bv_len;
435                 key.mv_data = keys[k].bv_val;
436         }
437         rc = mdb_cursor_get( cursor, &key, &data, MDB_SET );
438         err = "c_get";
439         if ( rc == 0 ) {
440                 i = data.mv_data;
441                 memcpy(&lo, data.mv_data, sizeof(ID));
442                 if ( lo != 0 ) {
443                         /* not a range, count the number of items */
444                         size_t count;
445                         rc = mdb_cursor_count( cursor, &count );
446                         if ( rc != 0 ) {
447                                 err = "c_count";
448                                 goto fail;
449                         }
450                         if ( count >= MDB_IDL_DB_MAX ) {
451                         /* No room, convert to a range */
452                                 lo = *i;
453                                 rc = mdb_cursor_get( cursor, &key, &data, MDB_LAST_DUP );
454                                 if ( rc != 0 && rc != MDB_NOTFOUND ) {
455                                         err = "c_get last_dup";
456                                         goto fail;
457                                 }
458                                 i = data.mv_data;
459                                 hi = *i;
460                                 /* Update hi/lo if needed */
461                                 if ( id < lo ) {
462                                         lo = id;
463                                 } else if ( id > hi ) {
464                                         hi = id;
465                                 }
466                                 /* delete the old key */
467                                 rc = mdb_cursor_del( cursor, MDB_NODUPDATA );
468                                 if ( rc != 0 ) {
469                                         err = "c_del dups";
470                                         goto fail;
471                                 }
472                                 /* Store the range */
473                                 data.mv_size = sizeof(ID);
474                                 data.mv_data = &id;
475                                 id = 0;
476                                 rc = mdb_cursor_put( cursor, &key, &data, 0 );
477                                 if ( rc != 0 ) {
478                                         err = "c_put range";
479                                         goto fail;
480                                 }
481                                 id = lo;
482                                 rc = mdb_cursor_put( cursor, &key, &data, 0 );
483                                 if ( rc != 0 ) {
484                                         err = "c_put lo";
485                                         goto fail;
486                                 }
487                                 id = hi;
488                                 rc = mdb_cursor_put( cursor, &key, &data, 0 );
489                                 if ( rc != 0 ) {
490                                         err = "c_put hi";
491                                         goto fail;
492                                 }
493                         } else {
494                         /* There's room, just store it */
495                                 if (id == mdb->mi_nextid)
496                                         flag |= MDB_APPENDDUP;
497                                 goto put1;
498                         }
499                 } else {
500                         /* It's a range, see if we need to rewrite
501                          * the boundaries
502                          */
503                         lo = i[1];
504                         hi = i[2];
505                         if ( id < lo || id > hi ) {
506                                 /* position on lo */
507                                 rc = mdb_cursor_get( cursor, &key, &data, MDB_NEXT_DUP );
508                                 if ( id > hi ) {
509                                         /* position on hi */
510                                         rc = mdb_cursor_get( cursor, &key, &data, MDB_NEXT_DUP );
511                                 }
512                                 data.mv_size = sizeof(ID);
513                                 data.mv_data = &id;
514                                 /* Replace the current lo/hi */
515                                 rc = mdb_cursor_put( cursor, &key, &data, MDB_CURRENT );
516                                 if ( rc != 0 ) {
517                                         err = "c_put lo/hi";
518                                         goto fail;
519                                 }
520                         }
521                 }
522         } else if ( rc == MDB_NOTFOUND ) {
523                 flag &= ~MDB_APPENDDUP;
524 put1:   data.mv_data = &id;
525                 data.mv_size = sizeof(ID);
526                 rc = mdb_cursor_put( cursor, &key, &data, flag );
527                 /* Don't worry if it's already there */
528                 if ( rc == MDB_KEYEXIST )
529                         rc = 0;
530                 if ( rc ) {
531                         err = "c_put id";
532                         goto fail;
533                 }
534         } else {
535                 /* initial c_get failed, nothing was done */
536 fail:
537                 Debug( LDAP_DEBUG_ANY, "=> mdb_idl_insert_keys: "
538                         "%s failed: %s (%d)\n", err, mdb_strerror(rc), rc );
539                 break;
540         }
541         }
542         return rc;
543 }
544
545 int
546 mdb_idl_delete_keys(
547         BackendDB       *be,
548         MDB_cursor      *cursor,
549         struct berval *keys,
550         ID                      id )
551 {
552         int     rc = 0, k;
553         MDB_val key, data;
554         ID lo, hi, tmp, *i;
555         char *err;
556 #ifndef MISALIGNED_OK
557         int kbuf[2];
558 #endif
559
560         {
561                 char buf[16];
562                 Debug( LDAP_DEBUG_ARGS,
563                         "mdb_idl_delete_keys: %lx %s\n", 
564                         (long) id, mdb_show_key( buf, keys->bv_val, keys->bv_len ), 0 );
565         }
566         assert( id != NOID );
567
568 #ifndef MISALIGNED_OK
569         if (keys[0].bv_len & ALIGNER)
570                 kbuf[1] = 0;
571 #endif
572         for ( k=0; keys[k].bv_val; k++) {
573         /* Fetch the first data item for this key, to see if it
574          * exists and if it's a range.
575          */
576 #ifndef MISALIGNED_OK
577         if (keys[k].bv_len & ALIGNER) {
578                 key.mv_size = sizeof(kbuf);
579                 key.mv_data = kbuf;
580                 memcpy(key.mv_data, keys[k].bv_val, keys[k].bv_len);
581         } else
582 #endif
583         {
584                 key.mv_size = keys[k].bv_len;
585                 key.mv_data = keys[k].bv_val;
586         }
587         rc = mdb_cursor_get( cursor, &key, &data, MDB_SET );
588         err = "c_get";
589         if ( rc == 0 ) {
590                 memcpy( &tmp, data.mv_data, sizeof(ID) );
591                 i = data.mv_data;
592                 if ( tmp != 0 ) {
593                         /* Not a range, just delete it */
594                         data.mv_data = &id;
595                         rc = mdb_cursor_get( cursor, &key, &data, MDB_GET_BOTH );
596                         if ( rc != 0 ) {
597                                 err = "c_get id";
598                                 goto fail;
599                         }
600                         rc = mdb_cursor_del( cursor, 0 );
601                         if ( rc != 0 ) {
602                                 err = "c_del id";
603                                 goto fail;
604                         }
605                 } else {
606                         /* It's a range, see if we need to rewrite
607                          * the boundaries
608                          */
609                         lo = i[1];
610                         hi = i[2];
611                         if ( id == lo || id == hi ) {
612                                 ID lo2 = lo, hi2 = hi;
613                                 if ( id == lo ) {
614                                         lo2++;
615                                 } else if ( id == hi ) {
616                                         hi2--;
617                                 }
618                                 if ( lo2 >= hi2 ) {
619                                 /* The range has collapsed... */
620                                         rc = mdb_cursor_del( cursor, MDB_NODUPDATA );
621                                         if ( rc != 0 ) {
622                                                 err = "c_del dup";
623                                                 goto fail;
624                                         }
625                                 } else {
626                                         /* position on lo */
627                                         rc = mdb_cursor_get( cursor, &key, &data, MDB_NEXT_DUP );
628                                         if ( id == lo )
629                                                 data.mv_data = &lo2;
630                                         else {
631                                                 /* position on hi */
632                                                 rc = mdb_cursor_get( cursor, &key, &data, MDB_NEXT_DUP );
633                                                 data.mv_data = &hi2;
634                                         }
635                                         /* Replace the current lo/hi */
636                                         data.mv_size = sizeof(ID);
637                                         rc = mdb_cursor_put( cursor, &key, &data, MDB_CURRENT );
638                                         if ( rc != 0 ) {
639                                                 err = "c_put lo/hi";
640                                                 goto fail;
641                                         }
642                                 }
643                         }
644                 }
645         } else {
646                 /* initial c_get failed, nothing was done */
647 fail:
648                 if ( rc == MDB_NOTFOUND )
649                         rc = 0;
650                 if ( rc ) {
651                         Debug( LDAP_DEBUG_ANY, "=> mdb_idl_delete_key: "
652                                 "%s failed: %s (%d)\n", err, mdb_strerror(rc), rc );
653                         break;
654                 }
655         }
656         }
657         return rc;
658 }
659
660
661 /*
662  * idl_intersection - return a = a intersection b
663  */
664 int
665 mdb_idl_intersection(
666         ID *a,
667         ID *b )
668 {
669         ID ida, idb;
670         ID idmax, idmin;
671         ID cursora = 0, cursorb = 0, cursorc;
672         int swap = 0;
673
674         if ( MDB_IDL_IS_ZERO( a ) || MDB_IDL_IS_ZERO( b ) ) {
675                 a[0] = 0;
676                 return 0;
677         }
678
679         idmin = IDL_MAX( MDB_IDL_FIRST(a), MDB_IDL_FIRST(b) );
680         idmax = IDL_MIN( MDB_IDL_LAST(a), MDB_IDL_LAST(b) );
681         if ( idmin > idmax ) {
682                 a[0] = 0;
683                 return 0;
684         } else if ( idmin == idmax ) {
685                 a[0] = 1;
686                 a[1] = idmin;
687                 return 0;
688         }
689
690         if ( MDB_IDL_IS_RANGE( a ) ) {
691                 if ( MDB_IDL_IS_RANGE(b) ) {
692                 /* If both are ranges, just shrink the boundaries */
693                         a[1] = idmin;
694                         a[2] = idmax;
695                         return 0;
696                 } else {
697                 /* Else swap so that b is the range, a is a list */
698                         ID *tmp = a;
699                         a = b;
700                         b = tmp;
701                         swap = 1;
702                 }
703         }
704
705         /* If a range completely covers the list, the result is
706          * just the list. If idmin to idmax is contiguous, just
707          * turn it into a range.
708          */
709         if ( MDB_IDL_IS_RANGE( b )
710                 && MDB_IDL_RANGE_FIRST( b ) <= MDB_IDL_RANGE_FIRST( a )
711                 && MDB_IDL_RANGE_LAST( b ) >= MDB_IDL_RANGE_LAST( a ) ) {
712                 if (idmax - idmin + 1 == a[0])
713                 {
714                         a[0] = NOID;
715                         a[1] = idmin;
716                         a[2] = idmax;
717                 }
718                 goto done;
719         }
720
721         /* Fine, do the intersection one element at a time.
722          * First advance to idmin in both IDLs.
723          */
724         cursora = cursorb = idmin;
725         ida = mdb_idl_first( a, &cursora );
726         idb = mdb_idl_first( b, &cursorb );
727         cursorc = 0;
728
729         while( ida <= idmax || idb <= idmax ) {
730                 if( ida == idb ) {
731                         a[++cursorc] = ida;
732                         ida = mdb_idl_next( a, &cursora );
733                         idb = mdb_idl_next( b, &cursorb );
734                 } else if ( ida < idb ) {
735                         ida = mdb_idl_next( a, &cursora );
736                 } else {
737                         idb = mdb_idl_next( b, &cursorb );
738                 }
739         }
740         a[0] = cursorc;
741 done:
742         if (swap)
743                 MDB_IDL_CPY( b, a );
744
745         return 0;
746 }
747
748
749 /*
750  * idl_union - return a = a union b
751  */
752 int
753 mdb_idl_union(
754         ID      *a,
755         ID      *b )
756 {
757         ID ida, idb;
758         ID cursora = 0, cursorb = 0, cursorc;
759
760         if ( MDB_IDL_IS_ZERO( b ) ) {
761                 return 0;
762         }
763
764         if ( MDB_IDL_IS_ZERO( a ) ) {
765                 MDB_IDL_CPY( a, b );
766                 return 0;
767         }
768
769         if ( MDB_IDL_IS_RANGE( a ) || MDB_IDL_IS_RANGE(b) ) {
770 over:           ida = IDL_MIN( MDB_IDL_FIRST(a), MDB_IDL_FIRST(b) );
771                 idb = IDL_MAX( MDB_IDL_LAST(a), MDB_IDL_LAST(b) );
772                 a[0] = NOID;
773                 a[1] = ida;
774                 a[2] = idb;
775                 return 0;
776         }
777
778         ida = mdb_idl_first( a, &cursora );
779         idb = mdb_idl_first( b, &cursorb );
780
781         cursorc = b[0];
782
783         /* The distinct elements of a are cat'd to b */
784         while( ida != NOID || idb != NOID ) {
785                 if ( ida < idb ) {
786                         if( ++cursorc > MDB_IDL_UM_MAX ) {
787                                 goto over;
788                         }
789                         b[cursorc] = ida;
790                         ida = mdb_idl_next( a, &cursora );
791
792                 } else {
793                         if ( ida == idb )
794                                 ida = mdb_idl_next( a, &cursora );
795                         idb = mdb_idl_next( b, &cursorb );
796                 }
797         }
798
799         /* b is copied back to a in sorted order */
800         a[0] = cursorc;
801         cursora = 1;
802         cursorb = 1;
803         cursorc = b[0]+1;
804         while (cursorb <= b[0] || cursorc <= a[0]) {
805                 if (cursorc > a[0])
806                         idb = NOID;
807                 else
808                         idb = b[cursorc];
809                 if (cursorb <= b[0] && b[cursorb] < idb)
810                         a[cursora++] = b[cursorb++];
811                 else {
812                         a[cursora++] = idb;
813                         cursorc++;
814                 }
815         }
816
817         return 0;
818 }
819
820
821 #if 0
822 /*
823  * mdb_idl_notin - return a intersection ~b (or a minus b)
824  */
825 int
826 mdb_idl_notin(
827         ID      *a,
828         ID      *b,
829         ID *ids )
830 {
831         ID ida, idb;
832         ID cursora = 0, cursorb = 0;
833
834         if( MDB_IDL_IS_ZERO( a ) ||
835                 MDB_IDL_IS_ZERO( b ) ||
836                 MDB_IDL_IS_RANGE( b ) )
837         {
838                 MDB_IDL_CPY( ids, a );
839                 return 0;
840         }
841
842         if( MDB_IDL_IS_RANGE( a ) ) {
843                 MDB_IDL_CPY( ids, a );
844                 return 0;
845         }
846
847         ida = mdb_idl_first( a, &cursora ),
848         idb = mdb_idl_first( b, &cursorb );
849
850         ids[0] = 0;
851
852         while( ida != NOID ) {
853                 if ( idb == NOID ) {
854                         /* we could shortcut this */
855                         ids[++ids[0]] = ida;
856                         ida = mdb_idl_next( a, &cursora );
857
858                 } else if ( ida < idb ) {
859                         ids[++ids[0]] = ida;
860                         ida = mdb_idl_next( a, &cursora );
861
862                 } else if ( ida > idb ) {
863                         idb = mdb_idl_next( b, &cursorb );
864
865                 } else {
866                         ida = mdb_idl_next( a, &cursora );
867                         idb = mdb_idl_next( b, &cursorb );
868                 }
869         }
870
871         return 0;
872 }
873 #endif
874
875 ID mdb_idl_first( ID *ids, ID *cursor )
876 {
877         ID pos;
878
879         if ( ids[0] == 0 ) {
880                 *cursor = NOID;
881                 return NOID;
882         }
883
884         if ( MDB_IDL_IS_RANGE( ids ) ) {
885                 if( *cursor < ids[1] ) {
886                         *cursor = ids[1];
887                 }
888                 return *cursor;
889         }
890
891         if ( *cursor == 0 )
892                 pos = 1;
893         else
894                 pos = mdb_idl_search( ids, *cursor );
895
896         if( pos > ids[0] ) {
897                 return NOID;
898         }
899
900         *cursor = pos;
901         return ids[pos];
902 }
903
904 ID mdb_idl_next( ID *ids, ID *cursor )
905 {
906         if ( MDB_IDL_IS_RANGE( ids ) ) {
907                 if( ids[2] < ++(*cursor) ) {
908                         return NOID;
909                 }
910                 return *cursor;
911         }
912
913         if ( ++(*cursor) <= ids[0] ) {
914                 return ids[*cursor];
915         }
916
917         return NOID;
918 }
919
920 /* Add one ID to an unsorted list. We ensure that the first element is the
921  * minimum and the last element is the maximum, for fast range compaction.
922  *   this means IDLs up to length 3 are always sorted...
923  */
924 int mdb_idl_append_one( ID *ids, ID id )
925 {
926         if (MDB_IDL_IS_RANGE( ids )) {
927                 /* if already in range, treat as a dup */
928                 if (id >= MDB_IDL_RANGE_FIRST(ids) && id <= MDB_IDL_RANGE_LAST(ids))
929                         return -1;
930                 if (id < MDB_IDL_RANGE_FIRST(ids))
931                         ids[1] = id;
932                 else if (id > MDB_IDL_RANGE_LAST(ids))
933                         ids[2] = id;
934                 return 0;
935         }
936         if ( ids[0] ) {
937                 ID tmp;
938
939                 if (id < ids[1]) {
940                         tmp = ids[1];
941                         ids[1] = id;
942                         id = tmp;
943                 }
944                 if ( ids[0] > 1 && id < ids[ids[0]] ) {
945                         tmp = ids[ids[0]];
946                         ids[ids[0]] = id;
947                         id = tmp;
948                 }
949         }
950         ids[0]++;
951         if ( ids[0] >= MDB_IDL_UM_MAX ) {
952                 ids[0] = NOID;
953                 ids[2] = id;
954         } else {
955                 ids[ids[0]] = id;
956         }
957         return 0;
958 }
959
960 /* Append sorted list b to sorted list a. The result is unsorted but
961  * a[1] is the min of the result and a[a[0]] is the max.
962  */
963 int mdb_idl_append( ID *a, ID *b )
964 {
965         ID ida, idb, tmp, swap = 0;
966
967         if ( MDB_IDL_IS_ZERO( b ) ) {
968                 return 0;
969         }
970
971         if ( MDB_IDL_IS_ZERO( a ) ) {
972                 MDB_IDL_CPY( a, b );
973                 return 0;
974         }
975
976         ida = MDB_IDL_LAST( a );
977         idb = MDB_IDL_LAST( b );
978         if ( MDB_IDL_IS_RANGE( a ) || MDB_IDL_IS_RANGE(b) ||
979                 a[0] + b[0] >= MDB_IDL_UM_MAX ) {
980                 a[2] = IDL_MAX( ida, idb );
981                 a[1] = IDL_MIN( a[1], b[1] );
982                 a[0] = NOID;
983                 return 0;
984         }
985
986         if ( b[0] > 1 && ida > idb ) {
987                 swap = idb;
988                 a[a[0]] = idb;
989                 b[b[0]] = ida;
990         }
991
992         if ( b[1] < a[1] ) {
993                 tmp = a[1];
994                 a[1] = b[1];
995         } else {
996                 tmp = b[1];
997         }
998         a[0]++;
999         a[a[0]] = tmp;
1000
1001         if ( b[0] > 1 ) {
1002                 int i = b[0] - 1;
1003                 AC_MEMCPY(a+a[0]+1, b+2, i * sizeof(ID));
1004                 a[0] += i;
1005         }
1006         if ( swap ) {
1007                 b[b[0]] = swap;
1008         }
1009         return 0;
1010 }
1011
1012 #if 1
1013
1014 /* Quicksort + Insertion sort for small arrays */
1015
1016 #define SMALL   8
1017 #define SWAP(a,b)       itmp=(a);(a)=(b);(b)=itmp
1018
1019 void
1020 mdb_idl_sort( ID *ids, ID *tmp )
1021 {
1022         int *istack = (int *)tmp; /* Private stack, not used by caller */
1023         int i,j,k,l,ir,jstack;
1024         ID a, itmp;
1025
1026         if ( MDB_IDL_IS_RANGE( ids ))
1027                 return;
1028
1029         ir = ids[0];
1030         l = 1;
1031         jstack = 0;
1032         for(;;) {
1033                 if (ir - l < SMALL) {   /* Insertion sort */
1034                         for (j=l+1;j<=ir;j++) {
1035                                 a = ids[j];
1036                                 for (i=j-1;i>=1;i--) {
1037                                         if (ids[i] <= a) break;
1038                                         ids[i+1] = ids[i];
1039                                 }
1040                                 ids[i+1] = a;
1041                         }
1042                         if (jstack == 0) break;
1043                         ir = istack[jstack--];
1044                         l = istack[jstack--];
1045                 } else {
1046                         k = (l + ir) >> 1;      /* Choose median of left, center, right */
1047                         SWAP(ids[k], ids[l+1]);
1048                         if (ids[l] > ids[ir]) {
1049                                 SWAP(ids[l], ids[ir]);
1050                         }
1051                         if (ids[l+1] > ids[ir]) {
1052                                 SWAP(ids[l+1], ids[ir]);
1053                         }
1054                         if (ids[l] > ids[l+1]) {
1055                                 SWAP(ids[l], ids[l+1]);
1056                         }
1057                         i = l+1;
1058                         j = ir;
1059                         a = ids[l+1];
1060                         for(;;) {
1061                                 do i++; while(ids[i] < a);
1062                                 do j--; while(ids[j] > a);
1063                                 if (j < i) break;
1064                                 SWAP(ids[i],ids[j]);
1065                         }
1066                         ids[l+1] = ids[j];
1067                         ids[j] = a;
1068                         jstack += 2;
1069                         if (ir-i+1 >= j-1) {
1070                                 istack[jstack] = ir;
1071                                 istack[jstack-1] = i;
1072                                 ir = j-1;
1073                         } else {
1074                                 istack[jstack] = j-1;
1075                                 istack[jstack-1] = l;
1076                                 l = i;
1077                         }
1078                 }
1079         }
1080 }
1081
1082 #else
1083
1084 /* 8 bit Radix sort + insertion sort
1085  * 
1086  * based on code from http://www.cubic.org/docs/radix.htm
1087  * with improvements by mbackes@symas.com and hyc@symas.com
1088  *
1089  * This code is O(n) but has a relatively high constant factor. For lists
1090  * up to ~50 Quicksort is slightly faster; up to ~100 they are even.
1091  * Much faster than quicksort for lists longer than ~100. Insertion
1092  * sort is actually superior for lists <50.
1093  */
1094
1095 #define BUCKETS (1<<8)
1096 #define SMALL   50
1097
1098 void
1099 mdb_idl_sort( ID *ids, ID *tmp )
1100 {
1101         int count, soft_limit, phase = 0, size = ids[0];
1102         ID *idls[2];
1103         unsigned char *maxv = (unsigned char *)&ids[size];
1104
1105         if ( MDB_IDL_IS_RANGE( ids ))
1106                 return;
1107
1108         /* Use insertion sort for small lists */
1109         if ( size <= SMALL ) {
1110                 int i,j;
1111                 ID a;
1112
1113                 for (j=1;j<=size;j++) {
1114                         a = ids[j];
1115                         for (i=j-1;i>=1;i--) {
1116                                 if (ids[i] <= a) break;
1117                                 ids[i+1] = ids[i];
1118                         }
1119                         ids[i+1] = a;
1120                 }
1121                 return;
1122         }
1123
1124         tmp[0] = size;
1125         idls[0] = ids;
1126         idls[1] = tmp;
1127
1128 #if BYTE_ORDER == BIG_ENDIAN
1129     for (soft_limit = 0; !maxv[soft_limit]; soft_limit++);
1130 #else
1131     for (soft_limit = sizeof(ID)-1; !maxv[soft_limit]; soft_limit--);
1132 #endif
1133
1134         for (
1135 #if BYTE_ORDER == BIG_ENDIAN
1136         count = sizeof(ID)-1; count >= soft_limit; --count
1137 #else
1138         count = 0; count <= soft_limit; ++count
1139 #endif
1140         ) {
1141                 unsigned int num[BUCKETS], * np, n, sum;
1142                 int i;
1143         ID *sp, *source, *dest;
1144         unsigned char *bp, *source_start;
1145
1146                 source = idls[phase]+1;
1147                 dest = idls[phase^1]+1;
1148                 source_start =  ((unsigned char *) source) + count;
1149
1150         np = num;
1151         for ( i = BUCKETS; i > 0; --i ) *np++ = 0;
1152
1153                 /* count occurences of every byte value */
1154                 bp = source_start;
1155         for ( i = size; i > 0; --i, bp += sizeof(ID) )
1156                                 num[*bp]++;
1157
1158                 /* transform count into index by summing elements and storing
1159                  * into same array
1160                  */
1161         sum = 0;
1162         np = num;
1163         for ( i = BUCKETS; i > 0; --i ) {
1164                 n = *np;
1165                 *np++ = sum;
1166                 sum += n;
1167         }
1168
1169                 /* fill dest with the right values in the right place */
1170                 bp = source_start;
1171         sp = source;
1172         for ( i = size; i > 0; --i, bp += sizeof(ID) ) {
1173                 np = num + *bp;
1174                 dest[*np] = *sp++;
1175                 ++(*np);
1176         }
1177                 phase ^= 1;
1178         }
1179
1180         /* copy back from temp if needed */
1181         if ( phase ) {
1182                 ids++; tmp++;
1183                 for ( count = 0; count < size; ++count ) 
1184                         *ids++ = *tmp++;
1185         }
1186 }
1187 #endif  /* Quick vs Radix */
1188
1189 unsigned mdb_id2l_search( ID2L ids, ID id )
1190 {
1191         /*
1192          * binary search of id in ids
1193          * if found, returns position of id
1194          * if not found, returns first position greater than id
1195          */
1196         unsigned base = 0;
1197         unsigned cursor = 1;
1198         int val = 0;
1199         unsigned n = ids[0].mid;
1200
1201         while( 0 < n ) {
1202                 unsigned pivot = n >> 1;
1203                 cursor = base + pivot + 1;
1204                 val = IDL_CMP( id, ids[cursor].mid );
1205
1206                 if( val < 0 ) {
1207                         n = pivot;
1208
1209                 } else if ( val > 0 ) {
1210                         base = cursor;
1211                         n -= pivot + 1;
1212
1213                 } else {
1214                         return cursor;
1215                 }
1216         }
1217
1218         if( val > 0 ) {
1219                 ++cursor;
1220         }
1221         return cursor;
1222 }
1223
1224 int mdb_id2l_insert( ID2L ids, ID2 *id )
1225 {
1226         unsigned x, i;
1227
1228         x = mdb_id2l_search( ids, id->mid );
1229         assert( x > 0 );
1230
1231         if( x < 1 ) {
1232                 /* internal error */
1233                 return -2;
1234         }
1235
1236         if ( x <= ids[0].mid && ids[x].mid == id->mid ) {
1237                 /* duplicate */
1238                 return -1;
1239         }
1240
1241         if ( ids[0].mid >= MDB_IDL_UM_MAX ) {
1242                 /* too big */
1243                 return -2;
1244
1245         } else {
1246                 /* insert id */
1247                 ids[0].mid++;
1248                 for (i=ids[0].mid; i>x; i--)
1249                         ids[i] = ids[i-1];
1250                 ids[x] = *id;
1251         }
1252
1253         return 0;
1254 }