call out non-ASCII
[ghsmtp.git] / CDB.cpp
blobbb00a73d70c93bdb9d9f38245c0753e8f88da8ab
1 #include "CDB.hpp"
3 #include <algorithm>
5 #include <glog/logging.h>
7 #include <fcntl.h>
8 #include <sys/stat.h>
9 #include <sys/types.h>
11 CDB::~CDB()
13 if (is_open()) {
14 close(fd_);
15 cdb_free(&cdb_);
19 bool CDB::open(fs::path db_path)
21 db_path += ".cdb";
22 auto const db_fn = db_path.string();
24 fd_ = ::open(db_fn.c_str(), O_RDONLY);
25 if (fd_ == -1) {
26 char err[256]{};
27 auto const msg = strerror_r(errno, err, sizeof(err));
28 LOG(WARNING) << "unable to open " << db_fn << ": " << msg;
29 return false;
31 cdb_init(&cdb_, fd_);
32 return true;
35 std::optional<std::string> CDB::find(std::string_view key)
37 if (!is_open())
38 return {};
40 CHECK_LT(key.length(), std::numeric_limits<unsigned int>::max());
41 if (cdb_find(&cdb_, key.data(), static_cast<unsigned int>(key.length())) >
42 0) {
43 auto const vpos = cdb_datapos(&cdb_);
44 auto const vlen = cdb_datalen(&cdb_);
45 std::string val;
46 val.resize(vlen);
47 cdb_read(&cdb_, &val[0], vlen, vpos);
48 return val;
51 return {};
54 // No locale, ASCII only.
55 bool CDB::contains_lc(std::string_view key)
57 std::string key_lc{key.begin(), key.end()};
58 std::transform(key_lc.begin(), key_lc.end(), key_lc.begin(),
59 [](unsigned char c) { return std::tolower(c); });
60 return contains(key_lc);
63 bool CDB::contains(std::string_view key)
65 if (!is_open())
66 return false;
68 CHECK_LT(key.length(), std::numeric_limits<unsigned int>::max());
69 return cdb_find(&cdb_, key.data(), static_cast<unsigned int>(key.length())) >