adjust some return codes
[ghsmtp.git] / CDB.cpp
blobd7cb7c7b2593aeb1fd6af1635837edc186787079
1 #include "CDB.hpp"
3 #include <glog/logging.h>
5 #include <fcntl.h>
6 #include <sys/stat.h>
7 #include <sys/types.h>
9 CDB::~CDB()
11 if (is_open()) {
12 close(fd_);
13 cdb_free(&cdb_);
17 bool CDB::open(fs::path db_path)
19 db_path += ".cdb";
20 auto const db_fn = db_path.string();
22 fd_ = ::open(db_fn.c_str(), O_RDONLY);
23 if (fd_ == -1) {
24 char err[256]{};
25 auto const msg = strerror_r(errno, err, sizeof(err));
26 LOG(WARNING) << "unable to open " << db_fn << ": " << msg;
27 return false;
29 cdb_init(&cdb_, fd_);
30 return true;
33 std::optional<std::string> CDB::find(std::string_view key)
35 if (!is_open())
36 return {};
38 CHECK_LT(key.length(), std::numeric_limits<unsigned int>::max());
39 if (cdb_find(&cdb_, key.data(), static_cast<unsigned int>(key.length())) >
40 0) {
41 auto const vpos = cdb_datapos(&cdb_);
42 auto const vlen = cdb_datalen(&cdb_);
43 std::string val;
44 val.resize(vlen);
45 cdb_read(&cdb_, &val[0], vlen, vpos);
46 return val;
49 return {};
52 bool CDB::contains(std::string_view key)
54 if (!is_open())
55 return false;
57 CHECK_LT(key.length(), std::numeric_limits<unsigned int>::max());
58 return cdb_find(&cdb_, key.data(), static_cast<unsigned int>(key.length())) >