-
Notifications
You must be signed in to change notification settings - Fork 0
/
memcached_kv.cc
83 lines (68 loc) · 2.28 KB
/
memcached_kv.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "memcached_kv.h"
#include <string>
#include <cstring>
#include <cassert>
#include <libmemcached/memcached.h>
#include "debug.h"
namespace slope {
namespace keyvalue {
Memcached::Memcached(std::string memc_confstr):
memc_(memcached(memc_confstr.c_str(), strlen(memc_confstr.c_str())), memcached_free) {
assert(
memcached_behavior_set(
memc_.get(),
MEMCACHED_BEHAVIOR_SUPPORT_CAS,
true) == MEMCACHED_SUCCESS
);
}
bool Memcached::compare_and_swap(const std::string& key,
const std::string& oldv, const std::string& newv) {
const char *keys[1] = {key.c_str()};
size_t sizes[1] = {std::strlen(key.c_str())};
auto mget_ret = memcached_mget(memc_.get(), keys, sizes, 1);
assert(mget_ret == MEMCACHED_SUCCESS);
memcached_result_st *res = memcached_result_create(memc_.get(), NULL);
assert(res != NULL);
memcached_return_t err;
memcached_fetch_result(memc_.get(), res, &err);
auto val = memcached_result_value(res);
auto cas = memcached_result_cas(res);
assert(NULL == memcached_fetch_result(memc_.get(), NULL, &err));
bool ret = false;
if(!strcmp(val, oldv.c_str())) {
auto memc_ret = memcached_cas(memc_.get(), key.c_str(), std::strlen(key.c_str()),
newv.c_str(), std::strlen(newv.c_str()), static_cast<time_t>(0),
static_cast<uint32_t>(0), cas);
ret = memc_ret == MEMCACHED_SUCCESS;
}
memcached_result_free(res);
return ret;
}
bool Memcached::set(const std::string& key, const std::string& val) {
auto ret = memcached_set(memc_.get(),
key.c_str(), std::strlen(key.c_str()),
val.c_str(), std::strlen(val.c_str()),
static_cast<time_t>(0), static_cast<uint32_t>(0));
return ret == MEMCACHED_SUCCESS;
}
bool Memcached::get(const std::string& key, std::string& ret) {
size_t value_length;
memcached_return_t memc_ret;
char *result = memcached_get(memc_.get(), key.c_str(), std::strlen(key.c_str()),
&value_length, 0, &memc_ret);
if(result != NULL) {
assert(memc_ret == MEMCACHED_SUCCESS);
ret = std::string(result);
free(result);
return true;
}
return false;
}
bool Memcached::wait_for(const std::string& key, std::string& ret) {
while(!get(key, ret)) {
// do it
}
return true;
}
} // namespace keyvalue
} // namespace slope