build sys, free, delete

This commit is contained in:
SowinskiBraeden committed 2026-07-22 11:59:17 -07:00
1 parent 2bfd812e87
commit 86e4ec1847
5 files changed
+97

No files matched your search

+1
View File
@@ -1 +1,2 @@
bin/*
obj/*
+15
View File
@@ -0,0 +1,15 @@
TARGET = bin/final
SRC = $(wildcard src/*c)
OBJ = $(patsubst src/%.c, obj/%.o, $(SRC))
default: $(TARGET)
clean:
rm -f obj/*.o
rm -f bin/*
$(TARGET): $(OBJ)
gcc -o $@ $?
obj/%.o : src/%.c
gcc -c $< -o $@ -Iinc
+2
View File
@@ -19,5 +19,7 @@ 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);
int kv_delete(kv_t *db, char *key);
int kv_free(kv_t *db);
#endif
+67
View File
@@ -20,6 +20,45 @@ size_t hash(char *val, int capacity)
return hash % capacity;
}
// fn kv_delete
// params:
// - db: a pointer to the db
// - key: pointer to the key value
// returns: index deleted
// -1 if not found
int kv_delete(kv_t *db, char *key)
{
if (!db || !key) return -1;
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 -1;
}
if (e->key &&
e->key != (void*)TOMBSTONE &&
!strcmp(e->key, key))
{
free(e->key);
free(e->val);
db->count--;
e->key = (void*)TOMBSTONE;
e->val = NULL;
return real_idx;
}
}
return -1;
}
// fn kv_get
// params:
@@ -55,6 +94,33 @@ char *kv_get(kv_t *db, char *key)
return NULL;
}
// fn kv_free
// params:
// - db: a pointer to the db
// returns: 0 on success, -1 on failure
int kv_free(kv_t *db)
{
if (!db) return -1;
for (int i = 0; i < db->capacity - 1; ++i)
{
kv_entry_t *e = &db->entries[i];
if (e->key && e->key != (void*)TOMBSTONE)
{
free(e->key);
free(e->val);
e->key = NULL;
e->val = NULL;
}
}
free(db->entries);
free(db);
return 0;
}
// fn kv_put
// params:
// - db: a pointer to the db
@@ -78,6 +144,7 @@ int kv_put(kv_t *db, char *key, char *val)
{
char *newval = strdup(val);
if (!newval) return -1;
free(e->val);
e->val = newval;
return idx;
}
+12
View File
@@ -24,4 +24,16 @@ int main(void)
char *val3 = kv_get(table, "fake");
printf("%s %s %s\n", val, val2, val3);
kv_delete(table, "goodbye");
val = NULL;
val = kv_get(table, "goodbye");
printf("%s %s %s\n", val, val2, val3);
kv_free(table);
table = NULL;
val = kv_get(table, "goodbye");
printf("%d\n", val);
}