Getting everything ready for non-blocking IO.
[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
34 rc= memcached_response(ptr, buffer, MEMCACHED_DEFAULT_COMMAND_SIZE, server_key);
35
36 /*
37 So why recheck responce? Because the protocol is brain dead :)
38 The number returned might end up equaling one of the string
39 values. Less chance of a mistake with memcmp() so we will
40 use it. We still called memcached_response() though since it
41 worked its magic for non-blocking IO.
42 */
43 if (!memcmp(buffer, "ERROR\r\n", MEMCACHED_DEFAULT_COMMAND_SIZE))
44 {
45 *value= 0;
46 rc= MEMCACHED_PROTOCOL_ERROR;
47 }
48 else if (!memcmp(buffer, "NOT_FOUND\r\n", MEMCACHED_DEFAULT_COMMAND_SIZE))
49 {
50 *value= 0;
51 rc= MEMCACHED_NOTFOUND;
52 }
53 else
54 {
55 *value= strtol(buffer, (char **)NULL, 10);
56 rc= MEMCACHED_SUCCESS;
57 }
58
59 return rc;
60 }
61
62 memcached_return memcached_increment(memcached_st *ptr,
63 char *key, size_t key_length,
64 unsigned int offset,
65 unsigned int *value)
66 {
67 memcached_return rc;
68
69 LIBMEMCACHED_MEMCACHED_INCREMENT_START();
70 rc= memcached_auto(ptr, "incr", key, key_length, offset, value);
71 LIBMEMCACHED_MEMCACHED_INCREMENT_END();
72
73 return rc;
74 }
75
76 memcached_return memcached_decrement(memcached_st *ptr,
77 char *key, size_t key_length,
78 unsigned int offset,
79 unsigned int *value)
80 {
81 memcached_return rc;
82
83 LIBMEMCACHED_MEMCACHED_DECREMENT_START();
84 rc= memcached_auto(ptr, "decr", key, key_length, offset, value);
85 LIBMEMCACHED_MEMCACHED_DECREMENT_END();
86
87 return rc;
88 }