Files
csse2310-a4/stringstore.c
2025-03-21 10:59:34 +10:00

73 lines
1.9 KiB
C

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stringstore.h>
typedef struct StringStoreContents {
char *key;
char *value;
} StringStoreContents;
struct StringStore {
struct StringStoreContents *contents;
int size;
};
StringStore *stringstore_init(void) {
StringStore *stringStore = (StringStore *)malloc(sizeof(StringStore));
memset(stringStore, 0, sizeof(StringStore));
stringStore->size = 0;
stringStore->contents =
(StringStoreContents *)malloc(sizeof(StringStoreContents));
return stringStore;
}
StringStore *stringstore_free(StringStore *store) {
for (int i = 0; i < store->size; i++) {
free(store->contents[i].key);
free(store->contents[i].value);
}
free(store->contents);
free(store);
return NULL;
}
int stringstore_add(StringStore *store, const char *key, const char *value) {
stringstore_delete(store, key);
store->contents = (StringStoreContents *)realloc(
store->contents, sizeof(StringStoreContents) * (store->size + 1));
if ((store->contents[store->size].key = strdup(key)) == NULL ||
(store->contents[store->size].value = strdup(value)) == NULL) {
return 0;
}
store->size++;
return 1;
}
const char *stringstore_retrieve(StringStore *store, const char *key) {
for (int i = 0; i < store->size; i++) {
if (strcmp(store->contents[i].key, key) == 0) {
return store->contents[i].value;
}
}
return NULL;
}
int stringstore_delete(StringStore *store, const char *key) {
for (int i = 0; i < store->size; i++) {
if (strcmp(store->contents[i].key, key) == 0) {
free(store->contents[i].key);
free(store->contents[i].value);
if ((i + 1) < store->size) {
store->contents[i] = store->contents[i + 1];
}
store->size--;
return 1;
}
}
return 0;
}