#include "blink.hpp" #include #include #include #include namespace blink { int validate(const Config &config) { if (config.pin < 0 || config.pin > 1023) { return invalid; } if (config.period < 1 || config.period > maximum_period) { return invalid; } if (config.active_low != 0 && config.active_low != 1) { return invalid; } if (config.initial != 0 && config.initial != 1) { return invalid; } return 0; } namespace { bool decimal(const std::string &text, unsigned &output) { if (text.empty()) { return false; } for (char character : text) { if (character < '0' || character > '9') { return false; } } const char *begin = text.data(); const char *end = begin + text.size(); auto result = std::from_chars(begin, end, output); return result.ec == std::errc{} && result.ptr == end; } } int parse_config(const std::string &text, Config &output) { if (text.size() > 128) { return invalid; } for (unsigned char byte : text) { if (byte > 127 || byte == 11 || byte == 12) return invalid; } std::istringstream stream(text); std::string token; std::set seen; Config value; while (stream >> token) { auto equal = token.find('='); if (equal == std::string::npos || equal == 0) { return invalid; } std::string key = token.substr(0, equal); std::string number = token.substr(equal + 1); unsigned parsed = 0; if (!seen.insert(key).second || !decimal(number, parsed)) { return invalid; } if (key == "pin") { if (parsed > 1023) return invalid; value.pin = static_cast(parsed); } else if (key == "period") { value.period = parsed; } else if (key == "low") { if (parsed > 1) return invalid; value.active_low = static_cast(parsed); } else if (key == "initial") { if (parsed > 1) return invalid; value.initial = static_cast(parsed); } else { return invalid; } } if (seen.count("pin") == 0 || validate(value) != 0) { return invalid; } output = value; return 0; } std::string format_config(const Config &config) { return "pin=" + std::to_string(config.pin) + " period=" + std::to_string(config.period) + " low=" + std::to_string(config.active_low) + " initial=" + std::to_string(config.initial); } }