Skip to content
Repos

mologram

C++ 1.7 KB54 lines Opens in site

Directory Raw Download

#include "mologram/SpecDocument.hpp"

#include <fstream>
#include <iterator>
#include <sstream>

namespace mologram {

static std::string trim(const std::string& s) {
  size_t a = s.find_first_not_of(" \t\r");
  if (a == std::string::npos) return "";
  size_t b = s.find_last_not_of(" \t\r");
  return s.substr(a, b - a + 1);
}

SpecDocument::SpecDocument(const std::string& path) {
  std::ifstream in(path);
  if (!in) { error_ = "cannot open " + path; return; }
  text_.assign((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
  std::istringstream ls(text_);
  std::string line, current;
  int rowInTable = 0;
  while (std::getline(ls, line)) {
    if (line.rfind("<!-- spec:", 0) == 0) {
      size_t e = line.find(" -->");
      current = line.substr(10, e - 10);
      tables_[current];
      rowInTable = 0;
      continue;
    }
    if (line.rfind("<!-- /spec:", 0) == 0) { current.clear(); continue; }
    if (current.empty() || line.empty() || line[0] != '|') continue;
    if (++rowInTable <= 2) continue; // header + separator
    Row cells;
    std::string inner = trim(line);
    if (!inner.empty() && inner.front() == '|') inner.erase(0, 1);
    if (!inner.empty() && inner.back() == '|') inner.pop_back();
    std::string cell;
    for (char ch : inner) {
      if (ch == '|') { cells.push_back(trim(cell)); cell.clear(); }
      else cell += ch;
    }
    cells.push_back(trim(cell));
    tables_[current].push_back(std::move(cells));
  }
}

const std::vector<SpecDocument::Row>& SpecDocument::table(const std::string& name) const {
  static const std::vector<Row> empty;
  auto it = tables_.find(name);
  return it == tables_.end() ? empty : it->second;
}

} // namespace mologram
27.6ms