forked from sparsehash/sparsehash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibchash.c
1538 lines (1380 loc) · 64.5 KB
/
libchash.c
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 1998 - 2005, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ---
* Author: Craig Silverstein
*
* This library is intended to be used for in-memory hash tables,
* though it provides rudimentary permanent-storage capabilities.
* It attempts to be fast, portable, and small. The best algorithm
* to fulfill these goals is an internal probing hashing algorithm,
* as in Knuth, _Art of Computer Programming_, vol III. Unlike
* chained (open) hashing, it doesn't require a pointer for every
* item, yet it is still constant time lookup in practice.
*
* Also to save space, we let the contents (both data and key) that
* you insert be a union: if the key/data is small, we store it
* directly in the hashtable, otherwise we store a pointer to it.
* To keep you from having to figure out which, use KEY_PTR and
* PTR_KEY to convert between the arguments to these functions and
* a pointer to the real data. For instance:
* char key[] = "ab", *key2;
* HTItem *bck; HashTable *ht;
* HashInsert(ht, PTR_KEY(ht, key), 0);
* bck = HashFind(ht, PTR_KEY(ht, "ab"));
* key2 = KEY_PTR(ht, bck->key);
*
* There are a rich set of operations supported:
* AllocateHashTable() -- Allocates a hashtable structure and
* returns it.
* cchKey: if it's a positive number, then each key is a
* fixed-length record of that length. If it's 0,
* the key is assumed to be a \0-terminated string.
* fSaveKey: normally, you are responsible for allocating
* space for the key. If this is 1, we make a
* copy of the key for you.
* ClearHashTable() -- Removes everything from a hashtable
* FreeHashTable() -- Frees memory used by a hashtable
*
* HashFind() -- takes a key (use PTR_KEY) and returns the
* HTItem containing that key, or NULL if the
* key is not in the hashtable.
* HashFindLast() -- returns the item found by last HashFind()
* HashFindOrInsert() -- inserts the key/data pair if the key
* is not already in the hashtable, or
* returns the appropraite HTItem if it is.
* HashFindOrInsertItem() -- takes key/data as an HTItem.
* HashInsert() -- adds a key/data pair to the hashtable. What
* it does if the key is already in the table
* depends on the value of SAMEKEY_OVERWRITE.
* HashInsertItem() -- takes key/data as an HTItem.
* HashDelete() -- removes a key/data pair from the hashtable,
* if it's there. RETURNS 1 if it was there,
* 0 else.
* If you use sparse tables and never delete, the full data
* space is available. Otherwise we steal -2 (maybe -3),
* so you can't have data fields with those values.
* HashDeleteLast() -- deletes the item returned by the last Find().
*
* HashFirstBucket() -- used to iterate over the buckets in a
* hashtable. DON'T INSERT OR DELETE WHILE
* ITERATING! You can't nest iterations.
* HashNextBucket() -- RETURNS NULL at the end of iterating.
*
* HashSetDeltaGoalSize() -- if you're going to insert 1000 items
* at once, call this fn with arg 1000.
* It grows the table more intelligently.
*
* HashSave() -- saves the hashtable to a file. It saves keys ok,
* but it doesn't know how to interpret the data field,
* so if the data field is a pointer to some complex
* structure, you must send a function that takes a
* file pointer and a pointer to the structure, and
* write whatever you want to write. It should return
* the number of bytes written. If the file is NULL,
* it should just return the number of bytes it would
* write, without writing anything.
* If your data field is just an integer, not a
* pointer, just send NULL for the function.
* HashLoad() -- loads a hashtable. It needs a function that takes
* a file and the size of the structure, and expects
* you to read in the structure and return a pointer
* to it. You must do memory allocation, etc. If
* the data is just a number, send NULL.
* HashLoadKeys() -- unlike HashLoad(), doesn't load the data off disk
* until needed. This saves memory, but if you look
* up the same key a lot, it does a disk access each
* time.
* You can't do Insert() or Delete() on hashtables that were loaded
* from disk.
*
* See libchash.h for parameters you can modify. Make sure LOG_WORD_SIZE
* is defined correctly for your machine! (5 for 32 bit words, 6 for 64).
*/
#include <sparsehash/internal/sparseconfig.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h> /* for strcmp, memcmp, etc */
#include <sys/types.h> /* ULTRIX needs this for in.h */
#include <netinet/in.h> /* for reading/writing hashtables */
#include <assert.h>
#include "libchash.h" /* all the types */
/* if keys are stored directly but cchKey is less than sizeof(ulong), */
/* this cuts off the bits at the end */
char grgKeyTruncMask[sizeof(ulong)][sizeof(ulong)];
#define KEY_TRUNC(ht, key) \
( STORES_PTR(ht) || (ht)->cchKey == sizeof(ulong) \
? (key) : ((key) & *(ulong *)&(grgKeyTruncMask[(ht)->cchKey][0])) )
/* round num up to a multiple of wordsize. (LOG_WORD_SIZE-3 is in bytes) */
#define WORD_ROUND(num) ( ((num-1) | ((1<<(LOG_WORD_SIZE-3))-1)) + 1 )
#define NULL_TERMINATED 0 /* val of cchKey if keys are null-term strings */
/* Useful operations we do to keys: compare them, copy them, free them */
#define KEY_CMP(ht, key1, key2) ( !STORES_PTR(ht) ? (key1) - (key2) : \
(key1) == (key2) ? 0 : \
HashKeySize(ht) == NULL_TERMINATED ? \
strcmp((char *)key1, (char *)key2) :\
memcmp((void *)key1, (void *)key2, \
HashKeySize(ht)) )
#define COPY_KEY(ht, keyTo, keyFrom) do \
if ( !STORES_PTR(ht) || !(ht)->fSaveKeys ) \
(keyTo) = (keyFrom); /* just copy pointer or info */\
else if ( (ht)->cchKey == NULL_TERMINATED ) /* copy 0-term.ed str */\
{ \
(keyTo) = (ulong)HTsmalloc( WORD_ROUND(strlen((char *)(keyFrom))+1) ); \
strcpy((char *)(keyTo), (char *)(keyFrom)); \
} \
else \
{ \
(keyTo) = (ulong) HTsmalloc( WORD_ROUND((ht)->cchKey) ); \
memcpy( (char *)(keyTo), (char *)(keyFrom), (ht)->cchKey); \
} \
while ( 0 )
#define FREE_KEY(ht, key) do \
if ( STORES_PTR(ht) && (ht)->fSaveKeys ) \
if ( (ht)->cchKey == NULL_TERMINATED ) \
HTfree((char *)(key), WORD_ROUND(strlen((char *)(key))+1)); \
else \
HTfree((char *)(key), WORD_ROUND((ht)->cchKey)); \
while ( 0 )
/* the following are useful for bitmaps */
/* Format is like this (if 1 word = 4 bits): 3210 7654 ba98 fedc ... */
typedef ulong HTBitmapPart; /* this has to be unsigned, for >> */
typedef HTBitmapPart HTBitmap[1<<LOG_BM_WORDS];
typedef ulong HTOffset; /* something big enough to hold offsets */
#define BM_BYTES(cBuckets) /* we must ensure it's a multiple of word size */\
( (((cBuckets) + 8*sizeof(ulong)-1) >> LOG_WORD_SIZE) << (LOG_WORD_SIZE-3) )
#define MOD2(i, logmod) ( (i) & ((1<<(logmod))-1) )
#define DIV_NUM_ENTRIES(i) ( (i) >> LOG_WORD_SIZE )
#define MOD_NUM_ENTRIES(i) ( MOD2(i, LOG_WORD_SIZE) )
#define MODBIT(i) ( ((ulong)1) << MOD_NUM_ENTRIES(i) )
#define TEST_BITMAP(bm, i) ( (bm)[DIV_NUM_ENTRIES(i)] & MODBIT(i) ? 1 : 0 )
#define SET_BITMAP(bm, i) (bm)[DIV_NUM_ENTRIES(i)] |= MODBIT(i)
#define CLEAR_BITMAP(bm, i) (bm)[DIV_NUM_ENTRIES(i)] &= ~MODBIT(i)
/* the following are useful for reading and writing hashtables */
#define READ_UL(fp, data) \
do { \
long _ul; \
fread(&_ul, sizeof(_ul), 1, (fp)); \
data = ntohl(_ul); \
} while (0)
#define WRITE_UL(fp, data) \
do { \
long _ul = htonl((long)(data)); \
fwrite(&_ul, sizeof(_ul), 1, (fp)); \
} while (0)
/* Moves data from disk to memory if necessary. Note dataRead cannot be *
* NULL, because then we might as well (and do) load the data into memory */
#define LOAD_AND_RETURN(ht, loadCommand) /* lC returns an HTItem * */ \
if ( !(ht)->fpData ) /* data is stored in memory */ \
return (loadCommand); \
else /* must read data off of disk */ \
{ \
int cchData; \
HTItem *bck; \
if ( (ht)->bckData.data ) free((char *)(ht)->bckData.data); \
ht->bckData.data = (ulong)NULL; /* needed if loadCommand fails */ \
bck = (loadCommand); \
if ( bck == NULL ) /* loadCommand failed: key not found */ \
return NULL; \
else \
(ht)->bckData = *bck; \
fseek(ht->fpData, (ht)->bckData.data, SEEK_SET); \
READ_UL((ht)->fpData, cchData); \
(ht)->bckData.data = (ulong)(ht)->dataRead((ht)->fpData, cchData); \
return &((ht)->bckData); \
}
/* ======================================================================== */
/* UTILITY ROUTINES */
/* ---------------------- */
/* HTsmalloc() -- safe malloc
* allocates memory, or crashes if the allocation fails.
*/
static void *HTsmalloc(unsigned long size)
{
void *retval;
if ( size == 0 )
return NULL;
retval = (void *)malloc(size);
if ( !retval )
{
fprintf(stderr, "HTsmalloc: Unable to allocate %lu bytes of memory\n",
size);
exit(1);
}
return retval;
}
/* HTscalloc() -- safe calloc
* allocates memory and initializes it to 0, or crashes if
* the allocation fails.
*/
static void *HTscalloc(unsigned long size)
{
void *retval;
retval = (void *)calloc(size, 1);
if ( !retval && size > 0 )
{
fprintf(stderr, "HTscalloc: Unable to allocate %lu bytes of memory\n",
size);
exit(1);
}
return retval;
}
/* HTsrealloc() -- safe calloc
* grows the amount of memory from a source, or crashes if
* the allocation fails.
*/
static void *HTsrealloc(void *ptr, unsigned long new_size, long delta)
{
if ( ptr == NULL )
return HTsmalloc(new_size);
ptr = realloc(ptr, new_size);
if ( !ptr && new_size > 0 )
{
fprintf(stderr, "HTsrealloc: Unable to reallocate %lu bytes of memory\n",
new_size);
exit(1);
}
return ptr;
}
/* HTfree() -- keep track of memory use
* frees memory using free, but updates count of how much memory
* is being used.
*/
static void HTfree(void *ptr, unsigned long size)
{
if ( size > 0 ) /* some systems seem to not like freeing NULL */
free(ptr);
}
/*************************************************************************\
| HTcopy() |
| Sometimes we interpret data as a ulong. But ulongs must be |
| aligned on some machines, so instead of casting we copy. |
\*************************************************************************/
unsigned long HTcopy(char *ul)
{
unsigned long retval;
memcpy(&retval, ul, sizeof(retval));
return retval;
}
/*************************************************************************\
| HTSetupKeyTrunc() |
| If keys are stored directly but cchKey is less than |
| sizeof(ulong), this cuts off the bits at the end. |
\*************************************************************************/
static void HTSetupKeyTrunc(void)
{
int i, j;
for ( i = 0; i < sizeof(unsigned long); i++ )
for ( j = 0; j < sizeof(unsigned long); j++ )
grgKeyTruncMask[i][j] = j < i ? 255 : 0; /* chars have 8 bits */
}
/* ======================================================================== */
/* TABLE ROUTINES */
/* -------------------- */
/* The idea is that a hashtable with (logically) t buckets is divided
* into t/M groups of M buckets each. (M is a constant set in
* LOG_BM_WORDS for efficiency.) Each group is stored sparsely.
* Thus, inserting into the table causes some array to grow, which is
* slow but still constant time. Lookup involves doing a
* logical-position-to-sparse-position lookup, which is also slow but
* constant time. The larger M is, the slower these operations are
* but the less overhead (slightly).
*
* To store the sparse array, we store a bitmap B, where B[i] = 1 iff
* bucket i is non-empty. Then to look up bucket i we really look up
* array[# of 1s before i in B]. This is constant time for fixed M.
*
* Terminology: the position of an item in the overall table (from
* 1 .. t) is called its "location." The logical position in a group
* (from 1 .. M ) is called its "position." The actual location in
* the array (from 1 .. # of non-empty buckets in the group) is
* called its "offset."
*
* The following operations are supported:
* o Allocate an array with t buckets, all empty
* o Free a array (but not whatever was stored in the buckets)
* o Tell whether or not a bucket is empty
* o Return a bucket with a given location
* o Set the value of a bucket at a given location
* o Iterate through all the buckets in the array
* o Read and write an occupancy bitmap to disk
* o Return how much memory is being allocated by the array structure
*/
#ifndef SparseBucket /* by default, each bucket holds an HTItem */
#define SparseBucket HTItem
#endif
typedef struct SparseBin {
SparseBucket *binSparse;
HTBitmap bmOccupied; /* bmOccupied[i] is 1 if bucket i has an item */
short cOccupied; /* size of binSparse; useful for iterators, eg */
} SparseBin;
typedef struct SparseIterator {
long posGroup;
long posOffset;
SparseBin *binSparse; /* state info, to avoid args for NextBucket() */
ulong cBuckets;
} SparseIterator;
#define LOG_LOW_BIN_SIZE ( LOG_BM_WORDS+LOG_WORD_SIZE )
#define SPARSE_GROUPS(cBuckets) ( (((cBuckets)-1) >> LOG_LOW_BIN_SIZE) + 1 )
/* we need a small function to figure out # of items set in the bm */
static HTOffset EntriesUpto(HTBitmapPart *bm, int i)
{ /* returns # of set bits in 0..i-1 */
HTOffset retval = 0;
static HTOffset rgcBits[256] = /* # of bits set in one char */
{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8};
if ( i == 0 ) return 0;
for ( ; i > sizeof(*bm)*8; i -= sizeof(*bm)*8, bm++ )
{ /* think of it as loop unrolling */
#if LOG_WORD_SIZE >= 3 /* 1 byte per word, or more */
retval += rgcBits[*bm & 255]; /* get the low byte */
#if LOG_WORD_SIZE >= 4 /* at least 2 bytes */
retval += rgcBits[(*bm >> 8) & 255];
#if LOG_WORD_SIZE >= 5 /* at least 4 bytes */
retval += rgcBits[(*bm >> 16) & 255];
retval += rgcBits[(*bm >> 24) & 255];
#if LOG_WORD_SIZE >= 6 /* 8 bytes! */
retval += rgcBits[(*bm >> 32) & 255];
retval += rgcBits[(*bm >> 40) & 255];
retval += rgcBits[(*bm >> 48) & 255];
retval += rgcBits[(*bm >> 56) & 255];
#if LOG_WORD_SIZE >= 7 /* not a concern for a while... */
#error Need to rewrite EntriesUpto to support such big words
#endif /* >8 bytes */
#endif /* 8 bytes */
#endif /* 4 bytes */
#endif /* 2 bytes */
#endif /* 1 byte */
}
switch ( i ) { /* from 0 to 63 */
case 0:
return retval;
#if LOG_WORD_SIZE >= 3 /* 1 byte per word, or more */
case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
return (retval + rgcBits[*bm & ((1 << i)-1)]);
#if LOG_WORD_SIZE >= 4 /* at least 2 bytes */
case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16:
return (retval + rgcBits[*bm & 255] +
rgcBits[(*bm >> 8) & ((1 << (i-8))-1)]);
#if LOG_WORD_SIZE >= 5 /* at least 4 bytes */
case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24:
return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] +
rgcBits[(*bm >> 16) & ((1 << (i-16))-1)]);
case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32:
return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] +
rgcBits[(*bm >> 16) & 255] +
rgcBits[(*bm >> 24) & ((1 << (i-24))-1)]);
#if LOG_WORD_SIZE >= 6 /* 8 bytes! */
case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40:
return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] +
rgcBits[(*bm >> 16) & 255] + rgcBits[(*bm >> 24) & 255] +
rgcBits[(*bm >> 32) & ((1 << (i-32))-1)]);
case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48:
return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] +
rgcBits[(*bm >> 16) & 255] + rgcBits[(*bm >> 24) & 255] +
rgcBits[(*bm >> 32) & 255] +
rgcBits[(*bm >> 40) & ((1 << (i-40))-1)]);
case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56:
return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] +
rgcBits[(*bm >> 16) & 255] + rgcBits[(*bm >> 24) & 255] +
rgcBits[(*bm >> 32) & 255] + rgcBits[(*bm >> 40) & 255] +
rgcBits[(*bm >> 48) & ((1 << (i-48))-1)]);
case 57: case 58: case 59: case 60: case 61: case 62: case 63: case 64:
return (retval + rgcBits[*bm & 255] + rgcBits[(*bm >> 8) & 255] +
rgcBits[(*bm >> 16) & 255] + rgcBits[(*bm >> 24) & 255] +
rgcBits[(*bm >> 32) & 255] + rgcBits[(*bm >> 40) & 255] +
rgcBits[(*bm >> 48) & 255] +
rgcBits[(*bm >> 56) & ((1 << (i-56))-1)]);
#endif /* 8 bytes */
#endif /* 4 bytes */
#endif /* 2 bytes */
#endif /* 1 byte */
}
assert("" == "word size is too big in EntriesUpto()");
return -1;
}
#define SPARSE_POS_TO_OFFSET(bm, i) ( EntriesUpto(&((bm)[0]), i) )
#define SPARSE_BUCKET(bin, location) \
( (bin)[(location) >> LOG_LOW_BIN_SIZE].binSparse + \
SPARSE_POS_TO_OFFSET((bin)[(location)>>LOG_LOW_BIN_SIZE].bmOccupied, \
MOD2(location, LOG_LOW_BIN_SIZE)) )
/*************************************************************************\
| SparseAllocate() |
| SparseFree() |
| Allocates, sets-to-empty, and frees a sparse array. All you need |
| to tell me is how many buckets you want. I return the number of |
| buckets I actually allocated, setting the array as a parameter. |
| Note that you have to set auxilliary parameters, like cOccupied. |
\*************************************************************************/
static ulong SparseAllocate(SparseBin **pbinSparse, ulong cBuckets)
{
int cGroups = SPARSE_GROUPS(cBuckets);
*pbinSparse = (SparseBin *) HTscalloc(sizeof(**pbinSparse) * cGroups);
return cGroups << LOG_LOW_BIN_SIZE;
}
static SparseBin *SparseFree(SparseBin *binSparse, ulong cBuckets)
{
ulong iGroup, cGroups = SPARSE_GROUPS(cBuckets);
for ( iGroup = 0; iGroup < cGroups; iGroup++ )
HTfree(binSparse[iGroup].binSparse, (sizeof(*binSparse[iGroup].binSparse)
* binSparse[iGroup].cOccupied));
HTfree(binSparse, sizeof(*binSparse) * cGroups);
return NULL;
}
/*************************************************************************\
| SparseIsEmpty() |
| SparseFind() |
| You give me a location (ie a number between 1 and t), and I |
| return the bucket at that location, or NULL if the bucket is |
| empty. It's OK to call Find() on an empty table. |
\*************************************************************************/
static int SparseIsEmpty(SparseBin *binSparse, ulong location)
{
return !TEST_BITMAP(binSparse[location>>LOG_LOW_BIN_SIZE].bmOccupied,
MOD2(location, LOG_LOW_BIN_SIZE));
}
static SparseBucket *SparseFind(SparseBin *binSparse, ulong location)
{
if ( SparseIsEmpty(binSparse, location) )
return NULL;
return SPARSE_BUCKET(binSparse, location);
}
/*************************************************************************\
| SparseInsert() |
| You give me a location, and contents to put there, and I insert |
| into that location and RETURN a pointer to the location. If |
| bucket was already occupied, I write over the contents only if |
| *pfOverwrite is 1. We set *pfOverwrite to 1 if there was someone |
| there (whether or not we overwrote) and 0 else. |
\*************************************************************************/
static SparseBucket *SparseInsert(SparseBin *binSparse, SparseBucket *bckInsert,
ulong location, int *pfOverwrite)
{
SparseBucket *bckPlace;
HTOffset offset;
bckPlace = SparseFind(binSparse, location);
if ( bckPlace ) /* means we replace old contents */
{
if ( *pfOverwrite )
*bckPlace = *bckInsert;
*pfOverwrite = 1;
return bckPlace;
}
binSparse += (location >> LOG_LOW_BIN_SIZE);
offset = SPARSE_POS_TO_OFFSET(binSparse->bmOccupied,
MOD2(location, LOG_LOW_BIN_SIZE));
binSparse->binSparse = (SparseBucket *)
HTsrealloc(binSparse->binSparse,
sizeof(*binSparse->binSparse) * ++binSparse->cOccupied,
sizeof(*binSparse->binSparse));
memmove(binSparse->binSparse + offset+1,
binSparse->binSparse + offset,
(binSparse->cOccupied-1 - offset) * sizeof(*binSparse->binSparse));
binSparse->binSparse[offset] = *bckInsert;
SET_BITMAP(binSparse->bmOccupied, MOD2(location, LOG_LOW_BIN_SIZE));
*pfOverwrite = 0;
return binSparse->binSparse + offset;
}
/*************************************************************************\
| SparseFirstBucket() |
| SparseNextBucket() |
| SparseCurrentBit() |
| Iterate through the occupied buckets of a dense hashtable. You |
| must, of course, have allocated space yourself for the iterator. |
\*************************************************************************/
static SparseBucket *SparseNextBucket(SparseIterator *iter)
{
if ( iter->posOffset != -1 && /* not called from FirstBucket()? */
(++iter->posOffset < iter->binSparse[iter->posGroup].cOccupied) )
return iter->binSparse[iter->posGroup].binSparse + iter->posOffset;
iter->posOffset = 0; /* start the next group */
for ( iter->posGroup++; iter->posGroup < SPARSE_GROUPS(iter->cBuckets);
iter->posGroup++ )
if ( iter->binSparse[iter->posGroup].cOccupied > 0 )
return iter->binSparse[iter->posGroup].binSparse; /* + 0 */
return NULL; /* all remaining groups were empty */
}
static SparseBucket *SparseFirstBucket(SparseIterator *iter,
SparseBin *binSparse, ulong cBuckets)
{
iter->binSparse = binSparse; /* set it up for NextBucket() */
iter->cBuckets = cBuckets;
iter->posOffset = -1; /* when we advance, we're at 0 */
iter->posGroup = -1;
return SparseNextBucket(iter);
}
/*************************************************************************\
| SparseWrite() |
| SparseRead() |
| These are routines for storing a sparse hashtable onto disk. We |
| store the number of buckets and a bitmap indicating which buckets |
| are allocated (occupied). The actual contents of the buckets |
| must be stored separately. |
\*************************************************************************/
static void SparseWrite(FILE *fp, SparseBin *binSparse, ulong cBuckets)
{
ulong i, j;
WRITE_UL(fp, cBuckets);
for ( i = 0; i < SPARSE_GROUPS(cBuckets); i++ )
for ( j = 0; j < (1<<LOG_BM_WORDS); j++ )
WRITE_UL(fp, binSparse[i].bmOccupied[j]);
}
static ulong SparseRead(FILE *fp, SparseBin **pbinSparse)
{
ulong i, j, cBuckets;
READ_UL(fp, cBuckets); /* actually, cBuckets is stored */
cBuckets = SparseAllocate(pbinSparse, cBuckets);
for ( i = 0; i < SPARSE_GROUPS(cBuckets); i++ )
{
for ( j = 0; j < (1<<LOG_BM_WORDS); j++ )
READ_UL(fp, (*pbinSparse)[i].bmOccupied[j]);
(*pbinSparse)[i].cOccupied =
SPARSE_POS_TO_OFFSET((*pbinSparse)[i].bmOccupied,1<<LOG_LOW_BIN_SIZE);
(*pbinSparse)[i].binSparse =
(SparseBucket *) HTsmalloc(sizeof(*((*pbinSparse)[i].binSparse)) *
(*pbinSparse)[i].cOccupied);
}
return cBuckets;
}
/*************************************************************************\
| SparseMemory() |
| SparseMemory() tells us how much memory is being allocated for |
| the dense table. You need to tell me not only how many buckets |
| there are, but how many are occupied. |
\*************************************************************************/
static ulong SparseMemory(ulong cBuckets, ulong cOccupied)
{
return ( cOccupied * sizeof(SparseBucket) +
SPARSE_GROUPS(cBuckets) * sizeof(SparseBin) );
}
/* Just for fun, I also provide support for dense tables. These are
* just regulr arrays. Access is fast, but they can get big.
* Use Table(x) at the top of chash.h to decide which you want.
* A disadvantage is we need to steal more of the data space for
* indicating empty buckets. We choose -3.
*/
#ifndef DenseBucket /* by default, each bucket holds an HTItem */
#define DenseBucket HTItem
#endif
typedef struct DenseBin { /* needs to be a struct for C typing reasons */
DenseBucket *rgBuckets; /* A bin is an array of buckets */
} DenseBin;
typedef struct DenseIterator {
long pos; /* the actual iterator */
DenseBin *bin; /* state info, to avoid args for NextBucket() */
ulong cBuckets;
} DenseIterator;
#define DENSE_IS_EMPTY(bin, i) ( (bin)[i].data == EMPTY )
#define DENSE_SET_EMPTY(bin, i) (bin)[i].data = EMPTY /* fks-hash.h */
#define DENSE_SET_OCCUPIED(bin, i) (bin)[i].data = 1 /* not EMPTY */
static void DenseClear(DenseBin *bin, ulong cBuckets)
{
while ( cBuckets-- )
DENSE_SET_EMPTY(bin->rgBuckets, cBuckets);
}
static ulong DenseAllocate(DenseBin **pbin, ulong cBuckets)
{
*pbin = (DenseBin *) HTsmalloc(sizeof(*pbin));
(*pbin)->rgBuckets = (DenseBucket *) HTsmalloc(sizeof(*(*pbin)->rgBuckets)
* cBuckets);
DenseClear(*pbin, cBuckets);
return cBuckets;
}
static DenseBin *DenseFree(DenseBin *bin, ulong cBuckets)
{
HTfree(bin->rgBuckets, sizeof(*bin->rgBuckets) * cBuckets);
HTfree(bin, sizeof(*bin));
return NULL;
}
static int DenseIsEmpty(DenseBin *bin, ulong location)
{
return DENSE_IS_EMPTY(bin->rgBuckets, location);
}
static DenseBucket *DenseFind(DenseBin *bin, ulong location)
{
if ( DenseIsEmpty(bin, location) )
return NULL;
return bin->rgBuckets + location;
}
static DenseBucket *DenseInsert(DenseBin *bin, DenseBucket *bckInsert,
ulong location, int *pfOverwrite)
{
DenseBucket *bckPlace;
bckPlace = DenseFind(bin, location);
if ( bckPlace ) /* means something is already there */
{
if ( *pfOverwrite )
*bckPlace = *bckInsert;
*pfOverwrite = 1; /* set to 1 to indicate someone was there */
return bckPlace;
}
else
{
bin->rgBuckets[location] = *bckInsert;
*pfOverwrite = 0;
return bin->rgBuckets + location;
}
}
static DenseBucket *DenseNextBucket(DenseIterator *iter)
{
for ( iter->pos++; iter->pos < iter->cBuckets; iter->pos++ )
if ( !DenseIsEmpty(iter->bin, iter->pos) )
return iter->bin->rgBuckets + iter->pos;
return NULL; /* all remaining groups were empty */
}
static DenseBucket *DenseFirstBucket(DenseIterator *iter,
DenseBin *bin, ulong cBuckets)
{
iter->bin = bin; /* set it up for NextBucket() */
iter->cBuckets = cBuckets;
iter->pos = -1; /* thus the next bucket will be 0 */
return DenseNextBucket(iter);
}
static void DenseWrite(FILE *fp, DenseBin *bin, ulong cBuckets)
{
ulong pos = 0, bit, bm;
WRITE_UL(fp, cBuckets);
while ( pos < cBuckets )
{
bm = 0;
for ( bit = 0; bit < 8*sizeof(ulong); bit++ )
{
if ( !DenseIsEmpty(bin, pos) )
SET_BITMAP(&bm, bit); /* in fks-hash.h */
if ( ++pos == cBuckets )
break;
}
WRITE_UL(fp, bm);
}
}
static ulong DenseRead(FILE *fp, DenseBin **pbin)
{
ulong pos = 0, bit, bm, cBuckets;
READ_UL(fp, cBuckets);
cBuckets = DenseAllocate(pbin, cBuckets);
while ( pos < cBuckets )
{
READ_UL(fp, bm);
for ( bit = 0; bit < 8*sizeof(ulong); bit++ )
{
if ( TEST_BITMAP(&bm, bit) ) /* in fks-hash.h */
DENSE_SET_OCCUPIED((*pbin)->rgBuckets, pos);
else
DENSE_SET_EMPTY((*pbin)->rgBuckets, pos);
if ( ++pos == cBuckets )
break;
}
}
return cBuckets;
}
static ulong DenseMemory(ulong cBuckets, ulong cOccupied)
{
return cBuckets * sizeof(DenseBucket);
}
/* ======================================================================== */
/* HASHING ROUTINES */
/* ---------------------- */
/* Implements a simple quadratic hashing scheme. We have a single hash
* table of size t and a single hash function h(x). When inserting an
* item, first we try h(x) % t. If it's occupied, we try h(x) +
* i*(i-1)/2 % t for increasing values of i until we hit a not-occupied
* space. To make this dynamic, we double the size of the hash table as
* soon as more than half the cells are occupied. When deleting, we can
* choose to shrink the hashtable when less than a quarter of the
* cells are occupied, or we can choose never to shrink the hashtable.
* For lookup, we check h(x) + i*(i-1)/2 % t (starting with i=0) until
* we get a match or we hit an empty space. Note that as a result,
* we can't make a cell empty on deletion, or lookups may end prematurely.
* Instead we mark the cell as "deleted." We thus steal the value
* DELETED as a possible "data" value. As long as data are pointers,
* that's ok.
* The hash increment we use, i(i-1)/2, is not the standard quadratic
* hash increment, which is i^2. i(i-1)/2 covers the entire bucket space
* when the hashtable size is a power of two, as it is for us. In fact,
* the first n probes cover n distinct buckets; then it repeats. This
* guarantees insertion will always succeed.
* If you linear hashing, set JUMP in chash.h. You can also change
* various other parameters there.
*/
/*************************************************************************\
| Hash() |
| The hash function I use is due to Bob Jenkins (see |
| http://burtleburtle.net/bob/hash/evahash.html |
| According to http://burtleburtle.net/bob/c/lookup2.c, |
| his implementation is public domain.) |
| It takes 36 instructions, in 18 cycles if you're lucky. |
| hashing depends on the fact the hashtable size is always a |
| power of 2. cBuckets is probably ht->cBuckets. |
\*************************************************************************/
#if LOG_WORD_SIZE == 5 /* 32 bit words */
#define mix(a,b,c) \
{ \
a -= b; a -= c; a ^= (c>>13); \
b -= c; b -= a; b ^= (a<<8); \
c -= a; c -= b; c ^= (b>>13); \
a -= b; a -= c; a ^= (c>>12); \
b -= c; b -= a; b ^= (a<<16); \
c -= a; c -= b; c ^= (b>>5); \
a -= b; a -= c; a ^= (c>>3); \
b -= c; b -= a; b ^= (a<<10); \
c -= a; c -= b; c ^= (b>>15); \
}
#ifdef WORD_HASH /* play with this on little-endian machines */
#define WORD_AT(ptr) ( *(ulong *)(ptr) )
#else
#define WORD_AT(ptr) ( (ptr)[0] + ((ulong)(ptr)[1]<<8) + \
((ulong)(ptr)[2]<<16) + ((ulong)(ptr)[3]<<24) )
#endif
#elif LOG_WORD_SIZE == 6 /* 64 bit words */
#define mix(a,b,c) \
{ \
a -= b; a -= c; a ^= (c>>43); \
b -= c; b -= a; b ^= (a<<9); \
c -= a; c -= b; c ^= (b>>8); \
a -= b; a -= c; a ^= (c>>38); \
b -= c; b -= a; b ^= (a<<23); \
c -= a; c -= b; c ^= (b>>5); \
a -= b; a -= c; a ^= (c>>35); \
b -= c; b -= a; b ^= (a<<49); \
c -= a; c -= b; c ^= (b>>11); \
a -= b; a -= c; a ^= (c>>12); \
b -= c; b -= a; b ^= (a<<18); \
c -= a; c -= b; c ^= (b>>22); \
}
#ifdef WORD_HASH /* alpha is little-endian, btw */
#define WORD_AT(ptr) ( *(ulong *)(ptr) )
#else
#define WORD_AT(ptr) ( (ptr)[0] + ((ulong)(ptr)[1]<<8) + \
((ulong)(ptr)[2]<<16) + ((ulong)(ptr)[3]<<24) + \
((ulong)(ptr)[4]<<32) + ((ulong)(ptr)[5]<<40) + \
((ulong)(ptr)[6]<<48) + ((ulong)(ptr)[7]<<56) )
#endif
#else /* neither 32 or 64 bit words */
#error This hash function can only hash 32 or 64 bit words. Sorry.
#endif
static ulong Hash(HashTable *ht, char *key, ulong cBuckets)
{
ulong a, b, c, cchKey, cchKeyOrig;
cchKeyOrig = ht->cchKey == NULL_TERMINATED ? strlen(key) : ht->cchKey;
a = b = c = 0x9e3779b9; /* the golden ratio; an arbitrary value */
for ( cchKey = cchKeyOrig; cchKey >= 3 * sizeof(ulong);
cchKey -= 3 * sizeof(ulong), key += 3 * sizeof(ulong) )
{
a += WORD_AT(key);
b += WORD_AT(key + sizeof(ulong));
c += WORD_AT(key + sizeof(ulong)*2);
mix(a,b,c);
}
c += cchKeyOrig;
switch ( cchKey ) { /* deal with rest. Cases fall through */
#if LOG_WORD_SIZE == 5
case 11: c += (ulong)key[10]<<24;
case 10: c += (ulong)key[9]<<16;
case 9 : c += (ulong)key[8]<<8;
/* the first byte of c is reserved for the length */
case 8 : b += WORD_AT(key+4); a+= WORD_AT(key); break;
case 7 : b += (ulong)key[6]<<16;
case 6 : b += (ulong)key[5]<<8;
case 5 : b += key[4];
case 4 : a += WORD_AT(key); break;
case 3 : a += (ulong)key[2]<<16;
case 2 : a += (ulong)key[1]<<8;
case 1 : a += key[0];
/* case 0 : nothing left to add */
#elif LOG_WORD_SIZE == 6
case 23: c += (ulong)key[22]<<56;
case 22: c += (ulong)key[21]<<48;
case 21: c += (ulong)key[20]<<40;
case 20: c += (ulong)key[19]<<32;
case 19: c += (ulong)key[18]<<24;
case 18: c += (ulong)key[17]<<16;
case 17: c += (ulong)key[16]<<8;
/* the first byte of c is reserved for the length */
case 16: b += WORD_AT(key+8); a+= WORD_AT(key); break;
case 15: b += (ulong)key[14]<<48;
case 14: b += (ulong)key[13]<<40;
case 13: b += (ulong)key[12]<<32;
case 12: b += (ulong)key[11]<<24;
case 11: b += (ulong)key[10]<<16;
case 10: b += (ulong)key[ 9]<<8;
case 9: b += (ulong)key[ 8];
case 8: a += WORD_AT(key); break;
case 7: a += (ulong)key[ 6]<<48;
case 6: a += (ulong)key[ 5]<<40;
case 5: a += (ulong)key[ 4]<<32;
case 4: a += (ulong)key[ 3]<<24;
case 3: a += (ulong)key[ 2]<<16;
case 2: a += (ulong)key[ 1]<<8;
case 1: a += (ulong)key[ 0];
/* case 0: nothing left to add */
#endif
}
mix(a,b,c);
return c & (cBuckets-1);
}
/*************************************************************************\
| Rehash() |
| You give me a hashtable, a new size, and a bucket to follow, and |
| I resize the hashtable's bin to be the new size, rehashing |
| everything in it. I keep particular track of the bucket you pass |
| in, and RETURN a pointer to where the item in the bucket got to. |
| (If you pass in NULL, I return an arbitrary pointer.) |
\*************************************************************************/
static HTItem *Rehash(HashTable *ht, ulong cNewBuckets, HTItem *bckWatch)
{
Table *tableNew;
ulong iBucketFirst;
HTItem *bck, *bckNew = NULL;
ulong offset; /* the i in h(x) + i*(i-1)/2 */
int fOverwrite = 0; /* not an issue: there can be no collisions */
assert( ht->table );
cNewBuckets = Table(Allocate)(&tableNew, cNewBuckets);
/* Since we RETURN the new position of bckWatch, we want *
* to make sure it doesn't get moved due to some table *
* rehashing that comes after it's inserted. Thus, we *
* have to put it in last. This makes the loop weird. */
for ( bck = HashFirstBucket(ht); ; bck = HashNextBucket(ht) )
{
if ( bck == NULL ) /* we're done iterating, so look at bckWatch */
{
bck = bckWatch;
if ( bck == NULL ) /* I guess bckWatch wasn't specified */
break;
}
else if ( bck == bckWatch )
continue; /* ignore if we see it during the iteration */
offset = 0; /* a new i for a new bucket */
for ( iBucketFirst = Hash(ht, KEY_PTR(ht, bck->key), cNewBuckets);
!Table(IsEmpty)(tableNew, iBucketFirst);
iBucketFirst = (iBucketFirst + JUMP(KEY_PTR(ht,bck->key), offset))
& (cNewBuckets-1) )
;
bckNew = Table(Insert)(tableNew, bck, iBucketFirst, &fOverwrite);
if ( bck == bckWatch ) /* we're done with the last thing to do */
break;
}
Table(Free)(ht->table, ht->cBuckets);
ht->table = tableNew;
ht->cBuckets = cNewBuckets;
ht->cDeletedItems = 0;
return bckNew; /* new position of bckWatch, which was inserted last */
}