Mercurial > minori
changeset 122:bc218c9d2ea6
strings: convert ToInt() to be a template
ini: conform to new strings.cc changes
author | Paper <mrpapersonic@gmail.com> |
---|---|
date | Wed, 08 Nov 2023 21:36:09 -0500 |
parents | a66c47c1ba3c |
children | a45edd073f9e |
files | include/core/ini.h include/core/strings.h |
diffstat | 2 files changed, 21 insertions(+), 5 deletions(-) [+] |
line wrap: on
line diff
--- a/include/core/ini.h Wed Nov 08 18:13:56 2023 -0500 +++ b/include/core/ini.h Wed Nov 08 21:36:09 2023 -0500 @@ -43,12 +43,9 @@ if constexpr (std::is_same<T, bool>::value) { /* Boolean? */ return Strings::ToBool(val); - } else if constexpr (std::is_unsigned<T>::value) { - /* Unsigned? */ - return Strings::ToUnsignedInt(val); } else { /* Always fall back to long long */ - return Strings::ToInt(val); + return Strings::ToInt<T>(val); } } else { return val;
--- a/include/core/strings.h Wed Nov 08 18:13:56 2023 -0500 +++ b/include/core/strings.h Wed Nov 08 21:36:09 2023 -0500 @@ -4,6 +4,8 @@ #include <string> #include <vector> #include <array> +#include <limits> +#include <stdexcept> #include <cstdint> class QString; @@ -39,7 +41,24 @@ QString ToQString(const std::wstring& wstring); /* arithmetic :) */ -int ToInt(const std::string& str, int def = 0); +template<typename T = int> +T ToInt(const std::string& str, T def = 0) { + auto clamp = [](const T& val, const T& min, const T& max){ + return std::max(min, std::min(val, max)); + }; + + try { + if constexpr (std::is_signed<T>::value) { + return clamp(std::stoll(str), std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); + } else if constexpr (std::is_unsigned<T>::value) { + return clamp(std::stoull(str), std::numeric_limits<T>::max(), std::numeric_limits<T>::max()); + } else { + throw std::invalid_argument("it no worky"); + } + } catch (std::invalid_argument const& ex) { + return def; + } +} bool ToBool(const std::string& s, const bool def = false); std::string ToUtf8String(const bool b);