/* The MIT License12Copyright (c) 2008, 2009, 2011 by Attractive Chaos <[email protected]>34Permission is hereby granted, free of charge, to any person obtaining5a copy of this software and associated documentation files (the6"Software"), to deal in the Software without restriction, including7without limitation the rights to use, copy, modify, merge, publish,8distribute, sublicense, and/or sell copies of the Software, and to9permit persons to whom the Software is furnished to do so, subject to10the following conditions:1112The above copyright notice and this permission notice shall be13included in all copies or substantial portions of the Software.1415THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,16EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF17MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND18NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS19BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN20ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN21CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE22SOFTWARE.23*/2425/*26An example:2728#include "khash.h"29KHASH_MAP_INIT_INT(32, char)30int main() {31int ret, is_missing;32khiter_t k;33khash_t(32) *h = kh_init(32);34k = kh_put(32, h, 5, &ret);35kh_value(h, k) = 10;36k = kh_get(32, h, 10);37is_missing = (k == kh_end(h));38k = kh_get(32, h, 5);39kh_del(32, h, k);40for (k = kh_begin(h); k != kh_end(h); ++k)41if (kh_exist(h, k)) kh_value(h, k) = 1;42kh_destroy(32, h);43return 0;44}45*/4647/*482013-05-02 (0.2.8):4950* Use quadratic probing. When the capacity is power of 2, stepping function51i*(i+1)/2 guarantees to traverse each bucket. It is better than double52hashing on cache performance and is more robust than linear probing.5354In theory, double hashing should be more robust than quadratic probing.55However, my implementation is probably not for large hash tables, because56the second hash function is closely tied to the first hash function,57which reduce the effectiveness of double hashing.5859Reference: http://research.cs.vt.edu/AVresearch/hashing/quadratic.php60612011-12-29 (0.2.7):6263* Minor code clean up; no actual effect.64652011-09-16 (0.2.6):6667* The capacity is a power of 2. This seems to dramatically improve the68speed for simple keys. Thank Zilong Tan for the suggestion. Reference:6970- http://code.google.com/p/ulib/71- http://nothings.org/computer/judy/7273* Allow to optionally use linear probing which usually has better74performance for random input. Double hashing is still the default as it75is more robust to certain non-random input.7677* Added Wang's integer hash function (not used by default). This hash78function is more robust to certain non-random input.79802011-02-14 (0.2.5):8182* Allow to declare global functions.83842009-09-26 (0.2.4):8586* Improve portability87882008-09-19 (0.2.3):8990* Corrected the example91* Improved interfaces92932008-09-11 (0.2.2):9495* Improved speed a little in kh_put()96972008-09-10 (0.2.1):9899* Added kh_clear()100* Fixed a compiling error1011022008-09-02 (0.2.0):103104* Changed to token concatenation which increases flexibility.1051062008-08-31 (0.1.2):107108* Fixed a bug in kh_get(), which has not been tested previously.1091102008-08-31 (0.1.1):111112* Added destructor113*/114115116#ifndef __AC_KHASH_H117#define __AC_KHASH_H118119/*!120@header121122Generic hash table library.123*/124125#define AC_VERSION_KHASH_H "0.2.8"126127#include <stdlib.h>128#include <string.h>129#include <limits.h>130131/* compiler specific configuration */132133#if UINT_MAX == 0xffffffffu134typedef unsigned int khint32_t;135#elif ULONG_MAX == 0xffffffffu136typedef unsigned long khint32_t;137#endif138139#if ULONG_MAX == ULLONG_MAX140typedef unsigned long khint64_t;141#else142typedef unsigned long long khint64_t;143#endif144145#ifndef kh_inline146#ifdef _MSC_VER147#define kh_inline __inline148#else149#define kh_inline inline150#endif151#endif /* kh_inline */152153#ifndef kh_unused154# ifdef __GNUC__155# define kh_unused(x) __attribute__((__unused__)) x156# else157# define kh_unused(x) x158# endif159#endif160161typedef khint32_t khint_t;162typedef khint_t khiter_t;163164#define __ac_isempty(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&2)165#define __ac_isdel(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&1)166#define __ac_iseither(flag, i) ((flag[i>>4]>>((i&0xfU)<<1))&3)167#define __ac_set_isdel_false(flag, i) (flag[i>>4]&=~(1ul<<((i&0xfU)<<1)))168#define __ac_set_isempty_false(flag, i) (flag[i>>4]&=~(2ul<<((i&0xfU)<<1)))169#define __ac_set_isboth_false(flag, i) (flag[i>>4]&=~(3ul<<((i&0xfU)<<1)))170#define __ac_set_isdel_true(flag, i) (flag[i>>4]|=1ul<<((i&0xfU)<<1))171172#define __ac_fsize(m) ((m) < 16? 1 : (m)>>4)173174#ifndef kroundup32175#define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x))176#endif177178#ifndef kcalloc179#define kcalloc(N,Z) calloc(N,Z)180#endif181#ifndef kmalloc182#define kmalloc(Z) malloc(Z)183#endif184#ifndef krealloc185#define krealloc(P,Z) realloc(P,Z)186#endif187#ifndef kfree188#define kfree(P) free(P)189#endif190191static const double __ac_HASH_UPPER = 0.77;192193#define __KHASH_TYPE(name, khkey_t, khval_t) \194typedef struct kh_##name##_s { \195khint_t n_buckets, size, n_occupied, upper_bound; \196khint32_t *flags; \197khkey_t *keys; \198khval_t *vals; \199} kh_##name##_t;200201#define __KHASH_PROTOTYPES(name, khkey_t, khval_t) \202extern kh_##name##_t * kh_init_##name(void); \203extern void kh_destroy_##name(kh_##name##_t *h); \204extern void kh_clear_##name(kh_##name##_t *h); \205extern khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key); \206extern int kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets); \207extern khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret); \208extern void kh_del_##name(kh_##name##_t *h, khint_t x);209210#define __KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \211SCOPE kh_##name##_t *kh_init_##name(void) { \212return (kh_##name##_t*)kcalloc(1, sizeof(kh_##name##_t)); \213} \214SCOPE void kh_destroy_##name(kh_##name##_t *h) \215{ \216if (h) { \217kfree((void *)h->keys); kfree(h->flags); \218kfree((void *)h->vals); \219kfree(h); \220} \221} \222SCOPE void kh_unused(kh_clear_##name)(kh_##name##_t *h) \223{ \224if (h && h->flags) { \225memset(h->flags, 0xaa, __ac_fsize(h->n_buckets) * sizeof(khint32_t)); \226h->size = h->n_occupied = 0; \227} \228} \229SCOPE khint_t kh_get_##name(const kh_##name##_t *h, khkey_t key) \230{ \231if (h->n_buckets) { \232khint_t k, i, last, mask, step = 0; \233mask = h->n_buckets - 1; \234k = __hash_func(key); i = k & mask; \235last = i; \236while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || !__hash_equal(h->keys[i], key))) { \237i = (i + (++step)) & mask; \238if (i == last) return h->n_buckets; \239} \240return __ac_iseither(h->flags, i)? h->n_buckets : i; \241} else return 0; \242} \243SCOPE int kh_resize_##name(kh_##name##_t *h, khint_t new_n_buckets) \244{ /* This function uses 0.25*n_buckets bytes of working space instead of [sizeof(key_t+val_t)+.25]*n_buckets. */ \245khint32_t *new_flags = 0; \246khint_t j = 1; \247{ \248kroundup32(new_n_buckets); \249if (new_n_buckets < 4) new_n_buckets = 4; \250if (h->size >= (khint_t)(new_n_buckets * __ac_HASH_UPPER + 0.5)) j = 0; /* requested size is too small */ \251else { /* hash table size to be changed (shrink or expand); rehash */ \252new_flags = (khint32_t*)kmalloc(__ac_fsize(new_n_buckets) * sizeof(khint32_t)); \253if (!new_flags) return -1; \254memset(new_flags, 0xaa, __ac_fsize(new_n_buckets) * sizeof(khint32_t)); \255if (h->n_buckets < new_n_buckets) { /* expand */ \256khkey_t *new_keys = (khkey_t*)krealloc((void *)h->keys, new_n_buckets * sizeof(khkey_t)); \257if (!new_keys) { kfree(new_flags); return -1; } \258h->keys = new_keys; \259if (kh_is_map) { \260khval_t *new_vals = (khval_t*)krealloc((void *)h->vals, new_n_buckets * sizeof(khval_t)); \261if (!new_vals) { kfree(new_flags); return -1; } \262h->vals = new_vals; \263} \264} /* otherwise shrink */ \265} \266} \267if (j) { /* rehashing is needed */ \268for (j = 0; j != h->n_buckets; ++j) { \269if (__ac_iseither(h->flags, j) == 0) { \270khkey_t key = h->keys[j]; \271khval_t val; \272khint_t new_mask; \273new_mask = new_n_buckets - 1; \274if (kh_is_map) val = h->vals[j]; \275__ac_set_isdel_true(h->flags, j); \276while (1) { /* kick-out process; sort of like in Cuckoo hashing */ \277khint_t k, i, step = 0; \278k = __hash_func(key); \279i = k & new_mask; \280while (!__ac_isempty(new_flags, i)) i = (i + (++step)) & new_mask; \281__ac_set_isempty_false(new_flags, i); \282if (i < h->n_buckets && __ac_iseither(h->flags, i) == 0) { /* kick out the existing element */ \283{ khkey_t tmp = h->keys[i]; h->keys[i] = key; key = tmp; } \284if (kh_is_map) { khval_t tmp = h->vals[i]; h->vals[i] = val; val = tmp; } \285__ac_set_isdel_true(h->flags, i); /* mark it as deleted in the old hash table */ \286} else { /* write the element and jump out of the loop */ \287h->keys[i] = key; \288if (kh_is_map) h->vals[i] = val; \289break; \290} \291} \292} \293} \294if (h->n_buckets > new_n_buckets) { /* shrink the hash table */ \295h->keys = (khkey_t*)krealloc((void *)h->keys, new_n_buckets * sizeof(khkey_t)); \296if (kh_is_map) h->vals = (khval_t*)krealloc((void *)h->vals, new_n_buckets * sizeof(khval_t)); \297} \298kfree(h->flags); /* free the working space */ \299h->flags = new_flags; \300h->n_buckets = new_n_buckets; \301h->n_occupied = h->size; \302h->upper_bound = (khint_t)(h->n_buckets * __ac_HASH_UPPER + 0.5); \303} \304return 0; \305} \306SCOPE khint_t kh_put_##name(kh_##name##_t *h, khkey_t key, int *ret) \307{ \308khint_t x; \309if (h->n_occupied >= h->upper_bound) { /* update the hash table */ \310if (h->n_buckets > (h->size<<1)) { \311if (kh_resize_##name(h, h->n_buckets - 1) < 0) { /* clear "deleted" elements */ \312*ret = -1; return h->n_buckets; \313} \314} else if (kh_resize_##name(h, h->n_buckets + 1) < 0) { /* expand the hash table */ \315*ret = -1; return h->n_buckets; \316} \317} /* TODO: to implement automatically shrinking; resize() already support shrinking */ \318{ \319khint_t k, i, site, last, mask = h->n_buckets - 1, step = 0; \320x = site = h->n_buckets; k = __hash_func(key); i = k & mask; \321if (__ac_isempty(h->flags, i)) x = i; /* for speed up */ \322else { \323last = i; \324while (!__ac_isempty(h->flags, i) && (__ac_isdel(h->flags, i) || !__hash_equal(h->keys[i], key))) { \325if (__ac_isdel(h->flags, i)) site = i; \326i = (i + (++step)) & mask; \327if (i == last) { x = site; break; } \328} \329if (x == h->n_buckets) { \330if (__ac_isempty(h->flags, i) && site != h->n_buckets) x = site; \331else x = i; \332} \333} \334} \335if (__ac_isempty(h->flags, x)) { /* not present at all */ \336h->keys[x] = key; \337__ac_set_isboth_false(h->flags, x); \338++h->size; ++h->n_occupied; \339*ret = 1; \340} else if (__ac_isdel(h->flags, x)) { /* deleted */ \341h->keys[x] = key; \342__ac_set_isboth_false(h->flags, x); \343++h->size; \344*ret = 2; \345} else *ret = 0; /* Don't touch h->keys[x] if present and not deleted */ \346return x; \347} \348SCOPE void kh_del_##name(kh_##name##_t *h, khint_t x) \349{ \350if (x != h->n_buckets && !__ac_iseither(h->flags, x)) { \351__ac_set_isdel_true(h->flags, x); \352--h->size; \353} \354}355356#define KHASH_DECLARE(name, khkey_t, khval_t) \357__KHASH_TYPE(name, khkey_t, khval_t) \358__KHASH_PROTOTYPES(name, khkey_t, khval_t)359360#define KHASH_INIT2(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \361__KHASH_TYPE(name, khkey_t, khval_t) \362__KHASH_IMPL(name, SCOPE, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal)363364#define KHASH_INIT(name, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal) \365KHASH_INIT2(name, static kh_inline, khkey_t, khval_t, kh_is_map, __hash_func, __hash_equal)366367/* --- BEGIN OF HASH FUNCTIONS --- */368369/*! @function370@abstract Integer hash function371@param key The integer [khint32_t]372@return The hash value [khint_t]373*/374#define kh_int_hash_func(key) (khint32_t)(key)375/*! @function376@abstract Integer comparison function377*/378#define kh_int_hash_equal(a, b) ((a) == (b))379/*! @function380@abstract 64-bit integer hash function381@param key The integer [khint64_t]382@return The hash value [khint_t]383*/384#define kh_int64_hash_func(key) (khint32_t)((key)>>33^(key)^(key)<<11)385/*! @function386@abstract 64-bit integer comparison function387*/388#define kh_int64_hash_equal(a, b) ((a) == (b))389/*! @function390@abstract const char* hash function391@param s Pointer to a null terminated string392@return The hash value393*/394static kh_inline khint_t __ac_X31_hash_string(const char *s)395{396khint_t h = (khint_t)*s;397if (h) for (++s ; *s; ++s) h = (h << 5) - h + (khint_t)*s;398return h;399}400/*! @function401@abstract Another interface to const char* hash function402@param key Pointer to a null terminated string [const char*]403@return The hash value [khint_t]404*/405#define kh_str_hash_func(key) __ac_X31_hash_string(key)406/*! @function407@abstract Const char* comparison function408*/409#define kh_str_hash_equal(a, b) (strcmp(a, b) == 0)410411static kh_inline khint_t __ac_Wang_hash(khint_t key)412{413key += ~(key << 15);414key ^= (key >> 10);415key += (key << 3);416key ^= (key >> 6);417key += ~(key << 11);418key ^= (key >> 16);419return key;420}421#define kh_int_hash_func2(k) __ac_Wang_hash((khint_t)key)422423/* --- END OF HASH FUNCTIONS --- */424425/* Other convenient macros... */426427/*!428@abstract Type of the hash table.429@param name Name of the hash table [symbol]430*/431#define khash_t(name) kh_##name##_t432433/*! @function434@abstract Initiate a hash table.435@param name Name of the hash table [symbol]436@return Pointer to the hash table [khash_t(name)*]437*/438#define kh_init(name) kh_init_##name()439440/*! @function441@abstract Destroy a hash table.442@param name Name of the hash table [symbol]443@param h Pointer to the hash table [khash_t(name)*]444*/445#define kh_destroy(name, h) kh_destroy_##name(h)446447/*! @function448@abstract Reset a hash table without deallocating memory.449@param name Name of the hash table [symbol]450@param h Pointer to the hash table [khash_t(name)*]451*/452#define kh_clear(name, h) kh_clear_##name(h)453454/*! @function455@abstract Resize a hash table.456@param name Name of the hash table [symbol]457@param h Pointer to the hash table [khash_t(name)*]458@param s New size [khint_t]459*/460#define kh_resize(name, h, s) kh_resize_##name(h, s)461462/*! @function463@abstract Insert a key to the hash table.464@param name Name of the hash table [symbol]465@param h Pointer to the hash table [khash_t(name)*]466@param k Key [type of keys]467@param r Extra return code: -1 if the operation failed;4680 if the key is present in the hash table;4691 if the bucket is empty (never used); 2 if the element in470the bucket has been deleted [int*]471@return Iterator to the inserted element [khint_t]472*/473#define kh_put(name, h, k, r) kh_put_##name(h, k, r)474475/*! @function476@abstract Retrieve a key from the hash table.477@param name Name of the hash table [symbol]478@param h Pointer to the hash table [khash_t(name)*]479@param k Key [type of keys]480@return Iterator to the found element, or kh_end(h) if the element is absent [khint_t]481*/482#define kh_get(name, h, k) kh_get_##name(h, k)483484/*! @function485@abstract Remove a key from the hash table.486@param name Name of the hash table [symbol]487@param h Pointer to the hash table [khash_t(name)*]488@param k Iterator to the element to be deleted [khint_t]489*/490#define kh_del(name, h, k) kh_del_##name(h, k)491492/*! @function493@abstract Test whether a bucket contains data.494@param h Pointer to the hash table [khash_t(name)*]495@param x Iterator to the bucket [khint_t]496@return 1 if containing data; 0 otherwise [int]497*/498#define kh_exist(h, x) (!__ac_iseither((h)->flags, (x)))499500/*! @function501@abstract Get key given an iterator502@param h Pointer to the hash table [khash_t(name)*]503@param x Iterator to the bucket [khint_t]504@return Key [type of keys]505*/506#define kh_key(h, x) ((h)->keys[x])507508/*! @function509@abstract Get value given an iterator510@param h Pointer to the hash table [khash_t(name)*]511@param x Iterator to the bucket [khint_t]512@return Value [type of values]513@discussion For hash sets, calling this results in segfault.514*/515#define kh_val(h, x) ((h)->vals[x])516517/*! @function518@abstract Alias of kh_val()519*/520#define kh_value(h, x) ((h)->vals[x])521522/*! @function523@abstract Get the start iterator524@param h Pointer to the hash table [khash_t(name)*]525@return The start iterator [khint_t]526*/527#define kh_begin(h) (khint_t)(0)528529/*! @function530@abstract Get the end iterator531@param h Pointer to the hash table [khash_t(name)*]532@return The end iterator [khint_t]533*/534#define kh_end(h) ((h)->n_buckets)535536/*! @function537@abstract Get the number of elements in the hash table538@param h Pointer to the hash table [khash_t(name)*]539@return Number of elements in the hash table [khint_t]540*/541#define kh_size(h) ((h)->size)542543/*! @function544@abstract Get the number of buckets in the hash table545@param h Pointer to the hash table [khash_t(name)*]546@return Number of buckets in the hash table [khint_t]547*/548#define kh_n_buckets(h) ((h)->n_buckets)549550/*! @function551@abstract Iterate over the entries in the hash table552@param h Pointer to the hash table [khash_t(name)*]553@param kvar Variable to which key will be assigned554@param vvar Variable to which value will be assigned555@param code Block of code to execute556*/557#define kh_foreach(h, kvar, vvar, code) { khint_t __i; \558for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \559if (!kh_exist(h,__i)) continue; \560(kvar) = kh_key(h,__i); \561(vvar) = kh_val(h,__i); \562code; \563} }564565/*! @function566@abstract Iterate over the values in the hash table567@param h Pointer to the hash table [khash_t(name)*]568@param vvar Variable to which value will be assigned569@param code Block of code to execute570*/571#define kh_foreach_value(h, vvar, code) { khint_t __i; \572for (__i = kh_begin(h); __i != kh_end(h); ++__i) { \573if (!kh_exist(h,__i)) continue; \574(vvar) = kh_val(h,__i); \575code; \576} }577578/* More conenient interfaces */579580/*! @function581@abstract Instantiate a hash set containing integer keys582@param name Name of the hash table [symbol]583*/584#define KHASH_SET_INIT_INT(name) \585KHASH_INIT(name, khint32_t, char, 0, kh_int_hash_func, kh_int_hash_equal)586587/*! @function588@abstract Instantiate a hash map containing integer keys589@param name Name of the hash table [symbol]590@param khval_t Type of values [type]591*/592#define KHASH_MAP_INIT_INT(name, khval_t) \593KHASH_INIT(name, khint32_t, khval_t, 1, kh_int_hash_func, kh_int_hash_equal)594595/*! @function596@abstract Instantiate a hash map containing 64-bit integer keys597@param name Name of the hash table [symbol]598*/599#define KHASH_SET_INIT_INT64(name) \600KHASH_INIT(name, khint64_t, char, 0, kh_int64_hash_func, kh_int64_hash_equal)601602/*! @function603@abstract Instantiate a hash map containing 64-bit integer keys604@param name Name of the hash table [symbol]605@param khval_t Type of values [type]606*/607#define KHASH_MAP_INIT_INT64(name, khval_t) \608KHASH_INIT(name, khint64_t, khval_t, 1, kh_int64_hash_func, kh_int64_hash_equal)609610typedef const char *kh_cstr_t;611/*! @function612@abstract Instantiate a hash map containing const char* keys613@param name Name of the hash table [symbol]614*/615#define KHASH_SET_INIT_STR(name) \616KHASH_INIT(name, kh_cstr_t, char, 0, kh_str_hash_func, kh_str_hash_equal)617618/*! @function619@abstract Instantiate a hash map containing const char* keys620@param name Name of the hash table [symbol]621@param khval_t Type of values [type]622*/623#define KHASH_MAP_INIT_STR(name, khval_t) \624KHASH_INIT(name, kh_cstr_t, khval_t, 1, kh_str_hash_func, kh_str_hash_equal)625626#endif /* __AC_KHASH_H */627628629