Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
1.4 KiB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "dict.h"
  4. void *dictionary_not_found;
  5. dictionary *dictionary_new(void) {
  6. static int dnf;
  7. if (!dictionary_not_found) {
  8. dictionary_not_found = &dnf;
  9. }
  10. dictionary *out = malloc(sizeof(dictionary));
  11. if(out != NULL) {
  12. *out = (dictionary) {};
  13. } else {
  14. fprintf(stderr, "Out of memory.\n");
  15. abort();
  16. }
  17. return out;
  18. }
  19. static void dictionary_add_keyval(dictionary *in, keyval *kv) {
  20. in->length++;
  21. in->pairs = realloc(in->pairs, sizeof(keyval*) * in->length);
  22. if(in->pairs != NULL) {
  23. in->pairs[in->length-1] = kv;
  24. } else {
  25. fprintf(stderr, "Out of memory.\n");
  26. abort();
  27. }
  28. }
  29. void dictionary_add(dictionary *in, char *key, void *value) {
  30. if(key == NULL) {
  31. fprintf(stderr, "NULL is not a valid key.\n");
  32. abort();
  33. }
  34. dictionary_add_keyval(in, keyval_new(key, value));
  35. }
  36. void *dictionary_find(const dictionary *in, const char *key) {
  37. for (size_t i = 0; i < in->length; i++) {
  38. if (keyval_matches(in->pairs[i], key)) {
  39. return in->pairs[i]->value;
  40. }
  41. }
  42. return dictionary_not_found;
  43. }
  44. dictionary *dictionary_copy(dictionary *in) {
  45. dictionary *out = dictionary_new();
  46. for (size_t i = 0; i < in->length; i++) {
  47. dictionary_add_keyval(out, keyval_copy(in->pairs[i]));
  48. }
  49. return out;
  50. }
  51. void dictionary_free(dictionary *in) {
  52. for (size_t i = 0; i < in->length; i++) {
  53. keyval_free(in->pairs[i]);
  54. }
  55. free(in);
  56. }