diff options
author | FreeArtMan <dos21h@gmail.com> | 2017-06-02 16:20:44 +0100 |
---|---|---|
committer | FreeArtMan <dos21h@gmail.com> | 2017-06-02 16:20:44 +0100 |
commit | a877a8ed7b508eb8cc5f7911dfcec8b8612470b3 (patch) | |
tree | 00b901522f01bad243cb14afc2f5ca8698ce5a37 /test/test_key_value_store.c | |
parent | 65fb94f8fd98d343ae49f7d7e576418dba5a5d46 (diff) | |
download | netbytes-a877a8ed7b508eb8cc5f7911dfcec8b8612470b3.tar.gz netbytes-a877a8ed7b508eb8cc5f7911dfcec8b8612470b3.zip |
Fixed memleaks, rearranged some code
Diffstat (limited to 'test/test_key_value_store.c')
-rw-r--r-- | test/test_key_value_store.c | 101 |
1 files changed, 87 insertions, 14 deletions
diff --git a/test/test_key_value_store.c b/test/test_key_value_store.c index 983b3b8..b499c9a 100644 --- a/test/test_key_value_store.c +++ b/test/test_key_value_store.c @@ -3,6 +3,38 @@ #include <netbytes.h> +char *alloc_new_str_s(char *str, size_t size) +{ + char *ret = NULL; + + if (str == NULL) + { + return NULL; + } + + //1MB is enought + if (size > (1024*1024)) + { + return NULL; + } + + ret = malloc(size+1); //extra for 1 zero at then end + if (ret == NULL) + { + return NULL; + } + + memcpy(ret, str, size); + ret[size] = 0; //add zero at the end + + return ret; +} + +char *alloc_new_str(char *str) +{ + return alloc_new_str_s(str, strlen(str)); +} + typedef struct kv_user_name { int id; @@ -12,17 +44,51 @@ typedef struct kv_user_name kv_user_name* kv_new(int id, char *name, char *desc) { - + kv_user_name *ret = NULL; + + ret = malloc(sizeof(kv_user_name)); + if (!ret) + { + return NULL; + } + + ret->id = id; + ret->name = alloc_new_str(name); + ret->desc = alloc_new_str(desc); + + return ret; } netbyte_store* kv_marsh(kv_user_name *kv) { - return NULL; + netbyte_store *nb=NULL; + nb_u8 nb_id; + nb_u8arr nb_name, nb_desc; + + nb = calloc(1,sizeof(netbyte_store)); + nb_init(nb); + + nb_u8_create(&nb_id, kv->id); + nb_add_u8(nb, &nb_id); + nb_u8arr_create(&nb_name, strlen(kv->name), kv->name); + nb_add_u8arr(nb, &nb_name); + nb_u8arr_create(&nb_desc, strlen(kv->desc), kv->desc); + nb_add_u8arr(nb, &nb_desc); + + nb_print(nb); + nb_print(nb); + + return nb; } -void kv_free() +void kv_free(kv_user_name *kv) { - + if (kv!=NULL) + { + free(kv->name); + free(kv->desc); + free(kv); + } } @@ -34,19 +100,26 @@ int main() FILE *f; int i=0; - netbyte_store nb; + kv_user_name *kv=NULL; + + netbyte_store *nb; printf("Start test\n"); - nb_init( &nb ); - f = fopen("test_many.nb","r"); - while (nb_fread( &nb, fileno(f) ) == 0) - { - printf("ITER %d: ", i ); - pr_store( &nb ); - i += 1; - } - fclose( f ); + kv = kv_new(1,"Name","Name of the human"); + nb = kv_marsh(kv); + nb_print(nb); + kv_free(kv); + + //nb_print(nb); + res = nb_create(nb); + + f = fopen("test_kv_save.nd","w+"); + fwrite(res, 1, nb->size, f); + fclose(f); + + free(res); + nb_free(nb); printf("End test\n"); return 0; |