Rewrote return read() to now read exactly character by character.
[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 (int)key_length, key,
24 offset);
25
26 if ((write(ptr->hosts[server_key].fd, buffer, send_length) == -1))
27 return MEMCACHED_WRITE_FAILURE;
28
29 memset(buffer, 0, MEMCACHED_DEFAULT_COMMAND_SIZE);
30 send_length= read(ptr->hosts[server_key].fd, buffer, MEMCACHED_DEFAULT_COMMAND_SIZE);
31
32 if (!memcmp(buffer, "ERROR\r\n", MEMCACHED_DEFAULT_COMMAND_SIZE))
33 {
34 *value= 0;
35 rc= MEMCACHED_PROTOCOL_ERROR;
36 }
37 else if (!memcmp(buffer, "NOT_FOUND\r\n", MEMCACHED_DEFAULT_COMMAND_SIZE))
38 {
39 *value= 0;
40 rc= MEMCACHED_NOTFOUND;
41 }
42 else
43 {
44 *value= strtol(buffer, (char **)NULL, 10);
45 rc= MEMCACHED_SUCCESS;
46 }
47
48 return rc;
49 }
50
51 memcached_return memcached_increment(memcached_st *ptr,
52 char *key, size_t key_length,
53 unsigned int offset,
54 unsigned int *value)
55 {
56 return memcached_auto(ptr, "incr", key, key_length, offset, value);
57 }
58
59 memcached_return memcached_decrement(memcached_st *ptr,
60 char *key, size_t key_length,
61 unsigned int offset,
62 unsigned int *value)
63 {
64 return memcached_auto(ptr, "decr", key, key_length, offset, value);
65 }