From 89bff1a8dcac2f951ac3f2c3d7415691ce16ca12 Mon Sep 17 00:00:00 2001 From: 0xFEEDC0DE64 Date: Thu, 15 Jul 2021 18:36:06 +0200 Subject: [PATCH] Added numberparsing --- CMakeLists.txt | 1 + src/numberparsing.h | 75 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 src/numberparsing.h 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