Increment and decrement now works.
[awesomized/libmemcached] / lib / memcached_auto.c
1 #include <memcached.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;
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 key_length, key,
24 offset);
25
26 if ((send(ptr->hosts[server_key].fd, buffer, send_length, 0) == -1))
27 {
28 fprintf(stderr, "failed set on %.*s TCP\n", key_length+1, key);
29
30 return MEMCACHED_WRITE_FAILURE;
31 }
32
33 memset(buffer, 0, MEMCACHED_DEFAULT_COMMAND_SIZE);
34 send_length= read(ptr->hosts[server_key].fd, buffer, MEMCACHED_DEFAULT_COMMAND_SIZE);
35
36 if (!memcmp(buffer, "ERROR\r\n", MEMCACHED_DEFAULT_COMMAND_SIZE))
37 {
38 *value= 0;
39 rc= MEMCACHED_PROTOCOL_ERROR;
40 }
41 else if (!memcmp(buffer, "NOT_FOUND\r\n", MEMCACHED_DEFAULT_COMMAND_SIZE))
42 {
43 *value= 0;
44 rc= MEMCACHED_NOTFOUND;
45 }
46 else
47 {
48 *value= strtol(buffer, (char **)NULL, 10);
49 rc= MEMCACHED_SUCCESS;
50 }
51
52 return rc;
53 }
54
55 memcached_return memcached_increment(memcached_st *ptr,
56 char *key, size_t key_length,
57 unsigned int offset,
58 unsigned int *value)
59 {
60 return memcached_auto(ptr, "incr", key, key_length, offset, value);
61 }
62
63 memcached_return memcached_decrement(memcached_st *ptr,
64 char *key, size_t key_length,
65 unsigned int offset,
66 unsigned int *value)
67 {
68 return memcached_auto(ptr, "decr", key, key_length, offset, value);
69 }