map.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (C) 2025 Midokura Japan KK. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <stdint.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include "map.h"
  11. static uintmax_t *
  12. map_find_slot(struct map *m, const char *name)
  13. {
  14. size_t i;
  15. for (i = 0; i < m->nentries; i++) {
  16. if (!strcmp(m->entries[i].k, name)) {
  17. return &m->entries[i].v;
  18. }
  19. }
  20. return NULL;
  21. }
  22. static void
  23. map_append(struct map *m, const char *k, uintmax_t v)
  24. {
  25. m->entries = realloc(m->entries, (m->nentries + 1) * sizeof(*m->entries));
  26. if (m->entries == NULL) {
  27. exit(1);
  28. }
  29. struct map_entry *e = &m->entries[m->nentries++];
  30. e->k = k;
  31. e->v = v;
  32. }
  33. void
  34. map_set(struct map *m, const char *k, uintmax_t v)
  35. {
  36. uintmax_t *p = map_find_slot(m, k);
  37. if (p != NULL) {
  38. fprintf(stderr, "duplicated id \"%s\"\n", k);
  39. exit(1);
  40. }
  41. map_append(m, k, v);
  42. }
  43. uintmax_t
  44. map_get(struct map *m, const char *k)
  45. {
  46. uintmax_t *p = map_find_slot(m, k);
  47. if (p == NULL) {
  48. fprintf(stderr, "id \"%s\" not found\n", k);
  49. exit(1);
  50. }
  51. return *p;
  52. }