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