#include "request.hpp" #include #include namespace remaining { namespace { bool horizontal(char value) { return value == ' ' || value == '\t' || value == '\r'; } bool decimal(char value) { return value >= '0' && value <= '9'; } bool digits(const std::string &word, std::size_t first, std::uint64_t limit, std::uint64_t &value) { if (first == word.size()) { return false; } std::uint64_t result = 0; for (std::size_t offset = first; offset < word.size(); ++offset) { if (!decimal(word[offset])) { return false; } const auto digit = static_cast(word[offset] - '0'); if (digit > limit || result > (limit - digit) / 10) { return false; } result = result * 10 + digit; } value = result; return true; } bool scaling(const std::string &unit, std::uint64_t &factor) { if (unit.empty() || unit == "ns") { factor = 1; return true; } if (unit == "us") { factor = 1000; return true; } if (unit == "ms") { factor = 1000000; return true; } if (unit == "s") { factor = kSecond; return true; } return false; } } // namespace std::vector split_words(const std::string &line) { std::vector words; std::size_t cursor = 0; while (cursor < line.size()) { while (cursor < line.size() && horizontal(line[cursor])) { ++cursor; } if (cursor == line.size()) { break; } const auto begin = cursor; while (cursor < line.size() && !horizontal(line[cursor])) { ++cursor; } words.push_back(line.substr(begin, cursor - begin)); } return words; } bool parse_unsigned(const std::string &word, std::uint64_t &value) { if (word.empty()) { return false; } const std::size_t first = word[0] == '+' ? 1 : 0; return digits(word, first, std::numeric_limits::max(), value); } bool parse_signed(const std::string &word, int &value) { if (word.empty()) { return false; } std::size_t first = 0; bool negative = false; if (word[0] == '+' || word[0] == '-') { negative = word[0] == '-'; first = 1; } std::uint64_t magnitude = 0; const auto limit = static_cast(INT_MAX) + (negative ? 1ULL : 0ULL); if (!digits(word, first, limit, magnitude)) { return false; } if (negative && magnitude == static_cast(INT_MAX) + 1ULL) { value = INT_MIN; return true; } value = negative ? -static_cast(magnitude) : static_cast(magnitude); return true; } bool parse_duration(const std::string &word, std::uint64_t &value) { if (word.empty()) { return false; } const std::size_t first = word[0] == '+' ? 1 : 0; auto cursor = first; while (cursor < word.size() && decimal(word[cursor])) { ++cursor; } if (cursor == first) { return false; } const std::string unit = word.substr(cursor); std::uint64_t factor = 0; if (!scaling(unit, factor)) { return false; } const std::string amount = word.substr(first, cursor - first); std::uint64_t number = 0; if (!digits(amount, 0, kMaximumDuration / factor, number)) { return false; } value = number * factor; return true; } } // namespace remaining