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;
|
2014-03-28 21:47:19 +01:00
|
|
|
posCacheLoaded = false;
|
2014-03-05 21:41:27 +01:00
|
|
|
options.create_if_missing = false;
|
2014-03-28 21:47:19 +01:00
|
|
|
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() {
|
2014-03-28 21:47:19 +01:00
|
|
|
delete db;
|
2014-03-05 21:41:27 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
std::vector<int64_t> DBLevelDB::getBlockPos() {
|
2014-03-28 21:47:19 +01:00
|
|
|
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()) {
|
2014-03-28 21:47:19 +01:00
|
|
|
posCache.push_back(stoi64(it->key().ToString()));
|
2014-03-05 21:41:27 +01:00
|
|
|
}
|
|
|
|
delete it;
|
2014-03-28 21:47:19 +01:00
|
|
|
posCacheLoaded = true;
|
2014-03-05 21:41:27 +01:00
|
|
|
}
|
|
|
|
|
2014-03-28 21:47:19 +01:00
|
|
|
DBBlockList DBLevelDB::getBlocksOnZ(int zPos) {
|
2014-03-05 21:41:27 +01:00
|
|
|
DBBlockList blocks;
|
|
|
|
std::string datastr;
|
|
|
|
leveldb::Status status;
|
|
|
|
|
2014-03-28 21:47:19 +01:00
|
|
|
int64_t psMin = (zPos * 16777216L) - 0x800000;
|
|
|
|
int64_t psMax = (zPos * 16777216L) + 0x7fffff;
|
2014-03-05 21:41:27 +01:00
|
|
|
|
2014-03-28 21:47:19 +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;
|
2014-03-28 21:47:19 +01:00
|
|
|
}
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|