-
Notifications
You must be signed in to change notification settings - Fork 0
/
kvstore.c
105 lines (90 loc) · 1.87 KB
/
kvstore.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
#include "kvstore.h"
long lookup_key(char *key)
{
/*XXX We want this on stack*/
char actual_key[512];
struct stat sbuf;
MAKE_KEY(actual_key, key);
if(stat(actual_key, &sbuf) < 0)
return -1;
return sbuf.st_size;
}
long open_key(char *key){
char actual_key[512];
int fd;
MAKE_KEY(actual_key, key);
fd = open(actual_key, O_RDWR | O_CREAT | O_EXCL, 0666);
if(fd < 0){
perror("open");
return -1;
}
close(fd);
return 0;
}
long put_key(char *key, char *val, int size)
{
char actual_key[512];
int fd;
MAKE_KEY(actual_key, key);
fd = open(actual_key, O_RDWR | O_CREAT | O_EXCL, 0666);
if(fd < 0){
perror("open");
return -1;
}
if(write(fd, val, size) < 0){
perror("write");
return -1;
}
close(fd);
return 0;
}
long create_key(char *key){
char actual_key[512];
int fd;
MAKE_KEY(actual_key, key);
fd = open(actual_key, O_RDWR | O_CREAT | O_EXCL, 0666);
if(fd < 0){
perror("open");
return -1;
}
close(fd);
return 0;
}
long get_key(char *key, char *val)
{
char actual_key[512];
int fd, size;
struct stat sbuf;
MAKE_KEY(actual_key, key);
fd = open(actual_key, O_RDWR, 0666);
if(fd < 0){
perror("open");
return -1;
}
if(fstat(fd, &sbuf) < 0){
perror("stat");
exit(-1);
}
size = sbuf.st_size;
if(size < 4096)
size = 4096;
if(read(fd, val, size) < 0){
perror("read");
return -1;
}
close(fd);
return 0;
}
long rename_key(char *old, char *new)
{
char actual_old[512], actual_new[512];
MAKE_KEY(actual_old, old);
MAKE_KEY(actual_new, new);
return rename(actual_old, actual_new);
}
long delete_key(char *key)
{
char actual_key[512];
MAKE_KEY(actual_key, key);
return unlink(actual_key);
}