-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkvdb.c
111 lines (94 loc) · 2.17 KB
/
kvdb.c
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
// A simple KeyValue DataBase
//
// Goals:
// - simple small C code
// - file format: key va lue\n
// - key lookup
// - key prefix (un-ordered)
// - range search (un-ordered)
// - append only filesystem based
// - many readers same machine
// - distributable ("tail -f")
// - single writer
// - multi reader concurrent
// - append transaction - A(CI)D
// - crash safe/recoverable
// - timestamped
//
// Non-Goals:
// - binary key/data with 0 NL?
// - thread safe
// - memory sharing
// - (multiple writers)
// - super efficiency
// RECORD==line
// key SPCS timestamp SPCS val u e\n
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
typedef struct kv {
char *k, *v;
} kv;
#define KVSIZE 1024
// we own all values
kv kvstore[KVSIZE]= {0};
int kvn= 0, kvorder= 1;
// own: free k v later
void kv_put(char* k, char* v, int own) {
assert(kvn<=KVSIZE);
kvstore[kvn].k= own?k:strdup(k);
kvstore[kvn].v= own?v:strdup(v);
kvn++;
// TODO: added is highest?
kvorder= 0;
}
char* kv_get(char* k) {
assert(k);
for(int i=0; i<kvn; i++) {
if (0==strcmp(kvstore[i].k, k)) return kvstore[i].v;
}
// no match
return NULL;
}
// TODO: test
kv kv_read(FILE* f) {
char *key=0, *val=0;
long ts=0;
int n= fscanf(f, "%ms %ld %ms\n", &key, &ts, &val);
printf("READ:\n key=%s\n ts=%ld\n val=%s\n", key, ts, val);
// TODO: return ts?
// TODO: deleted marker?
return (kv){key, val};
}
void kv_readfile(FILE* f) {
char* ln= 0; size_t z=0;
while(getline(&ln, &z, f)>=0) {
char *key=0, *val=0;
long ts=0;
int n= sscanf(ln, "%ms %ld %m[^\n]\n", &key, &ts, &val);
printf("READ:\n key=%s\n ts=%ld\n val=%s\n", key, ts, val);
// TODO: return ts?
// TODO: deleted marker?
kv r= {key, val};
assert(kvn<KVSIZE);
kvstore[kvn]= r;
kvn++;
}
free(ln);
}
// tests
int main(int argc, char** argv) {
char* k= "0000001st";
char* v= "first";
kv_put(k, v, 0);
kv_put("0000002nd", "second", 0);
char* r= kv_get(k);
char* kk= "0000002nd";
char* rr= kv_get(kk);
printf("%s => %s\n", k, r);
printf("%s => %s\n", kk, rr);
// get non-exist
printf("%s => %s\n", "0000003nd", kv_get("0000003nd"));
kv_readfile(stdin);
return 0;
}