da5a9ac6419449ffb181e094f3b378a00eb83fd5
[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 "common.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 assert(value);
26 assert(value_length);
27
28 rc= memcached_connect(ptr);
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 (write_length >= MEMCACHED_DEFAULT_COMMAND_SIZE)
39 return MEMCACHED_WRITE_FAILURE;
40 if ((sent_length= send(ptr->hosts[server_key].fd, buffer, write_length, 0)) == -1)
41 return MEMCACHED_WRITE_FAILURE;
42 assert(write_length == sent_length);
43
44 if ((sent_length= send(ptr->hosts[server_key].fd, value, value_length, 0)) == -1)
45 return MEMCACHED_WRITE_FAILURE;
46 assert(value_length == sent_length);
47
48 if ((sent_length= send(ptr->hosts[server_key].fd, "\r\n", 2, 0)) == -1)
49 return MEMCACHED_WRITE_FAILURE;
50 assert(2 == sent_length);
51
52 sent_length= recv(ptr->hosts[server_key].fd, buffer, MEMCACHED_DEFAULT_COMMAND_SIZE, 0);
53
54 if (sent_length && buffer[0] == 'S') /* STORED */
55 return MEMCACHED_SUCCESS;
56 else if (write_length && buffer[0] == 'N') /* NOT_STORED */
57 return MEMCACHED_NOTSTORED;
58 else
59 return MEMCACHED_READ_FAILURE;
60 }
61
62 memcached_return memcached_set(memcached_st *ptr, char *key, size_t key_length,
63 char *value, size_t value_length,
64 time_t expiration,
65 uint16_t flags)
66 {
67 memcached_return rc;
68 LIBMEMCACHED_MEMCACHED_SET_START();
69 rc= memcached_send(ptr, key, key_length, value, value_length,
70 expiration, flags, "set");
71 LIBMEMCACHED_MEMCACHED_SET_END();
72 return rc;
73 }
74
75 memcached_return memcached_add(memcached_st *ptr, char *key, size_t key_length,
76 char *value, size_t value_length,
77 time_t expiration,
78 uint16_t flags)
79 {
80 memcached_return rc;
81 LIBMEMCACHED_MEMCACHED_ADD_START();
82 rc= memcached_send(ptr, key, key_length, value, value_length,
83 expiration, flags, "add");
84 LIBMEMCACHED_MEMCACHED_ADD_END();
85 return rc;
86 }
87
88 memcached_return memcached_replace(memcached_st *ptr, char *key, size_t key_length,
89 char *value, size_t value_length,
90 time_t expiration,
91 uint16_t flags)
92 {
93 memcached_return rc;
94 LIBMEMCACHED_MEMCACHED_REPLACE_START();
95 rc= memcached_send(ptr, key, key_length, value, value_length,
96 expiration, flags, "replace");
97 LIBMEMCACHED_MEMCACHED_REPLACE_END();
98 return rc;
99 }