void func_dict_union(void) { cData * args; cDict * dict1, * dict2, *d; if (!func_init_2(&args, DICT, DICT)) return; dict1 = dict_dup(DICT1); dict2 = dict_dup(DICT2); pop(2); /* dict_union will discard the dicts */ d = dict_union(dict1, dict2); push_dict(d); dict_discard(d); }
/* WARNING: This will discard both arguments! */ cDict *dict_union (cDict *d1, cDict *d2) { int i, pos; Bool swap; if (d2->keys->len > d1->keys->len) { cDict *t; t=d2; d2=d1; d1=t; swap = NO; } else { swap = YES; } d1=dict_prep(d1); for (i=0; i<d2->keys->len; i++) { cData *key=&d2->keys->el[i], *value=&d2->values->el[i]; pos = search(d1, key); /* forget the add if it's already there */ if (pos != F_FAILURE) { /* ... but if the args are in the wrong order, we want to overwrite the key */ if (swap) d1->values = list_replace(d1->values, pos, value); continue; } /* Add the key and value to the list. */ d1->keys = list_add(d1->keys, key); d1->values = list_add(d1->values, value); /* Check if we should resize the hash table. */ if (d1->keys->len > d1->hashtab_size) increase_hashtab_size(d1); else insert_key(d1, d1->keys->len - 1); } dict_discard(d2); return d1; }