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.

91 lines
1.6 KiB

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