cb_hashmap.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * SPDX-License-Identifier: Apache-2.0
  3. *
  4. * Change Logs:
  5. * Date Author Notes
  6. * 2022-03-16 tyx first implementation
  7. */
  8. #ifndef CB_HASHMAP_H_
  9. #define CB_HASHMAP_H_
  10. #include "cb_list.h"
  11. #ifdef __cplusplus
  12. extern "C" {
  13. #endif
  14. struct cb_hashmap_item
  15. {
  16. cb_hlist_t n;
  17. const void *key;
  18. };
  19. typedef struct cb_hashmap_item cb_hashmap_item_t;
  20. #define CB_HASHMAP_ITER_INIT(_object) { 0, (_object)->table[0].hh.first, _object }
  21. struct cb_hashmap_ops
  22. {
  23. cb_uint32_t (*hash)(const void *k);
  24. long (*cmp)(const void *k1, const void *k2);
  25. };
  26. struct cb_hashmap_table
  27. {
  28. cb_hhead_t hh;
  29. };
  30. struct cb_hashmap
  31. {
  32. struct cb_hashmap_table *table;
  33. cb_size_t table_size;
  34. const struct cb_hashmap_ops *ops;
  35. };
  36. typedef struct cb_hashmap cb_hashmap_t;
  37. struct cb_hashmap_iter
  38. {
  39. cb_size_t index;
  40. cb_hlist_t *node;
  41. cb_hashmap_t *hashmap;
  42. };
  43. typedef struct cb_hashmap_iter cb_hashmap_iter_t;
  44. // hashmap
  45. cb_hashmap_t *cb_hashmap_init(cb_hashmap_t *object, struct cb_hashmap_table *table,
  46. cb_size_t table_size, const struct cb_hashmap_ops *ops);
  47. cb_size_t cb_hashmap_size(cb_hashmap_t *object);
  48. void cb_hashmap_put(cb_hashmap_t *object, cb_hashmap_item_t *item);
  49. cb_hashmap_item_t *cb_hashmap_replace(cb_hashmap_t *object, cb_hashmap_item_t *elem);
  50. cb_hashmap_item_t *cb_hashmap_get(cb_hashmap_t *object, const void *key);
  51. cb_hashmap_item_t *cb_hashmap_remove(cb_hashmap_t *object, const void *key);
  52. void cb_hashmap_item_remove(cb_hashmap_item_t *item);
  53. void cb_hashmap_remove_all(cb_hashmap_t *object, void (*free_item)(cb_hashmap_t *, cb_hashmap_item_t *));
  54. cb_hashmap_item_t *cb_hashmap_iterator(cb_hashmap_iter_t *ctx);
  55. // item
  56. cb_hashmap_item_t *cb_hashmap_item_init(cb_hashmap_item_t *item, const void *key);
  57. cb_hashmap_iter_t *cb_hashmap_iter_init(cb_hashmap_t *object, cb_hashmap_iter_t *iter);
  58. #ifdef __cplusplus
  59. }
  60. #endif
  61. #endif