File: sl.c

package info (click to toggle)
libmaa 1.4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,040 kB
  • sloc: ansic: 6,172; perl: 235; makefile: 195; awk: 92; sh: 20
file content (483 lines) | stat: -rw-r--r-- 13,667 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/* sl.c -- Skip lists
 * Created: Sun Feb 18 11:51:06 1996 by faith@dict.org
 * Copyright 1996-1997, 2002 Rickard E. Faith (faith@dict.org)
 * Copyright 1996 Lars Nyland (nyland@cs.unc.edu)
 * Copyright 2002-2008 Aleksey Cheusov (vle@gmx.net)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 * \section{Skip List Routines}
 *
 * \intro Skip list support is provided as an alternative to balanced
 * trees.  Skip lists have the advantage that an inorder walk through the
 * list is possible in the face of additions and deletions from the list.
 * Balanced tree, algorithms, in contrast, make this sort of traversal
 * impossible because of the rotations that are necessary for the
 * balancing.
 *
 * For these lists, the |key| is derivable from the |datum| that is stored
 * in the list.  This makes it possible for the actualy keys to change, as
 * long as the ordering of the data stay the same.  This is essential for
 * the use of skip lists for \khepera trees.
 *
 * This code is derived from \cite{faith:Pugh90} and from a skip list
 * implementation by Lars Nyland.
 *
 */

#include "maaP.h"

#define SL_DEBUG 0		/* Debug like crazy */

typedef struct _sl_Entry {
#if MAA_MAGIC
   int              magic;
#endif
   const void       *datum;
#if SL_DEBUG
   int              levels;	/* levels for this entry */
#endif
   struct _sl_Entry *forward[1]; /* variable sized array */
} *_sl_Entry;

typedef struct _sl_List {
#if MAA_MAGIC
   unsigned         magic;
#endif
   int              level;
   int              count;	/* number of data */
   struct _sl_Entry *head;
   int              (*compare)( const void *key1, const void *key2 );
   const void       *(*key)( const void *datum );
   const char       *(*print)( const void *datum );
} *_sl_List;

static mem_Object _sl_Memory;

#define _sl_MaxLevel  16

#define PRINT(l,d) ((l)->print ? (l)->print(d) : _sl_print(d))

static void _sl_check_list( _sl_List l, const char *function )
{
   if (!l) err_internal( function, "skip list is null\n" );
#if MAA_MAGIC
   if (l->magic != SL_LIST_MAGIC)
      err_internal( function,
		    "Bad magic: 0x%08x (should be 0x%08x)\n",
		    l->magic,
		    SL_LIST_MAGIC );
#endif
}

#if !SL_DEBUG
#define _sl_check_entry(e,f)	/*  */
#else
static int _sl_check_entry( _sl_Entry e, const char *function )
{
   if (!e) err_internal( function, "entry is null\n" );
#if MAA_MAGIC
   if (e->magic != SL_ENTRY_MAGIC) {
      err_warning( function,
		   "Bad magic: 0x%08x (should be 0x%08x)\n",
		   e->magic,
		   SL_ENTRY_MAGIC );
      return 1;
   }
#endif
   return 0;
}
#endif

#if !SL_DEBUG
#define _sl_check(x) /* */
#else
static void _sl_check( sl_List list )
{
   _sl_List  l     = (_sl_List)list;
   int       count = 0;
   _sl_Entry pt;
   
   _sl_check_list( list, __func__ );
   for (pt = l->head->forward[0]; pt; pt = pt->forward[0] ) {
      ++count;
      if (pt && pt->forward[0]
	  && l->compare( l->key( pt->datum ),
			 l->key( pt->forward[0]->datum ) ) >= 0) {
	 _sl_dump( list );
	 err_internal( __func__,
		       "Datum 0x%p=%lu >= 0x%p=%lu\n",
		       l->key( pt->datum ),
		       (unsigned long)l->key( pt->datum ),
		       l->key( pt->forward[0]->datum ),
		       (unsigned long)l->key( pt->forward[0]->datum ) );
      }
   }
   if (count != l->count) {
      err_internal( __func__,
		    "Count should be %d instead of %d\n", count, l->count );
   }
}
#endif

static _sl_Entry _sl_create_entry( int maxLevel, const void *datum )
{
   _sl_Entry e;

   if (maxLevel > _sl_MaxLevel)
      err_internal( __func__,
		    "level %d > %d\n", maxLevel, _sl_MaxLevel );

   e = xmalloc( sizeof( struct _sl_Entry )
		+ (maxLevel + 1) * sizeof( _sl_Entry ) );
#if MAA_MAGIC
   e->magic  = SL_ENTRY_MAGIC;
#endif
   e->datum  = datum;
#if SL_DEBUG
   e->levels = maxLevel + 1;
#endif

   return e;
}

/* \doc |sl_create| initializes a skip list.  The |compare| function
   returns -1, 0, or 1 depending on the ordering of |key1| and |key2|.  The
   |key| function converts a |datum| into a |key|.  The |print| function
   returns a string representation of |datum|, and is allowed to always
   return a pointer to the same static buffer.

   |compare| must be provided.  If |key| is not provided, then |datum| will
   be used as the key.  If |print| is not provided, then the |datum|
   pointer will be printed when necessary. */


sl_List sl_create( int (*compare)( const void *key1, const void *key2 ),
		   const void *(*key)( const void *datum ),
		   const char *(*print)( const void *datum ) )
{
   _sl_List l;
   int      i;

   if (!_sl_Memory) {
      _sl_Memory = mem_create_objects( sizeof( struct _sl_List ) );
   }

   if (!compare)
      err_internal( __func__, "compare function is NULL\n" );
   if (!key)
      err_internal( __func__, "key function is NULL\n" );

   l          = mem_get_object( _sl_Memory );
#if MAA_MAGIC
   l->magic   = SL_LIST_MAGIC;
#endif
   l->level   = 0;
   l->head    = _sl_create_entry( _sl_MaxLevel, NULL );
   l->compare = compare;
   l->key     = key;
   l->print   = print;
   l->count   = 0;

   for (i = 0; i <= _sl_MaxLevel; i++) l->head->forward[i] = NULL;

   return l;
}

/* \doc |sl_destroy| removes all of the memory associated with the
   maintenance of the specified skip |list|.  The pointer to the
   user-defined |datum| is "not" freed -- this is the responsibility of the
   user. */

void sl_destroy( sl_List list )
{
   _sl_List  l = (_sl_List)list;
   _sl_Entry e;
   _sl_Entry next;

   _sl_check_list( list, __func__ );
   for (e = l->head; e; e = next) {
      next = e->forward[0];
#if MAA_MAGIC
      e->magic = SL_ENTRY_MAGIC_FREED;
#endif
      xfree( e );
   }
#if MAA_MAGIC
   l->magic = SL_LIST_MAGIC_FREED;
#endif
   mem_free_object( _sl_Memory, l );
}

/* \doc |_sl_shutdown| is used to free the internal data structures used by
   the skip list package.  Since it is called automatically by \libmaa, it
   should not be called explicitly by the user. */

void _sl_shutdown( void )
{
   if (_sl_Memory) mem_destroy_objects( _sl_Memory );
   _sl_Memory = NULL;
}

#if 0
static int rnd( void )		/* generate bit stream */
{
   static int i = 0;

   i = !i;
   return i;
}
#endif

static int _sl_random_level( void )
{
   int level = 1;
				/* FIXME! Assumes random() is.  We should
                                   use our own random() to make sure.  This
                                   also assumes that p == 0.5, which is
                                   probably reasonable, but maybe should be
                                   a user-defined parameter. */
   while ((random() & 0x80) &&  level < _sl_MaxLevel) ++level;
   return level;
}

static const char *_sl_print( const void *datum )
{
   static char buf[1024];

   sprintf( buf, "%p", datum );

   return buf;
}

static _sl_Entry _sl_locate( _sl_List l, const void *key, _sl_Entry update[] )
{
   int       i;
   _sl_Entry pt;
   
   _sl_check( l );
   for (i = l->level, pt = l->head; i >= 0; i--) {
      while (pt->forward[i]
	     && l->compare( l->key( pt->forward[i]->datum ), key ) < 0)
	 pt = pt->forward[i];
      update[i] = pt;
   }
   
   return pt->forward[0];
}


/* \doc Insert |datum| into |list|. */

void sl_insert( sl_List list, const void *datum )
{
   _sl_List         l = (_sl_List)list;
   _sl_Entry        update[_sl_MaxLevel + 1];
   _sl_Entry        pt;
   const void       *key;
   int              i;
   int              level = _sl_random_level();
   _sl_Entry        entry;

   _sl_check_list( list, __func__ );
   
   key = l->key( datum );

   pt = _sl_locate( l, key, update );

   if (pt && !l->compare( l->key( pt->datum ), key ))
      err_internal( __func__,
		    "Datum \"%s\" is already in list\n", PRINT(l,datum) );

   if (level > l->level) {
      level = ++l->level;
      update[level] = l->head;
   }
   
   entry = _sl_create_entry( level, datum );

				/* Fixup forward pointers */
   for (i = 0; i <= level; i++) {
      entry->forward[i]     = update[i]->forward[i];
      update[i]->forward[i] = entry;
   }

   ++l->count;
   _sl_check( list );
}

/* \doc Delete |datum| from |list|. */

void sl_delete( sl_List list, const void *datum )
{
   _sl_List         l = (_sl_List)list;
   _sl_Entry        update[_sl_MaxLevel + 1];
   _sl_Entry        pt;
   const void       *key;
   int              i;

   _sl_check_list( list, __func__ );
   
   key = l->key( datum );

   pt = _sl_locate( l, key, update );

   if (!pt || l->compare( l->key( pt->datum ), key )) {
      _sl_dump( list );
      err_internal( __func__,
		    "Datum \"%s\" is not in list\n", PRINT(l,datum) );
   }

				/* Fixup forward pointers */
   for (i = 0; i <= l->level; i++) {
      if (update[i]->forward[i] == pt)
	 update[i]->forward[i] = pt->forward[i];
   }
   
   xfree( pt );
   while (l->level && !l->head->forward[ l->level ])
      --l->level;
   --l->count;
   _sl_check( list );
}

/* \doc Find the datum in |list| that has an associated value of |key|.
   Return that datum (a pointer), or "NULL" if the |key| is not found. */

const void *sl_find( sl_List list, const void *key )
{
   _sl_List         l = (_sl_List)list;
   _sl_Entry        update[_sl_MaxLevel + 1];
   _sl_Entry        pt;

   _sl_check_list( list, __func__ );

   pt = _sl_locate( l, key, update );

   if (pt && !l->compare( l->key( pt->datum ), key )) return pt->datum;
   return NULL;
}

/* \doc Iterate |f| over every datum in |list|.  If |f| returns non-zero,
   then abort the remainder of the iteration.  Iterations are designed to
   do something appropriate in the face of arbitrary insertions and
   deletions performed by |f|. */

int sl_iterate( sl_List list, sl_Iterator f )
{
   _sl_List   l = (_sl_List)list;
   _sl_Entry  pt;
   int        retcode;
   int        count;
   int        i;
   const void **copy;
   

   if (!list) return 0;
   _sl_check_list( list, __func__ );

				/* WARNING! This *ASSUMES* that the data to
                                   the right of the current point will
                                   remain at its memory location during the
                                   walk.  Only memory locations for data to
                                   the left of the point may change! */
   count = l->count;
   copy = alloca( count * sizeof( void * ) );
   for (i = 0, pt = l->head->forward[0]; pt; i++, pt = pt->forward[0]) {
      copy[i] = pt->datum;
   }
   for (i = 0; i < count; i++) {
      if ((retcode = f( copy[i] ))) return retcode;
   }

   _sl_check( list );
   
   return 0;
}

/* \doc Iterate |f| over every datum in |list|.  If |f| returns non-zero,
   then abort the remainder of the iteration.  Iterations are designed to
   do something appropriate in the face of arbitrary insertions and
   deletions performed by |f|. */

int sl_iterate_arg( sl_List list, sl_IteratorArg f, void *arg )
{
   _sl_List   l = (_sl_List)list;
   _sl_Entry  pt;
   int        retcode;
   int        count;
   int        i;
   const void **copy;
   

   if (!list) return 0;
   _sl_check_list( list, __func__ );

				/* WARNING! This *ASSUMES* that the data to
                                   the right of the current point will
                                   remain at its memory location during the
                                   walk.  Only memory locations for data to
                                   the left of the point may change! */
   count = l->count;
   copy = alloca( count * sizeof( void * ) );
   for (i = 0, pt = l->head->forward[0]; pt; i++, pt = pt->forward[0]) {
      _sl_check_entry( pt, __func__ );
      copy[i] = pt->datum;
   }
   for (i = 0; i < count; i++) {
      if ((retcode = f( copy[i], arg ))) return retcode;
   }

   _sl_check( list );
   
   return 0;
}

/* \doc Dump the internal data structures associated with |list|.  This is
   purely for debugging. */

void _sl_dump( sl_List list )
{
   _sl_List  l = (_sl_List)list;
   _sl_Entry pt;
   int       count = 0;

   _sl_check_list( list, __func__ );

   printf( "Level = %d, count = %d\n", l->level, l->count );
   for (pt = l->head; pt; pt = pt->forward[0]) {
#if SL_DEBUG
      int       i;
      
      printf( "  Entry %p (%d/%p/0x%p=%lu) has 0x%x levels:\n",
	      pt, count++, pt->datum,
	      pt->datum ? l->key( pt->datum ) : 0,
	      (unsigned long)(pt->datum ? l->key( pt->datum ) : 0),
	      pt->levels );
      for (i = 0; i < pt->levels; i++)
	 printf( "    %p\n", pt->forward[i] );
#else
      printf( "  Entry %p (%d/%p/0x%p=%lu)\n",
	      (void *)pt, count++, pt->datum,
	      pt->datum ? l->key( pt->datum ) : 0,
	      (unsigned long)(pt->datum ? l->key( pt->datum ) : 0) );
#endif
   }
}