5c34a57347dfd6854e418263cd7464d2954d8775
[awesomized/libmemcached] / lib / memcached_storage.c
1 /*
2 Memcached library
3
4 memcached_set()
5 memcached_replace()
6 memcached_add()
7
8 */
9
10 #include <memcached.h>
11
12 static memcached_return memcached_send(memcached_st *ptr,
13 char *key, size_t key_length,
14 char *value, size_t value_length,
15 time_t expiration,
16 uint16_t flags,
17 char *verb)
18 {
19 size_t write_length;
20 ssize_t sent_length;
21 memcached_return rc;
22 char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
23 unsigned int server_key;
24
25 rc= memcached_connect(ptr);
26 assert(value);
27 assert(value_length);
28
29 if (rc != MEMCACHED_SUCCESS)
30 return rc;
31
32 server_key= memcached_generate_hash(key, key_length) % ptr->number_of_hosts;
33
34 write_length= snprintf(buffer, MEMCACHED_DEFAULT_COMMAND_SIZE,
35 "%s %.*s %u %u %u\r\n", verb,
36 key_length, key, flags, expiration, value_length);
37 if ((sent_length= write(ptr->hosts[server_key].fd, buffer, write_length)) == -1)
38 {
39 fprintf(stderr, "failed %s on %.*s: %s\n", verb, key_length+1, key, strerror(errno));
40
41 return MEMCACHED_WRITE_FAILURE;
42 }
43 assert(write_length == sent_length);
44
45 WATCHPOINT;
46 printf("About to push %.*s\n", value_length, value);
47 WATCHPOINT;
48 if ((sent_length= write(ptr->hosts[server_key].fd, value, value_length)) == -1)
49 {
50 fprintf(stderr, "failed %s on %.*s: %s\n", verb, key_length+1, key, strerror(errno));
51
52 return MEMCACHED_WRITE_FAILURE;
53 }
54 assert(value_length == sent_length);
55 if ((sent_length= write(ptr->hosts[server_key].fd, "\r\n", 2)) == -1)
56 {
57 fprintf(stderr, "failed %s on %.*s: %s\n", verb, key_length+1, key, strerror(errno));
58
59 return MEMCACHED_WRITE_FAILURE;
60 }
61 assert(2 == sent_length);
62
63 sent_length= read(ptr->hosts[server_key].fd, buffer, MEMCACHED_DEFAULT_COMMAND_SIZE);
64
65 if (sent_length && buffer[0] == 'S') /* STORED */
66 return MEMCACHED_SUCCESS;
67 else if (write_length && buffer[0] == 'N') /* NOT_STORED */
68 return MEMCACHED_NOTSTORED;
69 else
70 return MEMCACHED_READ_FAILURE;
71 }
72
73 memcached_return memcached_set(memcached_st *ptr, char *key, size_t key_length,
74 char *value, size_t value_length,
75 time_t expiration,
76 uint16_t flags)
77 {
78 return memcached_send(ptr, key, key_length, value, value_length,
79 expiration, flags, "set");
80 }
81
82 memcached_return memcached_add(memcached_st *ptr, char *key, size_t key_length,
83 char *value, size_t value_length,
84 time_t expiration,
85 uint16_t flags)
86 {
87 return memcached_send(ptr, key, key_length, value, value_length,
88 expiration, flags, "add");
89 }
90
91 memcached_return memcached_replace(memcached_st *ptr, char *key, size_t key_length,
92 char *value, size_t value_length,
93 time_t expiration,
94 uint16_t flags)
95 {
96 return memcached_send(ptr, key, key_length, value, value_length,
97 expiration, flags, "replace");
98 }