#include "decimal.hpp" #include namespace decimal { Session::Session() = default; bool Session::slot_ok(int slot) { return slot >= 0 && slot < 4; } Code Session::put(int slot, const std::string& source) { if (!slot_ok(slot)) { return Code::SLOT; } if (source.size() > 128) { return Code::LENGTH; } Cell replacement; replacement.source = source; cells_[static_cast(slot)] = std::move(replacement); return Code::OK; } Prefix Session::scan(int slot, int begin) { if (!slot_ok(slot)) { Prefix rejected; rejected.code = Code::SLOT; return rejected; } Cell& cell = cells_[static_cast(slot)]; Prefix result = decode(cell.source, begin); if (result.code != Code::OK) { return result; } cell.last = result; cell.scanned = true; return result; } Code Session::clear(int slot) { if (!slot_ok(slot)) { return Code::SLOT; } cells_[static_cast(slot)] = Cell{}; return Code::OK; } View Session::view(int slot) const { View result; if (!slot_ok(slot)) { result.code = Code::SLOT; return result; } const Cell& cell = cells_[static_cast(slot)]; result.source = cell.source; result.scanned = cell.scanned; result.last = cell.last; return result; } std::string code_name(Code code) { switch (code) { case Code::OK: return "OK"; case Code::SLOT: return "SLOT"; case Code::LENGTH: return "LENGTH"; case Code::OFFSET: return "OFFSET"; case Code::NO_NUMBER: return "NO_NUMBER"; case Code::VALUE: return "VALUE"; } return "UNKNOWN"; } std::string hex_encode(const std::string& bytes) { if (bytes.empty()) { return "-"; } const char* alphabet = "0123456789abcdef"; std::string text; text.reserve(bytes.size() * 2); for (unsigned char byte : bytes) { unsigned high = byte >> 4; unsigned low = byte & 15; char first = alphabet[high]; char second = alphabet[low]; text.push_back(first); text.push_back(second); } return text; } namespace { int unhex(unsigned char byte) { if (byte >= '0' && byte <= '9') { return byte - '0'; } if (byte >= 'a' && byte <= 'f') { return byte - 'a' + 10; } if (byte >= 'A' && byte <= 'F') { return byte - 'A' + 10; } return -1; } } bool hex_decode(const std::string& token, std::string& bytes) { std::string decoded; if (token == "-") { bytes.clear(); return true; } if (token.empty() || token.size() % 2 != 0) { return false; } decoded.reserve(token.size() / 2); for (std::size_t i = 0; i < token.size(); i += 2) { int high = unhex(static_cast(token[i])); int low = unhex(static_cast(token[i + 1])); if (high < 0 || low < 0) { return false; } unsigned combined = static_cast(high) << 4; combined |= static_cast(low); char byte = static_cast(combined); decoded.push_back(byte); } bytes.swap(decoded); return true; } }