#include "topic.hpp" #include #include namespace retained { namespace { bool horizontal(char ch) { return ch == ' ' || ch == '\t'; } std::string trim(const std::string &text) { std::size_t first = 0; while (first < text.size() && horizontal(text[first])) { ++first; } std::size_t last = text.size(); while (last > first && horizontal(text[last - 1])) { --last; } return text.substr(first, last - first); } bool depth_value(const std::string &token, int &out) { if (token.empty()) { return false; } std::size_t at = 0; if (token[at] == '+') { ++at; } if (at == token.size()) { return false; } int value = 0; for (; at < token.size(); ++at) { char ch = token[at]; if (ch < '0' || ch > '9') { return false; } if (value > 8) { return false; } value = value * 10 + ch - '0'; } if (value < 1 || value > 8) { return false; } out = value; return true; } } bool valid_policy(const Policy &policy) { return (policy.durability == 0 || policy.durability == 1) && policy.depth >= 1 && policy.depth <= 8; } int profile_policy(const std::string &name, Policy &out) { Policy next; if (name == "sensor") { next.durability = 0; next.depth = 1; } else if (name == "map") { next.durability = 0; next.depth = 3; } else if (name == "control") { next.durability = 0; next.depth = 2; } else if (name == "status") { next.durability = 1; next.depth = 1; } else { return invalid; } out = next; return 0; } int parse_policy(const std::string &text, Policy &out) { std::string clean = trim(text); Policy next; if (profile_policy(clean, next) == 0) { out = next; return 0; } std::size_t slash = clean.find('/'); if (slash == std::string::npos || clean.find('/', slash + 1) != std::string::npos) { return invalid; } std::string durability = trim(clean.substr(0, slash)); std::string depth = trim(clean.substr(slash + 1)); if (durability == "volatile") { next.durability = 0; } else if (durability == "retained") { next.durability = 1; } else { return invalid; } if (!depth_value(depth, next.depth)) { return invalid; } out = next; return 0; } std::string format_policy(const Policy &policy) { if (!valid_policy(policy)) { return "invalid"; } const std::string prefix = policy.durability == 0 ? "volatile/" : "retained/"; return prefix + std::to_string(policy.depth); } }