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