get
This commit is contained in:
3 files changed
+49
-7
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
|
||||
+13
-7
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user