28e84ed903c6c1dbef622399bda481aab2cc278a
[awesomized/libmemcached] / libmemcached / memcached_fetch.c
1 #include "common.h"
2 #include "memcached_io.h"
3
4 char *memcached_fetch(memcached_st *ptr, char *key, size_t *key_length,
5 size_t *value_length,
6 uint32_t *flags,
7 memcached_return *error)
8 {
9 memcached_result_st *result_buffer= &ptr->result;
10
11 if (ptr->flags & MEM_USE_UDP)
12 {
13 *error= MEMCACHED_NOT_SUPPORTED;
14 return NULL;
15 }
16
17 result_buffer= memcached_fetch_result(ptr, result_buffer, error);
18
19 if (*error != MEMCACHED_SUCCESS)
20 {
21 *value_length= 0;
22 return NULL;
23 }
24
25 *value_length= memcached_string_length(&result_buffer->value);
26
27 if (key)
28 {
29 strncpy(key, result_buffer->key, result_buffer->key_length);
30 *key_length= result_buffer->key_length;
31 }
32
33 if (result_buffer->flags)
34 *flags= result_buffer->flags;
35 else
36 *flags= 0;
37
38 return memcached_string_c_copy(&result_buffer->value);
39 }
40
41 memcached_result_st *memcached_fetch_result(memcached_st *ptr,
42 memcached_result_st *result,
43 memcached_return *error)
44 {
45 memcached_server_st *server;
46
47 if (ptr->flags & MEM_USE_UDP)
48 {
49 *error= MEMCACHED_NOT_SUPPORTED;
50 return NULL;
51 }
52
53 if (result == NULL)
54 if ((result= memcached_result_create(ptr, NULL)) == NULL)
55 return NULL;
56
57 while ((server = memcached_io_get_readable_server(ptr)) != NULL) {
58 char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
59 *error= memcached_response(server, buffer, sizeof(buffer), result);
60
61 if (*error == MEMCACHED_SUCCESS)
62 return result;
63 else if (*error == MEMCACHED_END)
64 memcached_server_response_reset(server);
65 else
66 break;
67 }
68
69 /* We have completed reading data */
70 if (result->is_allocated)
71 memcached_result_free(result);
72 else
73 memcached_string_reset(&result->value);
74
75 return NULL;
76 }
77
78 memcached_return memcached_fetch_execute(memcached_st *ptr,
79 memcached_execute_function *callback,
80 void *context,
81 unsigned int number_of_callbacks)
82 {
83 memcached_result_st *result= &ptr->result;
84 memcached_return rc;
85 unsigned int x;
86
87 while ((result= memcached_fetch_result(ptr, result, &rc)) != NULL) {
88 if (rc == MEMCACHED_SUCCESS)
89 {
90 for (x= 0; x < number_of_callbacks; x++)
91 {
92 rc= (*callback[x])(ptr, result, context);
93 if (rc != MEMCACHED_SUCCESS)
94 break;
95 }
96 }
97 }
98 return rc;
99 }