minetestmapper/db-leveldb.cpp

75 lines
1.4 KiB
C++
Raw Normal View History

2014-03-05 21:41:27 +01:00
#include <stdexcept>
#include <sstream>
#include "db-leveldb.h"
#include "types.h"
2014-03-05 21:41:27 +01:00
static inline int64_t stoi64(const std::string &s)
{
2014-03-05 21:41:27 +01:00
std::stringstream tmp(s);
int64_t t;
2014-03-05 21:41:27 +01:00
tmp >> t;
return t;
}
static inline std::string i64tos(int64_t i)
{
std::ostringstream os;
os << i;
return os.str();
2014-03-05 21:41:27 +01:00
}
DBLevelDB::DBLevelDB(const std::string &mapdir)
{
2014-03-05 21:41:27 +01:00
leveldb::Options options;
options.create_if_missing = false;
leveldb::Status status = leveldb::DB::Open(options, mapdir + "map.db", &db);
if (!status.ok()) {
2014-03-05 21:41:27 +01:00
throw std::runtime_error("Failed to open Database");
}
loadPosCache();
2014-03-05 21:41:27 +01:00
}
DBLevelDB::~DBLevelDB()
{
delete db;
2014-03-05 21:41:27 +01:00
}
std::vector<BlockPos> DBLevelDB::getBlockPos()
{
return posCache;
}
void DBLevelDB::loadPosCache()
{
leveldb::Iterator * it = db->NewIterator(leveldb::ReadOptions());
2014-03-05 21:41:27 +01:00
for (it->SeekToFirst(); it->Valid(); it->Next()) {
int64_t posHash = stoi64(it->key().ToString());
posCache.push_back(decodeBlockPos(posHash));
2014-03-05 21:41:27 +01:00
}
delete it;
}
void DBLevelDB::getBlocksOnZ(std::map<int16_t, BlockList> &blocks, int16_t zPos)
{
2014-03-05 21:41:27 +01:00
std::string datastr;
leveldb::Status status;
for (std::vector<BlockPos>::iterator it = posCache.begin(); it != posCache.end(); ++it) {
if (it->z != zPos) {
2014-03-05 21:41:27 +01:00
continue;
}
status = db->Get(leveldb::ReadOptions(), i64tos(encodeBlockPos(*it)), &datastr);
if (status.ok()) {
Block b(*it, ustring((const unsigned char *) datastr.data(), datastr.size()));
blocks[b.first.x].push_back(b);
}
2014-03-05 21:41:27 +01:00
}
}