map.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include "map.h"
  4. static void
  5. map_dispose_free(Disposer *disposer, uint32_t key_len, void *dat)
  6. {
  7. void *val = map_val(dat, key_len);
  8. if (disposer)
  9. disposer->dispose(val, disposer->extra);
  10. free(dat);
  11. }
  12. void
  13. map_dispose(Map *map)
  14. {
  15. set_dispose(map, map_dispose_free);
  16. }
  17. Nit_error
  18. map_add(Map *map, uint32_t key_len, const void *key, void *val)
  19. {
  20. void *dat = malloc(key_len + sizeof(val));
  21. Nit_error error;
  22. if (!dat)
  23. return NIT_ERROR_MEMORY;
  24. memcpy(dat, key, key_len);
  25. memcpy(((char *) dat) + key_len, &val, sizeof(val));
  26. if ((error = set_add(map, key_len, dat))) {
  27. free(dat);
  28. return error;
  29. }
  30. return error;
  31. }
  32. Nit_error
  33. map_remove(Map *map, uint32_t key_len, const void *key, void **val)
  34. {
  35. Nit_error error;
  36. void *tmp;
  37. *val = (void *) key;
  38. if ((error = set_remove(map, key_len, val)))
  39. return error;
  40. tmp = *val;
  41. *val = map_val(tmp, key_len);
  42. free(tmp);
  43. return error;
  44. }
  45. int
  46. map_get(const Map *map, uint32_t key_len, const void *key, void **val)
  47. {
  48. void *tmp;
  49. *val = (void *) key;
  50. if (!set_get(map, key_len, val))
  51. return 0;
  52. tmp = *val;
  53. *val = map_val(tmp, key_len);
  54. return 1;
  55. }
  56. void *
  57. map_val(void *dat, uint32_t key_len)
  58. {
  59. return *(void **) ((char *) dat + key_len);
  60. }