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