10 #include <memcached.h>
12 static memcached_return
memcached_send(memcached_st
*ptr
,
13 char *key
, size_t key_length
,
14 char *value
, size_t value_length
,
22 char buffer
[MEMCACHED_DEFAULT_COMMAND_SIZE
];
23 unsigned int server_key
;
25 rc
= memcached_connect(ptr
);
29 if (rc
!= MEMCACHED_SUCCESS
)
32 server_key
= memcached_generate_hash(key
, key_length
) % ptr
->number_of_hosts
;
34 write_length
= snprintf(buffer
, MEMCACHED_DEFAULT_COMMAND_SIZE
,
35 "%s %.*s %u %u %u\r\n", verb
,
36 key_length
, key
, flags
, expiration
, value_length
);
37 if ((sent_length
= write(ptr
->hosts
[server_key
].fd
, buffer
, write_length
)) == -1)
39 fprintf(stderr
, "failed %s on %.*s: %s\n", verb
, key_length
+1, key
, strerror(errno
));
41 return MEMCACHED_WRITE_FAILURE
;
43 assert(write_length
== sent_length
);
46 printf("About to push %.*s\n", value_length
, value
);
48 if ((sent_length
= write(ptr
->hosts
[server_key
].fd
, value
, value_length
)) == -1)
50 fprintf(stderr
, "failed %s on %.*s: %s\n", verb
, key_length
+1, key
, strerror(errno
));
52 return MEMCACHED_WRITE_FAILURE
;
54 assert(value_length
== sent_length
);
55 if ((sent_length
= write(ptr
->hosts
[server_key
].fd
, "\r\n", 2)) == -1)
57 fprintf(stderr
, "failed %s on %.*s: %s\n", verb
, key_length
+1, key
, strerror(errno
));
59 return MEMCACHED_WRITE_FAILURE
;
61 assert(2 == sent_length
);
63 sent_length
= read(ptr
->hosts
[server_key
].fd
, buffer
, MEMCACHED_DEFAULT_COMMAND_SIZE
);
65 if (sent_length
&& buffer
[0] == 'S') /* STORED */
66 return MEMCACHED_SUCCESS
;
67 else if (write_length
&& buffer
[0] == 'N') /* NOT_STORED */
68 return MEMCACHED_NOTSTORED
;
70 return MEMCACHED_READ_FAILURE
;
73 memcached_return
memcached_set(memcached_st
*ptr
, char *key
, size_t key_length
,
74 char *value
, size_t value_length
,
78 return memcached_send(ptr
, key
, key_length
, value
, value_length
,
79 expiration
, flags
, "set");
82 memcached_return
memcached_add(memcached_st
*ptr
, char *key
, size_t key_length
,
83 char *value
, size_t value_length
,
87 return memcached_send(ptr
, key
, key_length
, value
, value_length
,
88 expiration
, flags
, "add");
91 memcached_return
memcached_replace(memcached_st
*ptr
, char *key
, size_t key_length
,
92 char *value
, size_t value_length
,
96 return memcached_send(ptr
, key
, key_length
, value
, value_length
,
97 expiration
, flags
, "replace");