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