IRSOL
C++ code implementing socket server for interacting with Baumer camera.
utils.hpp
Go to the documentation of this file.
1
14#pragma once
15
16#include "irsol/logging.hpp"
17#include "irsol/macros.hpp"
18#include "irsol/types.hpp"
19
20#include <regex>
21#include <sstream>
22#include <string>
23#include <type_traits>
24
25namespace irsol {
26namespace protocol {
27
36namespace utils {
37
54inline std::string
55validateIdentifier(const std::string& identifier)
56{
57 static const std::regex re(R"(^[a-zA-Z_][a-zA-Z0-9_]*(?:\[\d+\])*$)");
58 std::smatch m;
59 if(!std::regex_match(identifier, m, re)) {
60 IRSOL_LOG_ERROR("Invalid identifier '{}'", identifier);
61 throw std::invalid_argument("Invalid identifier");
62 }
63 return identifier;
64}
65
85template<typename T>
86T
87fromString(const std::string& str)
88{
89 std::size_t pos = 0;
90
91 if constexpr(std::is_integral_v<T>) {
92 IRSOL_LOG_TRACE("Converting string '{}' to integer", str);
93 int res = std::stoi(str, &pos);
94 if(pos != str.length())
95 throw std::invalid_argument("Extra characters after integer");
96 return res;
97 } else if constexpr(std::is_floating_point_v<T>) {
98 IRSOL_LOG_TRACE("Converting string '{}' to double", str);
99 double res = std::stod(str, &pos);
100 if(pos != str.length())
101 throw std::invalid_argument("Extra characters after double");
102 return res;
103 } else if constexpr(std::is_same_v<T, std::string>) {
104 return str;
105 } else {
106 IRSOL_MISSING_TEMPLATE_SPECIALIZATION(T, "utils::fromString()");
107 }
108}
109
121inline std::string
122trim(const std::string& s)
123{
124 size_t start = s.find_first_not_of(" \t\r\n");
125 size_t end = s.find_last_not_of(" \t\r\n");
126 return (start == std::string::npos) ? "" : s.substr(start, end - start + 1);
127}
128
129} // namespace utils
130} // namespace protocol
131} // namespace irsol
#define IRSOL_LOG_ERROR(...)
Logs an error-level message using the default logger.
Definition logging.hpp:94
#define IRSOL_LOG_TRACE(...)
Logs a trace-level message using the default logger.
Definition logging.hpp:90
Logging utilities and configuration for the irsol library.
Common portability and diagnostic macros for the irsol library.
#define IRSOL_MISSING_TEMPLATE_SPECIALIZATION(T, funcNameLiteral)
Emits a compile-time error when no template specialization is available.
Definition macros.hpp:173
std::string validateIdentifier(const std::string &identifier)
Validate that a string is a valid protocol identifier.
Definition utils.hpp:55
std::string trim(const std::string &s)
Remove leading and trailing whitespace from a string.
Definition utils.hpp:122
T fromString(const std::string &str)
Convert a string to a value of type T.
Definition utils.hpp:87
irsol::protocol::Assignment m(identifier, value)
Core type definitions for networking, time handling, and protocol values used throughout the irsol li...