StringIntMap.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "StringIntMap.h"
  5. void simInit(StringIntMap* sim) {
  6. sim->capacity = 16;
  7. sim->entries = 0;
  8. sim->stringData = malloc(sizeof(const char*) * sim->capacity);
  9. sim->intData = malloc(sizeof(int) * sim->capacity);
  10. }
  11. void simDelete(StringIntMap* sim) {
  12. free(sim->stringData);
  13. free(sim->intData);
  14. }
  15. bool simSearch(StringIntMap* sim, const char* s, int* mapping) {
  16. for(int i = 0; i < sim->entries; i++) {
  17. if(strcmp(s, sim->stringData[i]) == 0) {
  18. *mapping = sim->intData[i];
  19. return true;
  20. }
  21. }
  22. return false;
  23. }
  24. bool simAdd(StringIntMap* sim, const char* s, int* mapping) {
  25. if(simSearch(sim, s, mapping)) {
  26. return false;
  27. } else if(sim->entries >= sim->capacity) {
  28. sim->capacity *= 2;
  29. sim->stringData = realloc(sim->stringData, sizeof(const char*) * sim->capacity);
  30. sim->intData = realloc(sim->intData, sizeof(int) * sim->capacity);
  31. }
  32. int index = sim->entries++;
  33. sim->stringData[index] = s;
  34. sim->intData[index] = *mapping;
  35. return true;
  36. }