diff --git a/inc/kv.h b/inc/kv.h index 94cd1bb..245d31f 100644 --- a/inc/kv.h +++ b/inc/kv.h @@ -18,5 +18,6 @@ typedef struct kv_t *kv_init(size_t capacity); int kv_put(kv_t *db, char *key, char *val); +char *kv_get(kv_t *db, char *key); #endif diff --git a/src/kv.c b/src/kv.c index 8de4dd7..ab5590e 100644 --- a/src/kv.c +++ b/src/kv.c @@ -20,6 +20,41 @@ size_t hash(char *val, int capacity) return hash % capacity; } + +// fn kv_get +// params: +// - db: a pointer to the db +// - key: pointer to the key value +// returns: pointer to the key +// NULL if not found +char *kv_get(kv_t *db, char *key) +{ + if (!db || !key) return NULL; + + size_t idx = hash(key, db->capacity); + + for (int i = 0; i < db->capacity - 1; ++i) + { + size_t real_idx = (idx + i) % db->capacity; + + kv_entry_t *e = &db->entries[real_idx]; + + if (e->key == NULL) + { + return NULL; + } + + if (e->key && + e->key != (void*)TOMBSTONE && + !strcmp(e->key, key)) + { + return e->val; + } + } + + return NULL; +} + // fn kv_put // params: // - db: a pointer to the db diff --git a/src/main.c b/src/main.c index 2204e24..c60d25d 100644 --- a/src/main.c +++ b/src/main.c @@ -11,11 +11,17 @@ int main(void) kv_put(table, "hello", "people"); kv_put(table, "goodbye", "world"); - for (int i = 0; i < table->capacity; ++i) - { - if (table->entries[i].key) - { - printf("[%d] %s: %s\n", i, table->entries[i].key, table->entries[i].val); - } - } + // for (int i = 0; i < table->capacity; ++i) + // { + // if (table->entries[i].key) + // { + // printf("[%d] %s: %s\n", i, table->entries[i].key, table->entries[i].val); + // } + // } + + char *val = kv_get(table, "hello"); + char *val2 = kv_get(table, "goodbye"); + char *val3 = kv_get(table, "fake"); + + printf("%s %s %s\n", val, val2, val3); }