Advertisement
Madmouse

A draft for dicts in C

Dec 13th, 2015
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.97 KB | None | 0 0
  1. typedef struct dict_entry {
  2.     char* key;
  3.     void* value;
  4. } dict_entry_t;
  5.  
  6. typedef struct dict_array {
  7.     int size;
  8.     dict_entry_t** entry;
  9. } dict_t;
  10.  
  11. dict_t* dict()
  12. {
  13.     dict_t* d = malloc(sizeof(dict_t));
  14.     d->size = 0;
  15.     return d;
  16. }
  17.  
  18. bool dict_in(dict_t* d, char* key)
  19. {
  20.     for(int i = 1;i <= d->size;i++)
  21.         if(strcmp(key, d->entry[i]->key) == 0)
  22.             return true;
  23.     return false;
  24. }
  25.  
  26. bool dict_add(dict_t* d, char* key, void* value)
  27. {
  28.     if(dict_in(d, key)) return false;
  29.     d->size++;
  30.     d->entry[d->size] = malloc(sizeof(dict_entry_t));
  31.     d->entry[d->size]->key = key;
  32.     d->entry[d->size]->value = value;
  33.     return true;
  34. }
  35.  
  36. void* dict_value(dict_t* d, char* key)
  37. {
  38.     for(int i = 1;i <= d->size;i++)
  39.         if(strcmp(key, d->entry[i]->key) == 0)
  40.             return d->entry[i]->value;
  41.     return (void*) -1;
  42. }
  43.  
  44. void dict_copy(dict_t* from, dict_t* to)
  45. {
  46.     for(int i = 1;i <= from->size;i++)
  47.         dict_add(to, from->entry[i]->key, from->entry[i]->value);
  48. }
  49.  
  50. void dict_free(dict_t* d)
  51. {
  52.     for(int i = 1;i <= d->size;i++)
  53.         free(d->entry[i]);
  54.     free(d);
  55. }
  56.  
  57. void dict_remove(dict_t* d, char* key)
  58. {
  59.     for(int i = 0, c = 0;i <= d->size + 1;i++)
  60.     {
  61.         if(strcmp(d->entry[i]->key, key) == 0)
  62.         {
  63.             free(d->entry[i]);
  64.             d->size--;
  65.         }
  66.         else
  67.         {
  68.             d->entry[c] = d->entry[i];
  69.             c++;
  70.         }
  71.     }
  72. }
  73.  
  74. bool dict_assign(dict_t* d, char* key, void* value)
  75. {
  76.     for(int i = 1;i <= d->size;i++)
  77.     {
  78.         if(strcmp(key, d->entry[i]->key) == 0)
  79.         {
  80.             d->entry[i]->value = value;
  81.             return true;
  82.         }
  83.     }
  84.     return false;
  85. }
  86.  
  87.  
  88. void main(void)
  89. {
  90.     dict_t* d = dict();
  91.     dict_add(d, "name", "Aaron Yool");
  92.     dict_add(d, "age", 23);
  93.     dict_assign(d, "name", "MadMouse");
  94.     printf("name: %s age: %i\n", dict_value(d, "name"), dict_value(d, "age"));
  95.     dict_free(d);
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement