-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCDB.cpp
71 lines (59 loc) · 1.52 KB
/
CDB.cpp
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
#include "CDB.hpp"
#include <algorithm>
#include <glog/logging.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
CDB::~CDB()
{
if (is_open()) {
close(fd_);
cdb_free(&cdb_);
}
}
bool CDB::open(fs::path db_path)
{
db_path += ".cdb";
auto const db_fn = db_path.string();
fd_ = ::open(db_fn.c_str(), O_RDONLY);
if (fd_ == -1) {
char err[256]{};
auto const msg = strerror_r(errno, err, sizeof(err));
LOG(WARNING) << "unable to open " << db_fn << ": " << msg;
return false;
}
cdb_init(&cdb_, fd_);
return true;
}
std::optional<std::string> CDB::find(std::string_view key)
{
if (!is_open())
return {};
CHECK_LT(key.length(), std::numeric_limits<unsigned int>::max());
if (cdb_find(&cdb_, key.data(), static_cast<unsigned int>(key.length())) >
0) {
auto const vpos = cdb_datapos(&cdb_);
auto const vlen = cdb_datalen(&cdb_);
std::string val;
val.resize(vlen);
cdb_read(&cdb_, &val[0], vlen, vpos);
return val;
}
return {};
}
// No locale, ASCII only.
bool CDB::contains_lc(std::string_view key)
{
std::string key_lc{key.begin(), key.end()};
std::transform(key_lc.begin(), key_lc.end(), key_lc.begin(),
[](unsigned char c) { return std::tolower(c); });
return contains(key_lc);
}
bool CDB::contains(std::string_view key)
{
if (!is_open())
return false;
CHECK_LT(key.length(), std::numeric_limits<unsigned int>::max());
return cdb_find(&cdb_, key.data(), static_cast<unsigned int>(key.length())) >
0;
}