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