dict.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Borrowed from https://github.com/b-k/21st-Century-Examples
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include "dict.h"
  5. void *dictionary_not_found;
  6. dictionary *dictionary_new (void){
  7. static int dnf;
  8. if (!dictionary_not_found) dictionary_not_found = &dnf;
  9. dictionary *out= malloc(sizeof(dictionary));
  10. *out= (dictionary){ .pairs=NULL };
  11. return out;
  12. }
  13. static void dictionary_add_keyval(dictionary *in, keyval *kv){
  14. in->length++;
  15. in->pairs = realloc(in->pairs, sizeof(keyval*)*in->length);
  16. in->pairs[in->length-1] = kv;
  17. }
  18. void dictionary_add(dictionary *in, char *key, void *value){
  19. if (!key){fprintf(stderr, "NULL is not a valid key.\n"); abort();}
  20. dictionary_add_keyval(in, keyval_new(key, value));
  21. }
  22. void *dictionary_find(dictionary const *in, char const *key){
  23. for (int i=0; i< in->length; i++)
  24. if (keyval_matches(in->pairs[i], key))
  25. return in->pairs[i]->value;
  26. return NULL;
  27. }
  28. dictionary *dictionary_copy(dictionary *in){
  29. dictionary *out = dictionary_new();
  30. for (int i=0; i< in->length; i++)
  31. dictionary_add_keyval(out, keyval_copy(in->pairs[i]));
  32. return out;
  33. }
  34. void dictionary_free(dictionary *in){
  35. for (int i=0; i< in->length; i++)
  36. keyval_free(in->pairs[i]);
  37. free(in->pairs);
  38. free(in);
  39. }