Merge
[awesomized/libmemcached] / lib / memcached_auto.c
1 #include "common.h"
2
3 static memcached_return memcached_auto(memcached_st *ptr,
4 char *verb,
5 char *key, size_t key_length,
6 unsigned int offset,
7 uint64_t *value)
8 {
9 size_t send_length;
10 memcached_return rc;
11 char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
12 unsigned int server_key;
13
14 if (key_length == 0)
15 return MEMCACHED_NO_KEY_PROVIDED;
16
17 if (ptr->hosts == NULL || ptr->number_of_hosts == 0)
18 return MEMCACHED_NO_SERVERS;
19
20 server_key= memcached_generate_hash(ptr, key, key_length);
21
22 send_length= snprintf(buffer, MEMCACHED_DEFAULT_COMMAND_SIZE,
23 "%s %.*s %u\r\n", verb,
24 (int)key_length, key,
25 offset);
26 if (send_length >= MEMCACHED_DEFAULT_COMMAND_SIZE)
27 return MEMCACHED_WRITE_FAILURE;
28
29 rc= memcached_do(&ptr->hosts[server_key], buffer, send_length, 1);
30 if (rc != MEMCACHED_SUCCESS)
31 return rc;
32
33 rc= memcached_response(&ptr->hosts[server_key], buffer, MEMCACHED_DEFAULT_COMMAND_SIZE, NULL);
34
35 /*
36 So why recheck responce? Because the protocol is brain dead :)
37 The number returned might end up equaling one of the string
38 values. Less chance of a mistake with strncmp() so we will
39 use it. We still called memcached_response() though since it
40 worked its magic for non-blocking IO.
41 */
42 if (!strncmp(buffer, "ERROR\r\n", 7))
43 {
44 *value= 0;
45 rc= MEMCACHED_PROTOCOL_ERROR;
46 }
47 else if (!strncmp(buffer, "NOT_FOUND\r\n", 11))
48 {
49 *value= 0;
50 rc= MEMCACHED_NOTFOUND;
51 }
52 else
53 {
54 *value= (uint64_t)strtoll(buffer, (char **)NULL, 10);
55 rc= MEMCACHED_SUCCESS;
56 }
57
58 return rc;
59 }
60
61 memcached_return memcached_increment(memcached_st *ptr,
62 char *key, size_t key_length,
63 uint32_t offset,
64 uint64_t *value)
65 {
66 memcached_return rc;
67
68 LIBMEMCACHED_MEMCACHED_INCREMENT_START();
69 rc= memcached_auto(ptr, "incr", key, key_length, offset, value);
70 LIBMEMCACHED_MEMCACHED_INCREMENT_END();
71
72 return rc;
73 }
74
75 memcached_return memcached_decrement(memcached_st *ptr,
76 char *key, size_t key_length,
77 uint32_t offset,
78 uint64_t *value)
79 {
80 memcached_return rc;
81
82 LIBMEMCACHED_MEMCACHED_DECREMENT_START();
83 rc= memcached_auto(ptr, "decr", key, key_length, offset, value);
84 LIBMEMCACHED_MEMCACHED_DECREMENT_END();
85
86 return rc;
87 }