2 ** upb_table Implementation
4 ** Implementation is heavily inspired by Lua's ltable.c.
7 #include "upb/table.int.h"
11 #include "upb/port_def.inc"
13 #define UPB_MAXARRSIZE 16 /* 64k. */
16 #define ARRAY_SIZE(x) \
17 ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
19 static void upb_check_alloc(upb_table *t, upb_alloc *a) {
22 UPB_ASSERT_DEBUGVAR(t->alloc == a);
25 static const double MAX_LOAD = 0.85;
27 /* The minimum utilization of the array part of a mixed hash/array table. This
28 * is a speed/memory-usage tradeoff (though it's not straightforward because of
29 * cache effects). The lower this is, the more memory we'll use. */
30 static const double MIN_DENSITY = 0.1;
32 bool is_pow2(uint64_t v) { return v == 0 || (v & (v - 1)) == 0; }
34 int log2ceil(uint64_t v) {
36 bool pow2 = is_pow2(v);
37 while (v >>= 1) ret++;
38 ret = pow2 ? ret : ret + 1; /* Ceiling. */
39 return UPB_MIN(UPB_MAXARRSIZE, ret);
42 char *upb_strdup(const char *s, upb_alloc *a) {
43 return upb_strdup2(s, strlen(s), a);
46 char *upb_strdup2(const char *s, size_t len, upb_alloc *a) {
50 /* Prevent overflow errors. */
51 if (len == SIZE_MAX) return NULL;
52 /* Always null-terminate, even if binary data; but don't rely on the input to
53 * have a null-terminating byte since it may be a raw binary buffer. */
63 /* A type to represent the lookup key of either a strtable or an inttable. */
72 static lookupkey_t strkey2(const char *str, size_t len) {
79 static lookupkey_t intkey(uintptr_t key) {
85 typedef uint32_t hashfunc_t(upb_tabkey key);
86 typedef bool eqlfunc_t(upb_tabkey k1, lookupkey_t k2);
88 /* Base table (shared code) ***************************************************/
90 /* For when we need to cast away const. */
91 static upb_tabent *mutable_entries(upb_table *t) {
92 return (upb_tabent*)t->entries;
95 static bool isfull(upb_table *t) {
96 if (upb_table_size(t) == 0) {
99 return ((double)(t->count + 1) / upb_table_size(t)) > MAX_LOAD;
103 static bool init(upb_table *t, upb_ctype_t ctype, uint8_t size_lg2,
109 t->size_lg2 = size_lg2;
110 t->mask = upb_table_size(t) ? upb_table_size(t) - 1 : 0;
114 bytes = upb_table_size(t) * sizeof(upb_tabent);
116 t->entries = upb_malloc(a, bytes);
117 if (!t->entries) return false;
118 memset(mutable_entries(t), 0, bytes);
125 static void uninit(upb_table *t, upb_alloc *a) {
126 upb_check_alloc(t, a);
127 upb_free(a, mutable_entries(t));
130 static upb_tabent *emptyent(upb_table *t) {
131 upb_tabent *e = mutable_entries(t) + upb_table_size(t);
132 while (1) { if (upb_tabent_isempty(--e)) return e; UPB_ASSERT(e > t->entries); }
135 static upb_tabent *getentry_mutable(upb_table *t, uint32_t hash) {
136 return (upb_tabent*)upb_getentry(t, hash);
139 static const upb_tabent *findentry(const upb_table *t, lookupkey_t key,
140 uint32_t hash, eqlfunc_t *eql) {
143 if (t->size_lg2 == 0) return NULL;
144 e = upb_getentry(t, hash);
145 if (upb_tabent_isempty(e)) return NULL;
147 if (eql(e->key, key)) return e;
148 if ((e = e->next) == NULL) return NULL;
152 static upb_tabent *findentry_mutable(upb_table *t, lookupkey_t key,
153 uint32_t hash, eqlfunc_t *eql) {
154 return (upb_tabent*)findentry(t, key, hash, eql);
157 static bool lookup(const upb_table *t, lookupkey_t key, upb_value *v,
158 uint32_t hash, eqlfunc_t *eql) {
159 const upb_tabent *e = findentry(t, key, hash, eql);
162 _upb_value_setval(v, e->val.val, t->ctype);
170 /* The given key must not already exist in the table. */
171 static void insert(upb_table *t, lookupkey_t key, upb_tabkey tabkey,
172 upb_value val, uint32_t hash,
173 hashfunc_t *hashfunc, eqlfunc_t *eql) {
174 upb_tabent *mainpos_e;
177 UPB_ASSERT(findentry(t, key, hash, eql) == NULL);
178 UPB_ASSERT_DEBUGVAR(val.ctype == t->ctype);
181 mainpos_e = getentry_mutable(t, hash);
184 if (upb_tabent_isempty(mainpos_e)) {
185 /* Our main position is empty; use it. */
189 upb_tabent *new_e = emptyent(t);
190 /* Head of collider's chain. */
191 upb_tabent *chain = getentry_mutable(t, hashfunc(mainpos_e->key));
192 if (chain == mainpos_e) {
193 /* Existing ent is in its main posisiton (it has the same hash as us, and
194 * is the head of our chain). Insert to new ent and append to this chain. */
195 new_e->next = mainpos_e->next;
196 mainpos_e->next = new_e;
199 /* Existing ent is not in its main position (it is a node in some other
200 * chain). This implies that no existing ent in the table has our hash.
201 * Evict it (updating its chain) and use its ent for head of our chain. */
202 *new_e = *mainpos_e; /* copies next. */
203 while (chain->next != mainpos_e) {
204 chain = (upb_tabent*)chain->next;
213 our_e->val.val = val.val;
214 UPB_ASSERT(findentry(t, key, hash, eql) == our_e);
217 static bool rm(upb_table *t, lookupkey_t key, upb_value *val,
218 upb_tabkey *removed, uint32_t hash, eqlfunc_t *eql) {
219 upb_tabent *chain = getentry_mutable(t, hash);
220 if (upb_tabent_isempty(chain)) return false;
221 if (eql(chain->key, key)) {
222 /* Element to remove is at the head of its chain. */
224 if (val) _upb_value_setval(val, chain->val.val, t->ctype);
225 if (removed) *removed = chain->key;
227 upb_tabent *move = (upb_tabent*)chain->next;
229 move->key = 0; /* Make the slot empty. */
231 chain->key = 0; /* Make the slot empty. */
235 /* Element to remove is either in a non-head position or not in the
237 while (chain->next && !eql(chain->next->key, key)) {
238 chain = (upb_tabent*)chain->next;
241 /* Found element to remove. */
242 upb_tabent *rm = (upb_tabent*)chain->next;
244 if (val) _upb_value_setval(val, chain->next->val.val, t->ctype);
245 if (removed) *removed = rm->key;
246 rm->key = 0; /* Make the slot empty. */
247 chain->next = rm->next;
250 /* Element to remove is not in the table. */
256 static size_t next(const upb_table *t, size_t i) {
258 if (++i >= upb_table_size(t))
260 } while(upb_tabent_isempty(&t->entries[i]));
265 static size_t begin(const upb_table *t) {
270 /* upb_strtable ***************************************************************/
272 /* A simple "subclass" of upb_table that only adds a hash function for strings. */
274 static upb_tabkey strcopy(lookupkey_t k2, upb_alloc *a) {
275 uint32_t len = (uint32_t) k2.str.len;
276 char *str = upb_malloc(a, k2.str.len + sizeof(uint32_t) + 1);
277 if (str == NULL) return 0;
278 memcpy(str, &len, sizeof(uint32_t));
279 memcpy(str + sizeof(uint32_t), k2.str.str, k2.str.len + 1);
280 return (uintptr_t)str;
283 static uint32_t strhash(upb_tabkey key) {
285 char *str = upb_tabstr(key, &len);
286 return upb_murmur_hash2(str, len, 0);
289 static bool streql(upb_tabkey k1, lookupkey_t k2) {
291 char *str = upb_tabstr(k1, &len);
292 return len == k2.str.len && memcmp(str, k2.str.str, len) == 0;
295 bool upb_strtable_init2(upb_strtable *t, upb_ctype_t ctype, upb_alloc *a) {
296 return init(&t->t, ctype, 2, a);
299 void upb_strtable_uninit2(upb_strtable *t, upb_alloc *a) {
301 for (i = 0; i < upb_table_size(&t->t); i++)
302 upb_free(a, (void*)t->t.entries[i].key);
306 bool upb_strtable_resize(upb_strtable *t, size_t size_lg2, upb_alloc *a) {
307 upb_strtable new_table;
310 upb_check_alloc(&t->t, a);
312 if (!init(&new_table.t, t->t.ctype, size_lg2, a))
314 upb_strtable_begin(&i, t);
315 for ( ; !upb_strtable_done(&i); upb_strtable_next(&i)) {
316 upb_strtable_insert3(
318 upb_strtable_iter_key(&i),
319 upb_strtable_iter_keylength(&i),
320 upb_strtable_iter_value(&i),
323 upb_strtable_uninit2(t, a);
328 bool upb_strtable_insert3(upb_strtable *t, const char *k, size_t len,
329 upb_value v, upb_alloc *a) {
334 upb_check_alloc(&t->t, a);
337 /* Need to resize. New table of double the size, add old elements to it. */
338 if (!upb_strtable_resize(t, t->t.size_lg2 + 1, a)) {
343 key = strkey2(k, len);
344 tabkey = strcopy(key, a);
345 if (tabkey == 0) return false;
347 hash = upb_murmur_hash2(key.str.str, key.str.len, 0);
348 insert(&t->t, key, tabkey, v, hash, &strhash, &streql);
352 bool upb_strtable_lookup2(const upb_strtable *t, const char *key, size_t len,
354 uint32_t hash = upb_murmur_hash2(key, len, 0);
355 return lookup(&t->t, strkey2(key, len), v, hash, &streql);
358 bool upb_strtable_remove3(upb_strtable *t, const char *key, size_t len,
359 upb_value *val, upb_alloc *alloc) {
360 uint32_t hash = upb_murmur_hash2(key, len, 0);
362 if (rm(&t->t, strkey2(key, len), val, &tabkey, hash, &streql)) {
363 upb_free(alloc, (void*)tabkey);
372 static const upb_tabent *str_tabent(const upb_strtable_iter *i) {
373 return &i->t->t.entries[i->index];
376 void upb_strtable_begin(upb_strtable_iter *i, const upb_strtable *t) {
378 i->index = begin(&t->t);
381 void upb_strtable_next(upb_strtable_iter *i) {
382 i->index = next(&i->t->t, i->index);
385 bool upb_strtable_done(const upb_strtable_iter *i) {
386 if (!i->t) return true;
387 return i->index >= upb_table_size(&i->t->t) ||
388 upb_tabent_isempty(str_tabent(i));
391 const char *upb_strtable_iter_key(const upb_strtable_iter *i) {
392 UPB_ASSERT(!upb_strtable_done(i));
393 return upb_tabstr(str_tabent(i)->key, NULL);
396 size_t upb_strtable_iter_keylength(const upb_strtable_iter *i) {
398 UPB_ASSERT(!upb_strtable_done(i));
399 upb_tabstr(str_tabent(i)->key, &len);
403 upb_value upb_strtable_iter_value(const upb_strtable_iter *i) {
404 UPB_ASSERT(!upb_strtable_done(i));
405 return _upb_value_val(str_tabent(i)->val.val, i->t->t.ctype);
408 void upb_strtable_iter_setdone(upb_strtable_iter *i) {
413 bool upb_strtable_iter_isequal(const upb_strtable_iter *i1,
414 const upb_strtable_iter *i2) {
415 if (upb_strtable_done(i1) && upb_strtable_done(i2))
417 return i1->t == i2->t && i1->index == i2->index;
421 /* upb_inttable ***************************************************************/
423 /* For inttables we use a hybrid structure where small keys are kept in an
424 * array and large keys are put in the hash table. */
426 static uint32_t inthash(upb_tabkey key) { return upb_inthash(key); }
428 static bool inteql(upb_tabkey k1, lookupkey_t k2) {
432 static upb_tabval *mutable_array(upb_inttable *t) {
433 return (upb_tabval*)t->array;
436 static upb_tabval *inttable_val(upb_inttable *t, uintptr_t key) {
437 if (key < t->array_size) {
438 return upb_arrhas(t->array[key]) ? &(mutable_array(t)[key]) : NULL;
441 findentry_mutable(&t->t, intkey(key), upb_inthash(key), &inteql);
442 return e ? &e->val : NULL;
446 static const upb_tabval *inttable_val_const(const upb_inttable *t,
448 return inttable_val((upb_inttable*)t, key);
451 size_t upb_inttable_count(const upb_inttable *t) {
452 return t->t.count + t->array_count;
455 static void check(upb_inttable *t) {
457 #if defined(UPB_DEBUG_TABLE) && !defined(NDEBUG)
459 /* This check is very expensive (makes inserts/deletes O(N)). */
462 upb_inttable_begin(&i, t);
463 for(; !upb_inttable_done(&i); upb_inttable_next(&i), count++) {
464 UPB_ASSERT(upb_inttable_lookup(t, upb_inttable_iter_key(&i), NULL));
466 UPB_ASSERT(count == upb_inttable_count(t));
471 bool upb_inttable_sizedinit(upb_inttable *t, upb_ctype_t ctype,
472 size_t asize, int hsize_lg2, upb_alloc *a) {
475 if (!init(&t->t, ctype, hsize_lg2, a)) return false;
476 /* Always make the array part at least 1 long, so that we know key 0
477 * won't be in the hash part, which simplifies things. */
478 t->array_size = UPB_MAX(1, asize);
480 array_bytes = t->array_size * sizeof(upb_value);
481 t->array = upb_malloc(a, array_bytes);
486 memset(mutable_array(t), 0xff, array_bytes);
491 bool upb_inttable_init2(upb_inttable *t, upb_ctype_t ctype, upb_alloc *a) {
492 return upb_inttable_sizedinit(t, ctype, 0, 4, a);
495 void upb_inttable_uninit2(upb_inttable *t, upb_alloc *a) {
497 upb_free(a, mutable_array(t));
500 bool upb_inttable_insert2(upb_inttable *t, uintptr_t key, upb_value val,
503 tabval.val = val.val;
504 UPB_ASSERT(upb_arrhas(tabval)); /* This will reject (uint64_t)-1. Fix this. */
506 upb_check_alloc(&t->t, a);
508 if (key < t->array_size) {
509 UPB_ASSERT(!upb_arrhas(t->array[key]));
511 mutable_array(t)[key].val = val.val;
514 /* Need to resize the hash part, but we re-use the array part. */
518 if (!init(&new_table, t->t.ctype, t->t.size_lg2 + 1, a)) {
522 for (i = begin(&t->t); i < upb_table_size(&t->t); i = next(&t->t, i)) {
523 const upb_tabent *e = &t->t.entries[i];
527 _upb_value_setval(&v, e->val.val, t->t.ctype);
528 hash = upb_inthash(e->key);
529 insert(&new_table, intkey(e->key), e->key, v, hash, &inthash, &inteql);
532 UPB_ASSERT(t->t.count == new_table.count);
537 insert(&t->t, intkey(key), key, val, upb_inthash(key), &inthash, &inteql);
543 bool upb_inttable_lookup(const upb_inttable *t, uintptr_t key, upb_value *v) {
544 const upb_tabval *table_v = inttable_val_const(t, key);
545 if (!table_v) return false;
546 if (v) _upb_value_setval(v, table_v->val, t->t.ctype);
550 bool upb_inttable_replace(upb_inttable *t, uintptr_t key, upb_value val) {
551 upb_tabval *table_v = inttable_val(t, key);
552 if (!table_v) return false;
553 table_v->val = val.val;
557 bool upb_inttable_remove(upb_inttable *t, uintptr_t key, upb_value *val) {
559 if (key < t->array_size) {
560 if (upb_arrhas(t->array[key])) {
561 upb_tabval empty = UPB_TABVALUE_EMPTY_INIT;
564 _upb_value_setval(val, t->array[key].val, t->t.ctype);
566 mutable_array(t)[key] = empty;
572 success = rm(&t->t, intkey(key), val, NULL, upb_inthash(key), &inteql);
578 bool upb_inttable_push2(upb_inttable *t, upb_value val, upb_alloc *a) {
579 upb_check_alloc(&t->t, a);
580 return upb_inttable_insert2(t, upb_inttable_count(t), val, a);
583 upb_value upb_inttable_pop(upb_inttable *t) {
585 bool ok = upb_inttable_remove(t, upb_inttable_count(t) - 1, &val);
590 bool upb_inttable_insertptr2(upb_inttable *t, const void *key, upb_value val,
592 upb_check_alloc(&t->t, a);
593 return upb_inttable_insert2(t, (uintptr_t)key, val, a);
596 bool upb_inttable_lookupptr(const upb_inttable *t, const void *key,
598 return upb_inttable_lookup(t, (uintptr_t)key, v);
601 bool upb_inttable_removeptr(upb_inttable *t, const void *key, upb_value *val) {
602 return upb_inttable_remove(t, (uintptr_t)key, val);
605 void upb_inttable_compact2(upb_inttable *t, upb_alloc *a) {
606 /* A power-of-two histogram of the table keys. */
607 size_t counts[UPB_MAXARRSIZE + 1] = {0};
609 /* The max key in each bucket. */
610 uintptr_t max[UPB_MAXARRSIZE + 1] = {0};
617 upb_check_alloc(&t->t, a);
619 upb_inttable_begin(&i, t);
620 for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
621 uintptr_t key = upb_inttable_iter_key(&i);
622 int bucket = log2ceil(key);
623 max[bucket] = UPB_MAX(max[bucket], key);
627 /* Find the largest power of two that satisfies the MIN_DENSITY
628 * definition (while actually having some keys). */
629 arr_count = upb_inttable_count(t);
631 for (size_lg2 = ARRAY_SIZE(counts) - 1; size_lg2 > 0; size_lg2--) {
632 if (counts[size_lg2] == 0) {
633 /* We can halve again without losing any entries. */
635 } else if (arr_count >= (1 << size_lg2) * MIN_DENSITY) {
639 arr_count -= counts[size_lg2];
642 UPB_ASSERT(arr_count <= upb_inttable_count(t));
645 /* Insert all elements into new, perfectly-sized table. */
646 size_t arr_size = max[size_lg2] + 1; /* +1 so arr[max] will fit. */
647 size_t hash_count = upb_inttable_count(t) - arr_count;
648 size_t hash_size = hash_count ? (hash_count / MAX_LOAD) + 1 : 0;
649 int hashsize_lg2 = log2ceil(hash_size);
651 upb_inttable_sizedinit(&new_t, t->t.ctype, arr_size, hashsize_lg2, a);
652 upb_inttable_begin(&i, t);
653 for (; !upb_inttable_done(&i); upb_inttable_next(&i)) {
654 uintptr_t k = upb_inttable_iter_key(&i);
655 upb_inttable_insert2(&new_t, k, upb_inttable_iter_value(&i), a);
657 UPB_ASSERT(new_t.array_size == arr_size);
658 UPB_ASSERT(new_t.t.size_lg2 == hashsize_lg2);
660 upb_inttable_uninit2(t, a);
666 static const upb_tabent *int_tabent(const upb_inttable_iter *i) {
667 UPB_ASSERT(!i->array_part);
668 return &i->t->t.entries[i->index];
671 static upb_tabval int_arrent(const upb_inttable_iter *i) {
672 UPB_ASSERT(i->array_part);
673 return i->t->array[i->index];
676 void upb_inttable_begin(upb_inttable_iter *i, const upb_inttable *t) {
679 i->array_part = true;
680 upb_inttable_next(i);
683 void upb_inttable_next(upb_inttable_iter *iter) {
684 const upb_inttable *t = iter->t;
685 if (iter->array_part) {
686 while (++iter->index < t->array_size) {
687 if (upb_arrhas(int_arrent(iter))) {
691 iter->array_part = false;
692 iter->index = begin(&t->t);
694 iter->index = next(&t->t, iter->index);
698 bool upb_inttable_done(const upb_inttable_iter *i) {
699 if (!i->t) return true;
701 return i->index >= i->t->array_size ||
702 !upb_arrhas(int_arrent(i));
704 return i->index >= upb_table_size(&i->t->t) ||
705 upb_tabent_isempty(int_tabent(i));
709 uintptr_t upb_inttable_iter_key(const upb_inttable_iter *i) {
710 UPB_ASSERT(!upb_inttable_done(i));
711 return i->array_part ? i->index : int_tabent(i)->key;
714 upb_value upb_inttable_iter_value(const upb_inttable_iter *i) {
715 UPB_ASSERT(!upb_inttable_done(i));
716 return _upb_value_val(
717 i->array_part ? i->t->array[i->index].val : int_tabent(i)->val.val,
721 void upb_inttable_iter_setdone(upb_inttable_iter *i) {
724 i->array_part = false;
727 bool upb_inttable_iter_isequal(const upb_inttable_iter *i1,
728 const upb_inttable_iter *i2) {
729 if (upb_inttable_done(i1) && upb_inttable_done(i2))
731 return i1->t == i2->t && i1->index == i2->index &&
732 i1->array_part == i2->array_part;
735 #if defined(UPB_UNALIGNED_READS_OK) || defined(__s390x__)
736 /* -----------------------------------------------------------------------------
737 * MurmurHash2, by Austin Appleby (released as public domain).
738 * Reformatted and C99-ified by Joshua Haberman.
739 * Note - This code makes a few assumptions about how your machine behaves -
740 * 1. We can read a 4-byte value from any address without crashing
741 * 2. sizeof(int) == 4 (in upb this limitation is removed by using uint32_t
742 * And it has a few limitations -
743 * 1. It will not work incrementally.
744 * 2. It will not produce the same results on little-endian and big-endian
746 uint32_t upb_murmur_hash2(const void *key, size_t len, uint32_t seed) {
747 /* 'm' and 'r' are mixing constants generated offline.
748 * They're not really 'magic', they just happen to work well. */
749 const uint32_t m = 0x5bd1e995;
750 const int32_t r = 24;
752 /* Initialize the hash to a 'random' value */
753 uint32_t h = seed ^ len;
755 /* Mix 4 bytes at a time into the hash */
756 const uint8_t * data = (const uint8_t *)key;
758 uint32_t k = *(uint32_t *)data;
771 /* Handle the last few bytes of the input array */
773 case 3: h ^= data[2] << 16;
774 case 2: h ^= data[1] << 8;
775 case 1: h ^= data[0]; h *= m;
778 /* Do a few final mixes of the hash to ensure the last few
779 * bytes are well-incorporated. */
787 #else /* !UPB_UNALIGNED_READS_OK */
789 /* -----------------------------------------------------------------------------
790 * MurmurHashAligned2, by Austin Appleby
791 * Same algorithm as MurmurHash2, but only does aligned reads - should be safer
792 * on certain platforms.
793 * Performance will be lower than MurmurHash2 */
795 #define MIX(h,k,m) { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; }
797 uint32_t upb_murmur_hash2(const void * key, size_t len, uint32_t seed) {
798 const uint32_t m = 0x5bd1e995;
799 const int32_t r = 24;
800 const uint8_t * data = (const uint8_t *)key;
801 uint32_t h = (uint32_t)(seed ^ len);
802 uint8_t align = (uintptr_t)data & 3;
804 if(align && (len >= 4)) {
805 /* Pre-load the temp registers */
806 uint32_t t = 0, d = 0;
811 case 1: t |= data[2] << 16;
812 case 2: t |= data[1] << 8;
813 case 3: t |= data[0];
829 d = *(uint32_t *)data;
830 t = (t >> sr) | (d << sl);
842 /* Handle leftover data in temp registers */
850 case 3: d |= data[2] << 16;
851 case 2: d |= data[1] << 8;
852 case 1: d |= data[0];
855 k = (t >> sr) | (d << sl);
862 * Handle tail bytes */
865 case 3: h ^= data[2] << 16;
866 case 2: h ^= data[1] << 8;
867 case 1: h ^= data[0]; h *= m;
871 case 3: d |= data[2] << 16;
872 case 2: d |= data[1] << 8;
873 case 1: d |= data[0];
874 case 0: h ^= (t >> sr) | (d << sl); h *= m;
885 uint32_t k = *(uint32_t *)data;
894 * Handle tail bytes */
897 case 3: h ^= data[2] << 16;
898 case 2: h ^= data[1] << 8;
899 case 1: h ^= data[0]; h *= m;
911 #endif /* UPB_UNALIGNED_READS_OK */