hashtable.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Simple hash table implemented in C.
  2. // From: https://github.com/benhoyt/ht
  3. #ifndef _HT_H
  4. #define _HT_H
  5. #include <stdbool.h>
  6. #include <stddef.h>
  7. // Hash table structure: create with ht_create, free with ht_destroy.
  8. typedef struct ht ht;
  9. // Hash table entry (slot may be filled or empty).
  10. typedef struct {
  11. const char* key; // key is NULL if this slot is empty
  12. void* value;
  13. } ht_entry;
  14. // Hash table structure: create with ht_create, free with ht_destroy.
  15. struct ht {
  16. ht_entry* entries; // hash slots
  17. size_t capacity; // size of _entries array
  18. size_t length; // number of items in hash table
  19. };
  20. ht* ht_create(void);
  21. void ht_destroy(ht* table);
  22. // Get item with given key (NUL-terminated) from hash table. Return
  23. // value (which was set with ht_set), or NULL if key not found.
  24. void* ht_get(ht* table, const char* key);
  25. // Set item with given key (NUL-terminated) to value (which must not
  26. // be NULL). Return address of copied key, or NULL if out of memory.
  27. const char* ht_set(ht* table, const char* key, void* value);
  28. size_t ht_length(ht* table); // Return number of items
  29. // Hash table iterator: create with ht_iterator, iterate with ht_next.
  30. typedef struct {
  31. const char* key; // current key
  32. void* value; // current value
  33. // Don't use these fields directly.
  34. ht* _table; // reference to hash table being iterated
  35. size_t _index; // current index into ht._entries
  36. } hti;
  37. // Return new hash table iterator (for use with ht_next).
  38. hti ht_iterator(ht* table);
  39. // Move iterator to next item in hash table, update iterator's key
  40. // and value to current item, and return true. If there are no more
  41. // items, return false. Don't call ht_set during iteration.
  42. bool ht_next(hti* it);
  43. #endif // _HT_H