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.

87 lines
1.5 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. keyval **tmp = realloc(in->pairs, sizeof(keyval*) * in->length);
  22. if(tmp != NULL) {
  23. in->pairs = tmp;
  24. tmp = NULL;
  25. in->pairs[in->length-1] = kv;
  26. } else {
  27. fprintf(stderr, "Out of memory.\n");
  28. abort();
  29. }
  30. }
  31. void dictionary_add(dictionary *in, char *key, void *value) {
  32. if(key == NULL) {
  33. fprintf(stderr, "NULL is not a valid key.\n");
  34. abort();
  35. }
  36. dictionary_add_keyval(in, keyval_new(key, value));
  37. }
  38. void *dictionary_find(const dictionary *in, const char *key) {
  39. for (size_t i = 0; i < in->length; i++) {
  40. if (keyval_matches(in->pairs[i], key)) {
  41. return in->pairs[i]->value;
  42. }
  43. }
  44. return dictionary_not_found;
  45. }
  46. dictionary *dictionary_copy(dictionary *in) {
  47. dictionary *out = dictionary_new();
  48. for (size_t i = 0; i < in->length; i++) {
  49. dictionary_add_keyval(out, keyval_copy(in->pairs[i]));
  50. }
  51. return out;
  52. }
  53. void dictionary_free(dictionary *in) {
  54. for (size_t i = 0; i < in->length; i++) {
  55. keyval_free(in->pairs[i]);
  56. }
  57. free(in->pairs);
  58. free(in);
  59. }