Merge from Trond
[m6w6/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 unlikely (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 (result_buffer == NULL || *error != MEMCACHED_SUCCESS)
20 {
21 WATCHPOINT_ASSERT(result_buffer == NULL);
22 *value_length= 0;
23 return NULL;
24 }
25
26 *value_length= memcached_string_length(&result_buffer->value);
27
28 if (key)
29 {
30 strncpy(key, result_buffer->key, result_buffer->key_length);
31 *key_length= result_buffer->key_length;
32 }
33
34 if (result_buffer->flags)
35 *flags= result_buffer->flags;
36 else
37 *flags= 0;
38
39 return memcached_string_c_copy(&result_buffer->value);
40 }
41
42 memcached_result_st *memcached_fetch_result(memcached_st *ptr,
43 memcached_result_st *result,
44 memcached_return *error)
45 {
46 memcached_server_st *server;
47
48 unlikely (ptr->flags & MEM_USE_UDP)
49 {
50 *error= MEMCACHED_NOT_SUPPORTED;
51 return NULL;
52 }
53
54 if (result == NULL)
55 if ((result= memcached_result_create(ptr, NULL)) == NULL)
56 return NULL;
57
58 while ((server = memcached_io_get_readable_server(ptr)) != NULL)
59 {
60 char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];
61 *error= memcached_response(server, buffer, sizeof(buffer), result);
62
63 if (*error == MEMCACHED_SUCCESS)
64 return result;
65 else if (*error == MEMCACHED_END)
66 memcached_server_response_reset(server);
67 else
68 break;
69 }
70
71 /* We have completed reading data */
72 if (result->is_allocated)
73 memcached_result_free(result);
74 else
75 memcached_string_reset(&result->value);
76
77 return NULL;
78 }
79
80 memcached_return memcached_fetch_execute(memcached_st *ptr,
81 memcached_execute_function *callback,
82 void *context,
83 unsigned int number_of_callbacks)
84 {
85 memcached_result_st *result= &ptr->result;
86 memcached_return rc= MEMCACHED_FAILURE;
87 unsigned int x;
88
89 while ((result= memcached_fetch_result(ptr, result, &rc)) != NULL)
90 {
91 if (rc == MEMCACHED_SUCCESS)
92 {
93 for (x= 0; x < number_of_callbacks; x++)
94 {
95 rc= (*callback[x])(ptr, result, context);
96 if (rc != MEMCACHED_SUCCESS)
97 break;
98 }
99 }
100 }
101 return rc;
102 }