#include "group.hpp" #include namespace group { namespace { bool space(char value) { return value == ' ' || value == '\t'; } std::string trim(const std::string &text) { std::size_t first = 0; while (first < text.size() && space(text[first])) { ++first; } std::size_t last = text.size(); while (last > first && space(text[last - 1])) { --last; } return text.substr(first, last - first); } bool field(const std::string &text, const std::string &key, std::string &value) { const std::size_t equal = text.find('='); if (equal == std::string::npos || text.find('=', equal + 1) != std::string::npos) { return false; } if (trim(text.substr(0, equal)) != key) { return false; } value = trim(text.substr(equal + 1)); if (value.empty()) { return false; } for (char byte : value) { if (byte < '0' || byte > '9') { return false; } } return true; } } int parse_decimal(const std::string &text, Word maximum, Word &out) { if (text.empty()) { return invalid; } for (char byte : text) { if (byte < '0' || byte > '9') { return invalid; } } Word result = 0; for (char byte : text) { const Word digit = static_cast(byte - '0'); if (digit > maximum || result > (maximum - digit) / 10) { return range; } result = result * 10 + digit; } out = result; return 0; } int decode_config(const std::string &text, Config &out) { const std::size_t semicolon = text.find(';'); if (semicolon == std::string::npos || text.find(';', semicolon + 1) != std::string::npos) { return invalid; } std::string width; std::string capacity; if (!field(text.substr(0, semicolon), "width", width)) { return invalid; } if (!field(text.substr(semicolon + 1), "capacity", capacity)) { return invalid; } Config value; const Word limit = std::numeric_limits::max(); if (parse_decimal(width, limit, value.width) != 0) { return range; } if (parse_decimal(capacity, limit, value.capacity) != 0) { return range; } const int result = validate_config(value); if (result != 0) { return result; } out = value; return 0; } }