map.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include "map.h"
  2. #include "rb_tree.h"
  3. #include <string.h>
  4. #include "gc_prelude.h"
  5. typedef int (*rb_cmp_t)(void *, void *);
  6. void* new_map(cmp_t compare) {
  7. rb_tree_t *tree = malloc(sizeof(rb_tree_t));
  8. *tree = (rb_tree_t){NULL, (rb_cmp_t)compare, NULL};
  9. return tree;
  10. }
  11. void map_set(void* self, void* key, void* value) {
  12. node_entry_t *iter = rb_tree_find(self, &key);
  13. if (iter == NULL) {
  14. iter = malloc(sizeof(*iter));
  15. iter->key = key;
  16. iter->value = value;
  17. rb_tree_insert(self, iter);
  18. } else {
  19. iter->value = value;
  20. }
  21. }
  22. void* map_get(void* self, void* key) {
  23. node_entry_t *iter = rb_tree_find(self, &key);
  24. if (iter == NULL) return NULL;
  25. return iter->value;
  26. }
  27. void map_erase(void* self, void* key) {
  28. rb_tree_remove(self, key);
  29. }
  30. void* map_begin(void *self) {
  31. return rb_tree_min(self);
  32. }
  33. void* map_next(void *self, void *iter) {
  34. return rb_tree_next(self, iter);
  35. }
  36. void* map_iter_key(void* iter_) {
  37. node_entry_t *iter = iter_;
  38. return iter->key;
  39. }
  40. void* map_iter_value(void* iter_) {
  41. node_entry_t *iter = iter_;
  42. return iter->value;
  43. }
  44. static int dict_cmp(void **a, void** b) {
  45. return strcmp(*a, *b);
  46. }
  47. void* new_dict() {
  48. return new_map(dict_cmp);
  49. }
  50. void dict_set(void* self, const char *key, void* value) {
  51. map_set(self, (void*)key, value);
  52. }
  53. void* dict_get(void* self, const char* key) {
  54. return map_get(self, (void*)key);
  55. }
  56. void dict_erase(void* self, const char* key) {
  57. map_erase(self, (void*)key);
  58. }
  59. void* dict_begin(void *self) {
  60. return map_begin(self);
  61. }
  62. void* dict_next(void *self, void *iter) {
  63. return map_next(self, iter);
  64. }
  65. const char* dict_iter_key(void* iter) {
  66. return map_iter_key(iter);
  67. }
  68. void* dict_iter_value(void* iter) {
  69. return map_iter_value(iter);
  70. }