484341c842c286ad2dd8fd106cc5ebfe328f70e7
[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 %x %llu %zu\r\n", verb,
36 (int)key_length, key, flags,
37 (unsigned long long)expiration, value_length);
38 if ((sent_length= write(ptr->hosts[server_key].fd, buffer, write_length)) == -1)
39 return MEMCACHED_WRITE_FAILURE;
40 assert(write_length == sent_length);
41
42 if ((sent_length= write(ptr->hosts[server_key].fd, value, value_length)) == -1)
43 return MEMCACHED_WRITE_FAILURE;
44 assert(value_length == sent_length);
45
46 if ((sent_length= write(ptr->hosts[server_key].fd, "\r\n", 2)) == -1)
47 return MEMCACHED_WRITE_FAILURE;
48 assert(2 == sent_length);
49
50 sent_length= read(ptr->hosts[server_key].fd, buffer, MEMCACHED_DEFAULT_COMMAND_SIZE);
51
52 if (sent_length && buffer[0] == 'S') /* STORED */
53 return MEMCACHED_SUCCESS;
54 else if (write_length && buffer[0] == 'N') /* NOT_STORED */
55 return MEMCACHED_NOTSTORED;
56 else
57 return MEMCACHED_READ_FAILURE;
58 }
59
60 memcached_return memcached_set(memcached_st *ptr, char *key, size_t key_length,
61 char *value, size_t value_length,
62 time_t expiration,
63 uint16_t flags)
64 {
65 return memcached_send(ptr, key, key_length, value, value_length,
66 expiration, flags, "set");
67 }
68
69 memcached_return memcached_add(memcached_st *ptr, char *key, size_t key_length,
70 char *value, size_t value_length,
71 time_t expiration,
72 uint16_t flags)
73 {
74 return memcached_send(ptr, key, key_length, value, value_length,
75 expiration, flags, "add");
76 }
77
78 memcached_return memcached_replace(memcached_st *ptr, char *key, size_t key_length,
79 char *value, size_t value_length,
80 time_t expiration,
81 uint16_t flags)
82 {
83 return memcached_send(ptr, key, key_length, value, value_length,
84 expiration, flags, "replace");
85 }