#include "engine/io_native.hpp" #include #include #include #include #include #include #include #include #include #include #include namespace htab { namespace { void append_json_string(std::string& out, const std::string& s) { out.push_back('"'); for (unsigned char ch : s) { switch (ch) { case '"': out += "\\\""; break; case '\\': out += "\\\\"; break; case '\b': out += "\\b"; break; case '\f': out += "\\f"; break; case '\n': out += "\\n"; break; case '\r': out += "\\r"; break; case '\t': out += "\\t"; break; default: if (ch < 0x20) { char buf[8]; std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast(ch)); out += buf; } else { out.push_back(static_cast(ch)); } break; } } out.push_back('"'); } struct JsonValue; using JsonArray = std::vector; using JsonObject = std::vector>; struct JsonValue { std::variant data; bool is_null() const { return std::holds_alternative(data); } bool is_bool() const { return std::holds_alternative(data); } bool is_number() const { return std::holds_alternative(data); } bool is_string() const { return std::holds_alternative(data); } bool is_array() const { return std::holds_alternative(data); } bool is_object() const { return std::holds_alternative(data); } const JsonValue* find(std::string_view key) const { if (!is_object()) return nullptr; for (const auto& [k, v] : std::get(data)) { if (k == key) return &v; } return nullptr; } }; class JsonParser { public: explicit JsonParser(std::string_view src) : src_(src) {} bool parse(JsonValue& out, std::string& err) { skip_ws(); if (!parse_value(out, 0, err)) return false; skip_ws(); if (pos_ != src_.size()) { err = "Unexpected trailing data in JSON"; return false; } return true; } private: void skip_ws() { while (pos_ < src_.size() && (src_[pos_] == ' ' || src_[pos_] == '\t' || src_[pos_] == '\r' || src_[pos_] == '\n')) { ++pos_; } } static void append_utf8(std::string& out, uint32_t cp) { if (cp <= 0x7F) { out.push_back(static_cast(cp)); } else if (cp <= 0x7FF) { out.push_back(static_cast(0xC0 | (cp >> 6))); out.push_back(static_cast(0x80 | (cp & 0x3F))); } else if (cp <= 0xFFFF) { out.push_back(static_cast(0xE0 | (cp >> 12))); out.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); out.push_back(static_cast(0x80 | (cp & 0x3F))); } else { out.push_back(static_cast(0xF0 | (cp >> 18))); out.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); out.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); out.push_back(static_cast(0x80 | (cp & 0x3F))); } } bool parse_hex4(uint32_t& out) { if (pos_ + 4 > src_.size()) return false; uint32_t v = 0; for (int i = 0; i < 4; ++i) { char ch = src_[pos_++]; v <<= 4; if (ch >= '0' && ch <= '9') v |= static_cast(ch - '0'); else if (ch >= 'a' && ch <= 'f') v |= static_cast(ch - 'a' + 10); else if (ch >= 'A' && ch <= 'F') v |= static_cast(ch - 'A' + 10); else return false; } out = v; return true; } bool parse_string(std::string& out, std::string& err) { if (pos_ >= src_.size() || src_[pos_] != '"') { err = "Expected '\"'"; return false; } ++pos_; out.clear(); while (pos_ < src_.size()) { char ch = src_[pos_++]; if (ch == '"') return true; if (static_cast(ch) < 0x20) { err = "Control character in JSON string"; return false; } if (ch == '\\') { if (pos_ >= src_.size()) { err = "Unterminated escape in JSON string"; return false; } char esc = src_[pos_++]; switch (esc) { case '"': out.push_back('"'); break; case '\\': out.push_back('\\'); break; case '/': out.push_back('/'); break; case 'b': out.push_back('\b'); break; case 'f': out.push_back('\f'); break; case 'n': out.push_back('\n'); break; case 'r': out.push_back('\r'); break; case 't': out.push_back('\t'); break; case 'u': { uint32_t cp = 0; if (!parse_hex4(cp)) { err = "Invalid \\u escape in JSON"; return false; } if (cp >= 0xD800 && cp <= 0xDBFF && pos_ + 6 <= src_.size() && src_[pos_] == '\\' && src_[pos_ + 1] == 'u') { pos_ += 2; uint32_t low = 0; if (!parse_hex4(low) || low < 0xDC00 || low > 0xDFFF) { err = "Invalid UTF-16 surrogate pair in JSON"; return false; } cp = 0x10000 + (((cp - 0xD800) << 10) | (low - 0xDC00)); } append_utf8(out, cp); break; } default: err = "Unknown escape in JSON string"; return false; } } else { out.push_back(ch); } } err = "Unterminated JSON string"; return false; } bool parse_number(double& out, std::string& err) { size_t start = pos_; if (pos_ < src_.size() && src_[pos_] == '-') ++pos_; if (pos_ >= src_.size() || !std::isdigit(static_cast(src_[pos_]))) { err = "Invalid JSON number"; return false; } if (src_[pos_] == '0') { ++pos_; } else { while (pos_ < src_.size() && std::isdigit(static_cast(src_[pos_]))) ++pos_; } if (pos_ < src_.size() && src_[pos_] == '.') { ++pos_; if (pos_ >= src_.size() || !std::isdigit(static_cast(src_[pos_]))) { err = "Invalid JSON fraction"; return false; } while (pos_ < src_.size() && std::isdigit(static_cast(src_[pos_]))) ++pos_; } if (pos_ < src_.size() && (src_[pos_] == 'e' || src_[pos_] == 'E')) { ++pos_; if (pos_ < src_.size() && (src_[pos_] == '+' || src_[pos_] == '-')) ++pos_; if (pos_ >= src_.size() || !std::isdigit(static_cast(src_[pos_]))) { err = "Invalid JSON exponent"; return false; } while (pos_ < src_.size() && std::isdigit(static_cast(src_[pos_]))) ++pos_; } std::string num_str(src_.substr(start, pos_ - start)); char* endptr = nullptr; double val = std::strtod(num_str.c_str(), &endptr); if (endptr != num_str.c_str() + num_str.size() || !std::isfinite(val)) { err = "Non-finite JSON number"; return false; } out = val; return true; } bool parse_value(JsonValue& out, int depth, std::string& err) { if (depth > 64) { err = "JSON nesting too deep"; return false; } skip_ws(); if (pos_ >= src_.size()) { err = "Unexpected end of JSON"; return false; } char ch = src_[pos_]; if (ch == '"') { std::string s; if (!parse_string(s, err)) return false; out.data = std::move(s); return true; } if (ch == '{') { ++pos_; JsonObject obj; skip_ws(); if (pos_ < src_.size() && src_[pos_] == '}') { ++pos_; out.data = std::move(obj); return true; } while (true) { skip_ws(); std::string key; if (!parse_string(key, err)) return false; skip_ws(); if (pos_ >= src_.size() || src_[pos_] != ':') { err = "Expected ':' in JSON object"; return false; } ++pos_; JsonValue val; if (!parse_value(val, depth + 1, err)) return false; obj.emplace_back(std::move(key), std::move(val)); skip_ws(); if (pos_ >= src_.size()) { err = "Unterminated JSON object"; return false; } if (src_[pos_] == '}') { ++pos_; out.data = std::move(obj); return true; } if (src_[pos_] != ',') { err = "Expected ',' or '}' in JSON object"; return false; } ++pos_; } } if (ch == '[') { ++pos_; JsonArray arr; skip_ws(); if (pos_ < src_.size() && src_[pos_] == ']') { ++pos_; out.data = std::move(arr); return true; } while (true) { JsonValue elem; if (!parse_value(elem, depth + 1, err)) return false; arr.push_back(std::move(elem)); skip_ws(); if (pos_ >= src_.size()) { err = "Unterminated JSON array"; return false; } if (src_[pos_] == ']') { ++pos_; out.data = std::move(arr); return true; } if (src_[pos_] != ',') { err = "Expected ',' or ']' in JSON array"; return false; } ++pos_; } } if (src_.substr(pos_, 4) == "true") { pos_ += 4; out.data = true; return true; } if (src_.substr(pos_, 5) == "false") { pos_ += 5; out.data = false; return true; } if (src_.substr(pos_, 4) == "null") { pos_ += 4; out.data = nullptr; return true; } if (ch == '-' || std::isdigit(static_cast(ch))) { double d = 0.0; if (!parse_number(d, err)) return false; out.data = d; return true; } err = "Unexpected token in JSON"; return false; } std::string_view src_; size_t pos_ = 0; }; } // namespace std::string save_native_string(const Workbook& wb) { std::string out; out.reserve(4096); out += "{\n \"htab_version\": 1,\n \"active_sheet\": "; out += std::to_string(wb.active_sheet()); out += ",\n \"sheets\": [\n"; for (int si = 0; si < wb.sheet_count(); ++si) { const Sheet& s = wb.sheet(si); out += " {\n \"name\": "; append_json_string(out, s.name); // Deterministic sorted order for col_widths, row_heights, and cells std::map sorted_cw(s.col_widths.begin(), s.col_widths.end()); out += ",\n \"col_widths\": {"; bool first_cw = true; for (const auto& [col, w] : sorted_cw) { if (!first_cw) out += ", "; first_cw = false; append_json_string(out, std::to_string(col)); out += ": " + std::to_string(w); } out += "}"; std::map sorted_rh(s.row_heights.begin(), s.row_heights.end()); out += ",\n \"row_heights\": {"; bool first_rh = true; for (const auto& [row, h] : sorted_rh) { if (!first_rh) out += ", "; first_rh = false; append_json_string(out, std::to_string(row)); out += ": " + std::to_string(h); } out += "}"; std::vector> sorted_cells; sorted_cells.reserve(s.cells.size()); for (const auto& [key, cell] : s.cells) { if (cell.raw_input.empty() && cell.number_format.empty()) continue; sorted_cells.emplace_back(key, &cell); } std::sort(sorted_cells.begin(), sorted_cells.end(), [](const auto& a, const auto& b) { if (a.first.row != b.first.row) return a.first.row < b.first.row; return a.first.col < b.first.col; }); out += ",\n \"cells\": ["; if (!sorted_cells.empty()) out.push_back('\n'); for (size_t idx = 0; idx < sorted_cells.size(); ++idx) { const auto& [key, cell] = sorted_cells[idx]; out += " {\"r\": " + std::to_string(key.row) + ", \"c\": " + std::to_string(key.col) + ", \"raw\": "; append_json_string(out, cell->raw_input); if (!cell->number_format.empty()) { out += ", \"fmt\": "; append_json_string(out, cell->number_format); } out.push_back('}'); if (idx + 1 < sorted_cells.size()) out.push_back(','); out.push_back('\n'); } if (!sorted_cells.empty()) out += " "; out += "]\n }"; if (si + 1 < wb.sheet_count()) out.push_back(','); out.push_back('\n'); } out += " ]\n}\n"; return out; } bool save_native_file(const Workbook& wb, const std::string& path, std::string* err) { std::ofstream out(path, std::ios::binary | std::ios::trunc); if (!out) { if (err) *err = "Cannot open file for writing: " + path; return false; } std::string data = save_native_string(wb); out.write(data.data(), static_cast(data.size())); if (!out) { if (err) *err = "Failed writing workbook file: " + path; return false; } return true; } bool load_native_string(Workbook& wb, std::string_view json_text, std::string* err) { JsonParser parser(json_text); JsonValue root; std::string parse_err; if (!parser.parse(root, parse_err)) { if (err) *err = parse_err; return false; } if (!root.is_object()) { if (err) *err = "Root JSON value must be an object"; return false; } const JsonValue* ver = root.find("htab_version"); if (!ver || !ver->is_number() || static_cast(std::get(ver->data)) != 1) { if (err) *err = "Unsupported or missing htab_version"; return false; } const JsonValue* sheets_val = root.find("sheets"); if (!sheets_val || !sheets_val->is_array() || std::get(sheets_val->data).empty()) { if (err) *err = "Missing or empty sheets array"; return false; } int active_sheet = 0; if (const JsonValue* act = root.find("active_sheet")) { if (act->is_number()) active_sheet = static_cast(std::get(act->data)); } std::vector loaded_sheets; for (const auto& sv : std::get(sheets_val->data)) { if (!sv.is_object()) { if (err) *err = "Sheet entry must be an object"; return false; } Sheet s; const JsonValue* name_v = sv.find("name"); if (!name_v || !name_v->is_string() || std::get(name_v->data).empty()) { if (err) *err = "Sheet entry missing valid name"; return false; } s.name = std::get(name_v->data); if (const JsonValue* cw = sv.find("col_widths"); cw && cw->is_object()) { for (const auto& [k, v] : std::get(cw->data)) { if (v.is_number()) { int col = std::atoi(k.c_str()); int w = static_cast(std::get(v.data)); if (col >= 0 && col < kMaxCols && w > 0) s.col_widths[col] = w; } } } if (const JsonValue* rh = sv.find("row_heights"); rh && rh->is_object()) { for (const auto& [k, v] : std::get(rh->data)) { if (v.is_number()) { int row = std::atoi(k.c_str()); int h = static_cast(std::get(v.data)); if (row >= 0 && row < kMaxRows && h > 0) s.row_heights[row] = h; } } } if (const JsonValue* cells = sv.find("cells"); cells && cells->is_array()) { for (const auto& cv : std::get(cells->data)) { if (!cv.is_object()) continue; const JsonValue* rv = cv.find("r"); const JsonValue* colv = cv.find("c"); const JsonValue* rawv = cv.find("raw"); if (!rv || !rv->is_number() || !colv || !colv->is_number() || !rawv || !rawv->is_string()) { if (err) *err = "Invalid cell object in JSON"; return false; } int r = static_cast(std::get(rv->data)); int c = static_cast(std::get(colv->data)); if (r < 0 || r >= kMaxRows || c < 0 || c >= kMaxCols) { if (err) *err = "Cell coordinates out of bounds"; return false; } Cell cell; cell.raw_input = std::get(rawv->data); if (const JsonValue* fmtv = cv.find("fmt"); fmtv && fmtv->is_string()) { cell.number_format = std::get(fmtv->data); } s.cells.emplace(CellKey{r, c}, std::move(cell)); } } loaded_sheets.push_back(std::move(s)); } wb.replace_all_sheets(std::move(loaded_sheets), active_sheet); return true; } bool load_native_file(Workbook& wb, const std::string& path, std::string* err) { std::ifstream in(path, std::ios::binary); if (!in) { if (err) *err = "Cannot open workbook file for reading: " + path; return false; } std::ostringstream oss; oss << in.rdbuf(); return load_native_string(wb, oss.str(), err); } } // namespace htab