Mercurial > minori
comparison include/core/strings.h @ 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 | 39521c47c7a3 |
| children | bc8d2ccff09c |
comparison
equal
deleted
inserted
replaced
| 121:a66c47c1ba3c | 122:bc218c9d2ea6 |
|---|---|
| 2 #define __core__strings_h | 2 #define __core__strings_h |
| 3 | 3 |
| 4 #include <string> | 4 #include <string> |
| 5 #include <vector> | 5 #include <vector> |
| 6 #include <array> | 6 #include <array> |
| 7 #include <limits> | |
| 8 #include <stdexcept> | |
| 7 #include <cstdint> | 9 #include <cstdint> |
| 8 | 10 |
| 9 class QString; | 11 class QString; |
| 10 class QByteArray; | 12 class QByteArray; |
| 11 | 13 |
| 37 std::string ToUtf8String(const QByteArray& ba); | 39 std::string ToUtf8String(const QByteArray& ba); |
| 38 QString ToQString(const std::string& string); | 40 QString ToQString(const std::string& string); |
| 39 QString ToQString(const std::wstring& wstring); | 41 QString ToQString(const std::wstring& wstring); |
| 40 | 42 |
| 41 /* arithmetic :) */ | 43 /* arithmetic :) */ |
| 42 int ToInt(const std::string& str, int def = 0); | 44 template<typename T = int> |
| 45 T ToInt(const std::string& str, T def = 0) { | |
| 46 auto clamp = [](const T& val, const T& min, const T& max){ | |
| 47 return std::max(min, std::min(val, max)); | |
| 48 }; | |
| 49 | |
| 50 try { | |
| 51 if constexpr (std::is_signed<T>::value) { | |
| 52 return clamp(std::stoll(str), std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); | |
| 53 } else if constexpr (std::is_unsigned<T>::value) { | |
| 54 return clamp(std::stoull(str), std::numeric_limits<T>::max(), std::numeric_limits<T>::max()); | |
| 55 } else { | |
| 56 throw std::invalid_argument("it no worky"); | |
| 57 } | |
| 58 } catch (std::invalid_argument const& ex) { | |
| 59 return def; | |
| 60 } | |
| 61 } | |
| 43 | 62 |
| 44 bool ToBool(const std::string& s, const bool def = false); | 63 bool ToBool(const std::string& s, const bool def = false); |
| 45 std::string ToUtf8String(const bool b); | 64 std::string ToUtf8String(const bool b); |
| 46 | 65 |
| 47 uint64_t HumanReadableSizeToBytes(const std::string& str); | 66 uint64_t HumanReadableSizeToBytes(const std::string& str); |
