Last active
February 25, 2025 10:50
-
-
Save dk949/642fb0fbd56eeb26895ca85c9ccfcbf3 to your computer and use it in GitHub Desktop.
Convenient string_view to number conversions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef UT_SV_TO_NUM_HPP | |
#define UT_SV_TO_NUM_HPP | |
#include <charconv> | |
#include <concepts> | |
#include <optional> | |
#include <string_view> | |
/** Usage: | |
* int main() { | |
* for (std::string_view sv : {"123", "12.3", "12e3", "abc"}) { | |
* std::cout << "string = " << sv << "\n"; | |
* | |
* if (auto res = ut::svToNum<int>(sv)) | |
* std::cout << "\tres = " << *res << "\n"; | |
* else | |
* std::clog << "\tCould not parse '" << sv << "' as int\n"; | |
* | |
* if (auto res = ut::svToNum<double>(sv)) | |
* std::cout << "\tres = " << *res << "\n"; | |
* else | |
* std::clog << "\tCould not parse '" << sv << "' as double\n"; | |
* | |
* if (auto res = ut::svToNum<int, ut::SvToNumOnlyNumbers::No>(sv)) | |
* std::cout << "\tres = " << res->first << " rest of string = '" << res->second << "'\n"; | |
* else | |
* std::clog << "\tCould not parse any part of '" << sv << "' as int\n"; | |
* | |
* if (auto res = ut::svToNum<double, ut::SvToNumOnlyNumbers::No>(sv)) | |
* std::cout << "\tres = " << res->first << " rest of string = '" << res->second << "'\n"; | |
* else | |
* std::clog << "\tCould not parse any part of '" << sv << "' as double\n"; | |
* | |
* if (auto res = ut::svToInt<int, ut::SvToNumBase(16)>(sv)) | |
* std::cout << "\tres = 0x" << *res << "\n"; | |
* else | |
* std::clog << "\tCould not parse '" << sv << "' as base 16 int\n"; | |
* | |
* if (auto res = ut::svToFloat<float, ut::SvToNumFormat::Hex>(sv)) | |
* std::cout << "\tres = 0x" << *res << "\n"; | |
* else | |
* std::clog << "\tCould not parse '" << sv << "' as hex double\n"; | |
* } | |
* } | |
* // Output: | |
* // string = 123 | |
* // res = 123 | |
* // res = 123 | |
* // res = 123 rest of string = '' | |
* // res = 123 rest of string = '' | |
* // res = 0x291 | |
* // res = 0x291 | |
* // string = 12.3 | |
* // Could not parse '12.3' as int | |
* // res = 12.3 | |
* // res = 12 rest of string = '.3' | |
* // res = 12.3 rest of string = '' | |
* // Could not parse '12.3' as base 16 int | |
* // res = 0x18.1875 | |
* // string = 12e3 | |
* // Could not parse '12e3' as int | |
* // res = 12000 | |
* // res = 12 rest of string = 'e3' | |
* // res = 12000 rest of string = '' | |
* // res = 0x4835 | |
* // res = 0x4835 | |
* // string = abc | |
* // Could not parse 'abc' as int | |
* // Could not parse 'abc' as double | |
* // Could not parse any part of 'abc' as int | |
* // Could not parse any part of 'abc' as double | |
* // res = 0x2748 | |
* // res = 0x2748 | |
* // | |
*/ | |
namespace ut { | |
enum struct SvToNumOnlyNumbers : bool { Yes = true, No = false }; | |
enum struct SvToNumBase : int { Poison = -1, Default = 10 }; | |
enum struct SvToNumFormat { | |
Scientific = int(std::chars_format::scientific), | |
Fixed = int(std::chars_format::fixed), | |
Hex = int(std::chars_format::hex), | |
General = int(std::chars_format::general), | |
Poison, | |
Default = General, | |
}; | |
template<typename Num, SvToNumOnlyNumbers only_numbers> | |
using SvToNumResult = | |
std::optional<std::conditional_t<only_numbers == SvToNumOnlyNumbers::Yes, Num, std::pair<Num, std::string_view>>>; | |
template<typename T> | |
concept SvToNumArithmetic = std::integral<T> || std::floating_point<T>; | |
/** Convert string_view to number | |
* | |
* When `only_numbers` is set to `SvToNumOnlyNumbers::Yes`, tries to parse the whole string as a number. Returns a | |
* `std::optional<Num>`, where Num is the type being converted to. If the string could not be converted to `Num`, | |
* returns `std::nullopt`. | |
* | |
* If `only_numbers` is `SvToNumOnlyNumbers::No`, tries to parse as much of the string as it can. Returns a | |
* `std::optional<std::pair<Num, std::string_view>>`. The `string_view` in the pair holds the unparsed part of the | |
* string. Returns `std::nullopt` if none of the string can be parsed. | |
* | |
* `base` is the base for integral types (10 by default), it should be set to SvToNumBase::Poison when parsing floats. | |
* | |
* `format` is the floating point format (General by default, see `std::chars_format`), it should be set to | |
* SvToNumFormat::Poison when parsing ints. | |
* | |
* NOTE: To avoid manually specifying `Poison` values use `svToNum` and `svToFloat` wrappers. | |
*/ | |
template<SvToNumArithmetic Num, | |
SvToNumOnlyNumbers only_numbers = SvToNumOnlyNumbers::Yes, | |
SvToNumBase base = std::is_integral_v<Num> ? SvToNumBase::Default : SvToNumBase::Poison, | |
SvToNumFormat format = std::is_floating_point_v<Num> ? SvToNumFormat::Default : SvToNumFormat::Poison> | |
[[nodiscard]] | |
SvToNumResult<Num, only_numbers> svToNum(std::string_view sv) noexcept { | |
static_assert(!std::is_integral_v<Num> ? base == SvToNumBase::Poison : true, | |
"Base can only be specified for integral values"); | |
static_assert(!std::is_floating_point_v<Num> ? format == SvToNumFormat::Poison : true, | |
"Format can only be specified for float values"); | |
Num result = 0; | |
auto const endptr = sv.data() + sv.size(); | |
std::from_chars_result res; | |
if constexpr (std::is_integral_v<Num>) | |
res = std::from_chars(sv.data(), endptr, result, int(base)); | |
else | |
res = std::from_chars(sv.data(), endptr, result, std::chars_format(format)); | |
if (res.ec == std::errc()) { | |
if constexpr (bool(only_numbers)) { | |
if (res.ptr == endptr) return result; | |
} else { | |
return std::pair { | |
result, | |
std::string_view {res.ptr, endptr}, | |
}; | |
} | |
} | |
return {}; | |
} | |
/** Convert string_view to integral type | |
* | |
* Simplifies calling svToNum if base needs to be specified | |
* | |
* If type is omitted, long long is used. | |
*/ | |
template<std::integral Num = long long, | |
SvToNumBase base = SvToNumBase::Default, | |
SvToNumOnlyNumbers only_numbers = SvToNumOnlyNumbers::Yes> | |
[[nodiscard]] | |
SvToNumResult<Num, only_numbers> svToInt(std::string_view sv) noexcept { | |
return svToNum<Num, only_numbers, base, SvToNumFormat::Poison>(sv); | |
} | |
/** Convert string_view to float type | |
* | |
* Simplifies calling svToNum if format needs to be specified | |
* | |
* If type is omitted, double is used. | |
*/ | |
template<std::floating_point Num = double, | |
SvToNumFormat format = SvToNumFormat::Default, | |
SvToNumOnlyNumbers only_numbers = SvToNumOnlyNumbers::Yes> | |
[[nodiscard]] | |
SvToNumResult<Num, only_numbers> svToFloat(std::string_view sv) noexcept { | |
return svToNum<Num, only_numbers, SvToNumBase::Poison, format>(sv); | |
} | |
} // namespace ut | |
/* | |
This is free and unencumbered software released into the public domain. | |
Anyone is free to copy, modify, publish, use, compile, sell, or | |
distribute this software, either in source code form or as a compiled | |
binary, for any purpose, commercial or non-commercial, and by any | |
means. | |
In jurisdictions that recognize copyright laws, the author or authors | |
of this software dedicate any and all copyright interest in the | |
software to the public domain. We make this dedication for the benefit | |
of the public at large and to the detriment of our heirs and | |
successors. We intend this dedication to be an overt act of | |
relinquishment in perpetuity of all present and future rights to this | |
software under copyright law. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | |
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | |
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | |
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
For more information, please refer to <https://unlicense.org> | |
*/ | |
#endif // UT_SV_TO_NUM_HPP |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
convert `std::string_view` to a number |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment