diff --git a/CMakeLists.txt b/CMakeLists.txt index 9e1087c..aff08d1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9,6 +9,7 @@ set(headers src/cpptypesafeenum.h src/cpputils.h src/delayedconstruction.h + src/numberparsing.h src/refwhenneeded.h src/strutils.h ) diff --git a/src/numberparsing.h b/src/numberparsing.h new file mode 100644 index 0000000..869bfb7 --- /dev/null +++ b/src/numberparsing.h @@ -0,0 +1,75 @@ +#pragma once + +// system includes +#include +#include +#include +#include + +namespace cpputils { +template constexpr std::optional fromString(std::string_view str) = delete; + +template<> constexpr inline std::optional fromString(std::string_view str) +{ + int8_t val{}; + if (std::sscanf(str.data(), "%" SCNi8, &val) == 1) + return val; + return std::nullopt; +} + +template<> constexpr inline std::optional fromString(std::string_view str) +{ + uint8_t val{}; + if (std::sscanf(str.data(), "%" SCNu8, &val) == 1) + return val; + return std::nullopt; +} + +template<> constexpr inline std::optional fromString(std::string_view str) +{ + int16_t val{}; + if (std::sscanf(str.data(), "%" SCNi16, &val) == 1) + return val; + return std::nullopt; +} + +template<> constexpr inline std::optional fromString(std::string_view str) +{ + uint16_t val{}; + if (std::sscanf(str.data(), "%" SCNu16, &val) == 1) + return val; + return std::nullopt; +} + +template<> constexpr inline std::optional fromString(std::string_view str) +{ + int32_t val{}; + if (std::sscanf(str.data(), "%" SCNi32, &val) == 1) + return val; + return std::nullopt; +} + +template<> constexpr inline std::optional fromString(std::string_view str) +{ + uint32_t val{}; + if (std::sscanf(str.data(), "%" SCNu32, &val) == 1) + return val; + return std::nullopt; +} + +template<> constexpr inline std::optional fromString(std::string_view str) +{ + int64_t val{}; + if (std::sscanf(str.data(), "%" SCNi64, &val) == 1) + return val; + return std::nullopt; +} + +template<> constexpr inline std::optional fromString(std::string_view str) +{ + uint64_t val{}; + if (std::sscanf(str.data(), "%" SCNu64, &val) == 1) + return val; + return std::nullopt; +} +} // namespace cpputils