summaryrefslogtreecommitdiffstats
path: root/test/test_key_value_store.c
blob: de939da8ed59758d7d74289ae325d15c0590531e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <stdio.h>
#include <stdlib.h>

#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;
	char *name;
	char *desc;
} 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)
{
	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(kv_user_name *kv)
{
	if (kv!=NULL)
	{
		free(kv->name);
		free(kv->desc);
		free(kv);
	}
}


int main()
{

	int er;
	uint8_t *res;
	FILE *f;
	int i=0;

	kv_user_name *kv=NULL;

	netbyte_store *nb;

	printf("Start test\n");

	kv = kv_new(1,"Jhony","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.md","w+");
	fwrite(res, 1, nb->size, f);
	fclose(f);

	free(res);
	nb_free(nb);

	printf("End test\n");
	return 0;
}