minetestmapper/db-leveldb.cpp

75 lines
1.6 KiB
C++
Raw Normal View History

2014-03-05 21:41:27 +01:00
#include "db-leveldb.h"
#include <stdexcept>
#include <sstream>
inline int64_t stoi64(const std::string &s) {
std::stringstream tmp(s);
long long t;
tmp >> t;
return t;
}
inline std::string i64tos(int64_t i) {
std::ostringstream o;
o<<i;
return o.str();
}
DBLevelDB::DBLevelDB(const std::string &mapdir) {
leveldb::Options options;
posCacheLoaded = false;
2014-03-05 21:41:27 +01:00
options.create_if_missing = false;
leveldb::Status status = leveldb::DB::Open(options, mapdir + "map.db", &db);
2014-03-05 21:41:27 +01:00
if(!status.ok())
throw std::runtime_error("Failed to open Database");
}
DBLevelDB::~DBLevelDB() {
delete db;
2014-03-05 21:41:27 +01:00
}
std::vector<int64_t> DBLevelDB::getBlockPos() {
loadPosCache();
return posCache;
}
void DBLevelDB::loadPosCache() {
if (posCacheLoaded) {
return;
}
leveldb::Iterator * it = db->NewIterator(leveldb::ReadOptions());
2014-03-05 21:41:27 +01:00
for (it->SeekToFirst(); it->Valid(); it->Next()) {
posCache.push_back(stoi64(it->key().ToString()));
2014-03-05 21:41:27 +01:00
}
delete it;
posCacheLoaded = true;
2014-03-05 21:41:27 +01:00
}
DBBlockList DBLevelDB::getBlocksOnZ(int zPos) {
2014-03-05 21:41:27 +01:00
DBBlockList blocks;
std::string datastr;
leveldb::Status status;
int64_t psMin = (zPos * 16777216L) - 0x800000;
int64_t psMax = (zPos * 16777216L) + 0x7fffff;
2014-03-05 21:41:27 +01:00
for (std::vector<int64_t>::iterator it = posCache.begin(); it != posCache.end(); ++it) {
int64_t i = *it;
if (i < psMin || i > psMax) {
2014-03-05 21:41:27 +01:00
continue;
}
status = db->Get(leveldb::ReadOptions(), i64tos(i), &datastr);
if (status.ok()) {
blocks.push_back(
DBBlock(i,
std::basic_string<unsigned char>((const unsigned char*) datastr.data(), datastr.size())
)
);
}
2014-03-05 21:41:27 +01:00
}
return blocks;
}