storage.cc 1.8 KB
Newer Older
S
superjom 已提交
1 2 3 4 5 6 7
#include <fstream>
#include <glog/logging.h>

#include "visualdl/backend/storage/storage.h"

namespace visualdl {

S
superjom 已提交
8 9 10 11
storage::Tablet *Storage::Add(const std::string &tag, int num_samples) {
  auto *tablet = &(*proto_.mutable_tablets())[tag];
  tablet->set_num_samples(num_samples);
  return tablet;
S
superjom 已提交
12 13
}

S
superjom 已提交
14 15
storage::Tablet *Storage::Find(const std::string &tag) {
  auto it = proto_.mutable_tablets()->find(tag);
S
superjom 已提交
16 17 18 19 20 21
  if (it != proto_.tablets().end()) {
    return &it->second;
  }
  return nullptr;
}

S
superjom 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
storage::Record *Storage::NewRecord(const std::string &tag) {
  auto *tablet = Find(tag);
  CHECK(tablet) << "Tablet" << tag << " should be create first";
  auto *record = tablet->mutable_records()->Add();
  // increase num_records
  int num_records = tablet->num_records();
  tablet->set_num_records(num_records + 1);
  return record;
}
storage::Record *Storage::GetRecord(const std::string &tag, int offset) {
  auto *tablet = Find(tag);
  CHECK(tablet) << "Tablet" << tag << " should be create first";

  auto num_records = tablet->num_records();
  CHECK_LT(offset, num_records) << "invalid offset";
  return tablet->mutable_records()->Mutable(offset);
}

S
superjom 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
void Storage::Save(const std::string &path) const {
  std::ofstream file(path, file.binary | file.out);
  CHECK(file.is_open()) << "can't open path " << path;
  auto str = Serialize();
  file.write(str.c_str(), str.size());
}

void Storage::Load(const std::string &path) {
  std::ifstream file(path, file.binary);
  CHECK(file.is_open()) << "can't open path " << path;
  size_t size = file.tellg();
  std::string buffer(size, ' ');
  file.seekg(0);
  file.read(&buffer[0], size);
  DeSerialize(buffer);
}

S
superjom 已提交
57
std::string Storage::Serialize() const { return proto_.SerializeAsString(); }
S
superjom 已提交
58 59 60 61 62

void Storage::DeSerialize(const std::string &data) {
  proto_.ParseFromString(data);
}

S
superjom 已提交
63
} // namespace visualdl