htable.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * Hash table implementation.
  3. *
  4. * This code is hack...ahem, built upon Klib:
  5. * https://github.com/attractivechaos/klib/blob/master/khash.h
  6. *
  7. * After trying several hash map implementations, none met all the requirements
  8. * (small, single-file; accept arbitrarily-sized elements; not an unsightly
  9. * macro mess; reasonably fast), so I decided to expand a KLib macro and adapt
  10. * it to a data type agnostic model.
  11. *
  12. * This table stores keys and optionally values as unspecified null pointers of
  13. * arbitrary, but fixed, data sizes. For small keys / values of unusual size,
  14. * this is convenient because it avoids creating (and having to manage) a
  15. * pointer for each key and value. Data are all stored inline. The data types
  16. * are set by casting on retrieval.
  17. *
  18. * For larger or variably-sized keys or values, or ones that are not convenient
  19. * to copy into the table, pointers can obviously be used by specifying ptr_t
  20. * key and/or value size.
  21. */
  22. #ifndef _LSUP_HTABLE_H
  23. #define _LSUP_HTABLE_H
  24. #include <stdint.h>
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #include <limits.h>
  28. #include "include/core.h"
  29. #ifdef LSUP_BIG_HTABLE
  30. typedef size_t ht_size_t;
  31. #else
  32. typedef uint32_t ht_size_t;
  33. #endif
  34. /**
  35. * Key hashing function.
  36. *
  37. * Takes a void pointer. The key length is calculated from the ksize value in
  38. * the table.
  39. */
  40. typedef uint64_t (*key_hash_fn_t)(const void *key);
  41. /**
  42. * Key equality function (true: keys are equal).
  43. *
  44. * Takes two void pointers. The key lengths are calculated from the ksize value
  45. * in the table.
  46. */
  47. typedef bool (*key_eq_fn_t)(const void *a, const void *b);
  48. /**
  49. * Hash table type.
  50. *
  51. * Supports up to UINT_MAX entries (~4 billions on most modern machines).
  52. *
  53. * If compiled with -DLSUP_BIG_HTABLE it supports up to size_t entries
  54. * for extremely large in-memory graphs.
  55. */
  56. typedef struct HTable LSUP_HTable;
  57. extern int LSUP_htable_init(
  58. LSUP_HTable *ht, ht_size_t size, uint32_t ksize, uint32_t vsize,
  59. key_hash_fn_t key_hash_fn, key_eq_fn_t key_eq_fn);
  60. extern void LSUP_htable_done(LSUP_HTable *ht);
  61. extern ht_size_t LSUP_htable_get(const LSUP_HTable *ht, void *key);
  62. extern ht_size_t LSUP_htable_put(LSUP_HTable *h, void *key, int *ret);
  63. extern void LSUP_htable_del(LSUP_HTable *h, khint_t x);
  64. #endif