Memory leak fixed.
[m6w6/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 send_length;
20 memcached_return rc;
21 char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
22 unsigned int server_key;
23
24 rc= memcached_connect(ptr);
25
26 if (rc != MEMCACHED_SUCCESS)
27 return rc;
28
29 server_key= memcached_generate_hash(key, key_length) % ptr->number_of_hosts;
30
31 send_length= snprintf(buffer, MEMCACHED_DEFAULT_COMMAND_SIZE,
32 "%s %.*s %u %u %u\r\n", verb,
33 key_length, key, flags, expiration, value_length);
34 if ((send(ptr->hosts[server_key].fd, buffer, send_length, 0) == -1))
35 {
36 fprintf(stderr, "failed set on %.*s TCP\n", key_length+1, key);
37
38 return MEMCACHED_WRITE_FAILURE;
39 }
40
41 send_length= snprintf(buffer, MEMCACHED_DEFAULT_COMMAND_SIZE,
42 "%.*s\r\n",
43 value_length, value);
44 if ((send(ptr->hosts[server_key].fd, buffer, send_length, 0) == -1))
45 {
46 fprintf(stderr, "failed set on %.*s TCP\n", key_length+1, key);
47
48 return MEMCACHED_WRITE_FAILURE;
49 }
50
51 send_length= read(ptr->hosts[server_key].fd, buffer, MEMCACHED_DEFAULT_COMMAND_SIZE);
52
53 if (send_length && buffer[0] == 'S') /* STORED */
54 return MEMCACHED_SUCCESS;
55 else if (send_length && buffer[0] == 'N') /* NOT_STORED */
56 return MEMCACHED_NOTSTORED;
57 else
58 return MEMCACHED_READ_FAILURE;
59 }
60
61 memcached_return memcached_set(memcached_st *ptr, char *key, size_t key_length,
62 char *value, size_t value_length,
63 time_t expiration,
64 uint16_t flags)
65 {
66 return memcached_send(ptr, key, key_length, value, value_length,
67 expiration, flags, "set");
68 }
69
70 memcached_return memcached_add(memcached_st *ptr, char *key, size_t key_length,
71 char *value, size_t value_length,
72 time_t expiration,
73 uint16_t flags)
74 {
75 return memcached_send(ptr, key, key_length, value, value_length,
76 expiration, flags, "add");
77 }
78
79 memcached_return memcached_replace(memcached_st *ptr, char *key, size_t key_length,
80 char *value, size_t value_length,
81 time_t expiration,
82 uint16_t flags)
83 {
84 return memcached_send(ptr, key, key_length, value, value_length,
85 expiration, flags, "replace");
86 }