Broke library up into multiple files.
[m6w6/libmemcached] / lib / memcached_get.c
1 #include <memcached.h>
2
3 char *memcached_get(memcached_st *ptr, char *key, size_t key_length,
4 size_t *value_length,
5 uint16_t *flags,
6 memcached_return *error)
7 {
8 size_t send_length;
9 char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
10 char *string_ptr;
11
12 *error= memcached_connect(ptr);
13
14 send_length= snprintf(buffer, MEMCACHED_DEFAULT_COMMAND_SIZE, "get %.*s\r\n",
15 key_length, key);
16 if (*error != MEMCACHED_SUCCESS)
17 return NULL;
18
19 if ((send(ptr->fd, buffer, send_length, 0) == -1))
20 {
21 fprintf(stderr, "failed fetch on %.*s TCP\n", key_length+1, key);
22 *error= MEMCACHED_WRITE_FAILURE;
23 return NULL;
24 }
25
26 memset(buffer, 0, MEMCACHED_DEFAULT_COMMAND_SIZE);
27 *error= memcached_response(ptr, buffer, MEMCACHED_DEFAULT_COMMAND_SIZE);
28
29 if (*error == MEMCACHED_SUCCESS)
30 {
31 char *end_ptr;
32
33 string_ptr= buffer;
34 string_ptr+= 6; /* "VALUE " */
35
36 /* We do nothing with the key, since we only asked for one key */
37 for (end_ptr= string_ptr; *end_ptr != ' '; end_ptr++);
38
39 /* Flags fetch */
40 string_ptr= end_ptr + 1;
41 for (end_ptr= string_ptr; *end_ptr != ' '; end_ptr++);
42 *flags= (uint16_t)strtol(string_ptr, &end_ptr, 10);
43
44 /* Length fetch */
45 string_ptr= end_ptr + 1;
46 for (end_ptr= string_ptr; *end_ptr != ' '; end_ptr++);
47 *value_length= strtoll(string_ptr, &end_ptr, 10);
48
49 /* Skip past the \r\n */
50 string_ptr= end_ptr +2;
51
52 if (*value_length)
53 {
54 size_t need_to_copy;
55 char *pos_ptr;
56 char *value;
57
58 value= (char *)malloc(*value_length * sizeof(char));
59
60 if (!value)
61 {
62 *error= MEMCACHED_MEMORY_ALLOCATION_FAILURE;
63 return NULL;
64 }
65
66 need_to_copy= (*value_length < (size_t)(buffer-string_ptr))
67 ? *value_length
68 : (size_t)(buffer-string_ptr) ;
69
70 pos_ptr= memcpy(value, string_ptr, need_to_copy);
71
72 if ( need_to_copy > *value_length)
73 {
74 size_t read_length;
75 size_t need_to_read;
76
77 need_to_read= *value_length - need_to_copy;
78
79 read_length= read(ptr->fd, pos_ptr, need_to_read);
80 if (read_length != need_to_read)
81 {
82 free(value);
83 *error= MEMCACHED_PARTIAL_READ;
84
85 return NULL;
86 }
87 }
88
89 return value;
90 }
91 }
92
93 return NULL;
94 }