loa

Virtual machine for the Logic of Assumptions
git clone git://juanmeleiro.mat.br/loa
Log | Files | Refs

assoc.c (1445B)


      1 #include "assoc.h"
      2 
      3 struct cell {
      4 	symbol key;
      5 	void *value;
      6 	struct cell *next;
      7 };
      8 
      9 struct assoc {
     10 	struct cell *cells;
     11 };
     12 
     13 assoc*
     14 new_assoc(void)
     15 {
     16 	return calloc(1, sizeof(struct assoc));
     17 }
     18 
     19 struct cell*
     20 new_cell(symbol s, void *v)
     21 {
     22 	struct cell *c = malloc(sizeof(struct cell));
     23 	c->key = s;
     24 	c->value = v;
     25 	c->next = NULL;
     26 	return c;
     27 }
     28 
     29 void
     30 assoc_set(assoc* a, symbol s, void* v)
     31 {
     32 	if (a->cells == NULL) {
     33 		a->cells = new_cell(s, v);
     34 	} else {
     35 		struct cell *c = a->cells;
     36 		while (1) {
     37 			if (c->key == s) {
     38 				c->value = v;
     39 				break;
     40 			} else if (c->next == NULL) {
     41 				c->next = new_cell(s, v);
     42 				break;
     43 			} else {
     44 				c = c->next;
     45 				continue;
     46 			}
     47 		}
     48 	}
     49 }
     50 
     51 void*
     52 get(struct cell *c, symbol s)
     53 {
     54 	if (c == NULL)
     55 		return NULL;
     56 	else if (c->key == s)
     57 		return c->value;
     58 	else if (c->next == NULL)
     59 		return NULL;
     60 	else
     61 		return get(c->next, s);
     62 }
     63 
     64 void*
     65 assoc_get(assoc* a, symbol s)
     66 {
     67 	return get(a->cells, s);
     68 }
     69 
     70 size_t
     71 get_amount_of_keys(assoc* a)
     72 {
     73 	size_t amount;
     74 	struct cell *c;
     75 	for (amount = 0, c = a->cells; c; c = c->next, amount++);
     76 	return amount;
     77 }
     78 
     79 symbol*
     80 get_keys(assoc* a)
     81 {
     82 	struct cell *c;
     83 	size_t i;
     84 	symbol *res = malloc(sizeof(symbol)*get_amount_of_keys(a));
     85 	for (i = 0, c = a->cells; c; res[i++] = c->key, c = c->next);
     86 	return res;
     87 }
     88 
     89 void
     90 free_cells(struct cell *c)
     91 {
     92 	if (c->next)
     93 		free_cells(c->next);
     94 	free(c);
     95 }
     96 
     97 void
     98 free_assoc(assoc *a)
     99 {
    100 	if (a->cells)
    101 		free_cells(a->cells);
    102 	free(a);
    103 }
    104 
    105