3 char *memcached_get(memcached_st
*ptr
, char *key
, size_t key_length
,
6 memcached_return
*error
)
9 char buffer
[MEMCACHED_DEFAULT_COMMAND_SIZE
];
11 unsigned int server_key
;
14 *error
= memcached_connect(ptr
);
16 if (*error
!= MEMCACHED_SUCCESS
)
19 server_key
= memcached_generate_hash(key
, key_length
) % ptr
->number_of_hosts
;
21 send_length
= snprintf(buffer
, MEMCACHED_DEFAULT_COMMAND_SIZE
, "get %.*s\r\n",
23 if (*error
!= MEMCACHED_SUCCESS
)
26 if ((send(ptr
->hosts
[server_key
].fd
, buffer
, send_length
, 0) == -1))
28 fprintf(stderr
, "failed fetch on %.*s TCP\n", key_length
+1, key
);
29 *error
= MEMCACHED_WRITE_FAILURE
;
33 memset(buffer
, 0, MEMCACHED_DEFAULT_COMMAND_SIZE
);
34 *error
= memcached_response(ptr
, buffer
, MEMCACHED_DEFAULT_COMMAND_SIZE
, server_key
);
36 if (*error
== MEMCACHED_SUCCESS
)
41 string_ptr
+= 6; /* "VALUE " */
43 /* We do nothing with the key, since we only asked for one key */
44 for (end_ptr
= string_ptr
; *end_ptr
!= ' '; end_ptr
++);
47 string_ptr
= end_ptr
+ 1;
48 for (end_ptr
= string_ptr
; *end_ptr
!= ' '; end_ptr
++);
49 *flags
= (uint16_t)strtol(string_ptr
, &end_ptr
, 10);
52 string_ptr
= end_ptr
+ 1;
53 for (end_ptr
= string_ptr
; *end_ptr
!= ' '; end_ptr
++);
54 *value_length
= strtoll(string_ptr
, &end_ptr
, 10);
56 /* Skip past the \r\n */
57 string_ptr
= end_ptr
+2;
65 value
= (char *)malloc(*value_length
* sizeof(char));
69 *error
= MEMCACHED_MEMORY_ALLOCATION_FAILURE
;
73 need_to_copy
= (*value_length
< (size_t)(buffer
-string_ptr
))
75 : (size_t)(buffer
-string_ptr
) ;
77 pos_ptr
= memcpy(value
, string_ptr
, need_to_copy
);
79 if ( need_to_copy
> *value_length
)
84 need_to_read
= *value_length
- need_to_copy
;
86 read_length
= read(ptr
->hosts
[server_key
].fd
, pos_ptr
, need_to_read
);
87 if (read_length
!= need_to_read
)
90 *error
= MEMCACHED_PARTIAL_READ
;