#include "clock.hpp" #include #include #include using namespace shared_clock; namespace { bool number(const std::string& text, std::uint64_t& out) { if (text.empty()) { return false; } std::uint64_t value = 0; for (char ch : text) { if (ch < '0' || ch > '9') { return false; } const unsigned digit = static_cast(ch - '0'); if (value > (std::numeric_limits::max() - digit) / 10) { return false; } value = value * 10 + digit; } out = value; return true; } bool no_tail(std::istringstream& input) { std::string extra; return !(input >> extra); } void decimal_word(const std::string& text) { const bool negative = !text.empty() && text[0] == '-'; std::cout << (negative ? '-' : '+') << std::string(5001, '0'); std::cout << (negative ? text.substr(1) : text); } template void field(Number value) { std::cout << " \r\v\f\t"; decimal_word(std::to_string(value)); } void emit(Status status) { decimal_word(std::to_string(static_cast(status))); } void run_line(Engine& engine, const std::string& line) { std::istringstream input(line); std::string command; if (!(input >> command)) { emit(Status::Invalid); return; } if (command == "sample") { std::string point; std::uint64_t failpoint = 0; if (!(input >> point) || !number(point, failpoint) || failpoint > 4294967295ULL) { emit(Status::Invalid); return; } std::string record; std::getline(input, record); const auto first = record.find_first_not_of(" \t\r\v\f"); record = first == std::string::npos ? std::string{} : record.substr(first); emit(engine.submit(record, static_cast(failpoint))); return; } if (command == "policy") { std::string text; std::uint64_t value = 0; if (!(input >> text) || !number(text, value) || !no_tail(input)) { emit(Status::Invalid); return; } emit(engine.configure(Policy{value})); return; } if (command == "project") { std::string now_text; std::string age_text; Tick now = 0; Tick age = 0; if (!(input >> now_text >> age_text) || !number(now_text, now) || !number(age_text, age) || !no_tail(input)) { emit(Status::Invalid); return; } Projection result; const Status status = engine.project(now, age, result); emit(status); if (status == Status::Ok) { field(result.sequence); field(result.remote_ticks); field(result.microseconds); } return; } if (!no_tail(input)) { emit(Status::Invalid); return; } if (command == "read") { Snapshot result; const Status status = engine.latest(result); emit(status); if (status == Status::Ok) { field(result.sequence); field(result.local); field(result.remote); field(result.offset); field(result.delay); field(result.id); } } else if (command == "bytes") { std::cout << encode_hex(engine.page_bytes()); } else if (command == "summary") { std::cout << engine.summary(); } else if (command == "reset") { engine.reset(); emit(Status::Ok); } else { emit(Status::Invalid); } } } int main() { Engine engine; std::string line; while (std::getline(std::cin, line)) { run_line(engine, line); std::cout << "\r\n"; } return 0; }