#include "test.h" void hmap_set_replace_and_grow(struct ct *t) { char keybuf[16], valbuf[16], source[] = "copied"; Hmap *h; Hnode *n; Str key; int i; h = hmapalloc(1); for(i = 0; i < 4; i++){ snprint(keybuf, sizeof keybuf, "key%d", i); snprint(valbuf, sizeof valbuf, "value%d", i); key = mkstr(keybuf); hmapset(&h, &key, valbuf, strlen(valbuf)); } for(i = 0; i < 4; i++){ snprint(keybuf, sizeof keybuf, "key%d", i); snprint(valbuf, sizeof valbuf, "value%d", i); key = mkstr(keybuf); n = hmapget(h, &key); if(n == nil || strcmp(n->val, valbuf) != 0) CT_ERRORF(t, "%s: collision chain lost value", keybuf); } key = mkstr("key1"); hmapset(&h, &key, source, strlen(source)); source[0] = 'X'; n = hmapget(h, &key); if(!CT_CHECK(t, n != nil)) goto cleanup; CT_EQ_STR(t, "copied", n->val); key = mkstr("key2"); n = hmapget(h, &key); if(!CT_CHECK(t, n != nil)) goto cleanup; CT_EQ_STR(t, "value2", n->val); key = mkstr("key1"); hmapset(&h, &key, nil, 0); n = hmapget(h, &key); if(!CT_CHECK(t, n != nil)) goto cleanup; CT_EQ_INT(t, 0, n->vlen); CT_EQ_PTR(t, nil, n->val); key = mkstr("missing"); CT_EQ_PTR(t, nil, hmapget(h, &key)); cleanup: hmapfree(h); } void hmap_long_utf8_keys(struct ct *t) { Hmap *h; Hnode *n; Str a, b; int i; for(i = 0; i < Maxrunes-1; i++) a.r[i] = b.r[i] = 0x1f600; a.r[Maxrunes-1] = 0x1f601; b.r[Maxrunes-1] = 0x1f602; a.n = b.n = Maxrunes; h = hmapalloc(1); hmapset(&h, &a, "first", 5); hmapset(&h, &b, "second", 6); n = hmapget(h, &a); if(!CT_CHECK(t, n != nil)) goto cleanup; CT_EQ_STR(t, "first", n != nil ? n->val : nil); n = hmapget(h, &b); if(!CT_CHECK(t, n != nil)) goto cleanup; CT_EQ_STR(t, "second", n != nil ? n->val : nil); cleanup: hmapfree(h); } void hmap_binary_keys_and_invalid_lengths(struct ct *t) { Hmap *h; Hnode *n; Str key, other; h = hmapalloc(1); CT_CHECK(t, h != nil); key.n = 3; key.r[0] = 'a'; key.r[1] = 0; key.r[2] = 'b'; other = key; other.r[2] = 'c'; hmapset(&h, &key, "one", 3); hmapset(&h, &other, "two", 3); n = hmapget(h, &key); if(CT_CHECK(t, n != nil)){ CT_EQ_INT(t, 3, n->klen); CT_EQ_MEM(t, "one", n->val, n->vlen); } n = hmapget(h, &other); if(CT_CHECK(t, n != nil)) CT_EQ_MEM(t, "two", n->val, n->vlen); hmapset(&h, &key, "bad", -1); hmapset(&h, &key, nil, 1); n = hmapget(h, &key); if(CT_CHECK(t, n != nil)) CT_EQ_MEM(t, "one", n->val, n->vlen); CT_EQ_PTR(t, nil, hmapalloc(0)); hmapfree(h); }