e779f279a7966928f5d95e7add9cf73c4d591d6e
[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 rc= memcached_connect(ptr);
15
16 if (rc != MEMCACHED_SUCCESS)
17 return rc;
18
19 server_key= memcached_generate_hash(key, key_length) % ptr->number_of_hosts;
20
21 send_length= snprintf(buffer, MEMCACHED_DEFAULT_COMMAND_SIZE,
22 "%s %.*s %u\r\n", verb,
23 (int)key_length, key,
24 offset);
25 if (send_length >= MEMCACHED_DEFAULT_COMMAND_SIZE)
26 return MEMCACHED_WRITE_FAILURE;
27 sent_length= send(ptr->hosts[server_key].fd, buffer, send_length, 0);
28
29 if (sent_length == -1 || sent_length != send_length)
30 return MEMCACHED_WRITE_FAILURE;
31
32 memset(buffer, 0, MEMCACHED_DEFAULT_COMMAND_SIZE);
33 send_length= read(ptr->hosts[server_key].fd, buffer, MEMCACHED_DEFAULT_COMMAND_SIZE);
34
35 if (!memcmp(buffer, "ERROR\r\n", MEMCACHED_DEFAULT_COMMAND_SIZE))
36 {
37 *value= 0;
38 rc= MEMCACHED_PROTOCOL_ERROR;
39 }
40 else if (!memcmp(buffer, "NOT_FOUND\r\n", MEMCACHED_DEFAULT_COMMAND_SIZE))
41 {
42 *value= 0;
43 rc= MEMCACHED_NOTFOUND;
44 }
45 else
46 {
47 *value= strtol(buffer, (char **)NULL, 10);
48 rc= MEMCACHED_SUCCESS;
49 }
50
51 return rc;
52 }
53
54 memcached_return memcached_increment(memcached_st *ptr,
55 char *key, size_t key_length,
56 unsigned int offset,
57 unsigned int *value)
58 {
59 memcached_return rc;
60
61 LIBMEMCACHED_MEMCACHED_INCREMENT_START();
62 rc= memcached_auto(ptr, "incr", key, key_length, offset, value);
63 LIBMEMCACHED_MEMCACHED_INCREMENT_END();
64
65 return rc;
66 }
67
68 memcached_return memcached_decrement(memcached_st *ptr,
69 char *key, size_t key_length,
70 unsigned int offset,
71 unsigned int *value)
72 {
73 memcached_return rc;
74
75 LIBMEMCACHED_MEMCACHED_DECREMENT_START();
76 rc= memcached_auto(ptr, "decr", key, key_length, offset, value);
77 LIBMEMCACHED_MEMCACHED_DECREMENT_END();
78
79 return rc;
80 }