RSTools 3.1.0
Versatile C++20 utility library
Loading...
Searching...
No Matches
Convert.hpp
Go to the documentation of this file.
1#pragma once
2
4#include "RST/string/Trim.hpp"
5
6#include <charconv>
7#include <initializer_list>
8#include <optional>
9#include <string_view>
10#include <system_error>
11#include <type_traits>
12
13namespace RST::String {
14
17
22 template <typename T>
23 [[nodiscard]] std::optional<T> parseNumber(std::string_view text, int base = 10) noexcept
24 {
25 static_assert(std::is_arithmetic_v<T> && !std::is_same_v<T, bool>, "parseNumber needs a number type");
26 if (base < 2 || base > 36 || (std::is_floating_point_v<T> && base != 10))
27 return std::nullopt;
28
30 if (text.size() > 1 && text[0] == '+' && text[1] != '+' && text[1] != '-')
31 text.remove_prefix(1);
32 if (base == 16 && text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X') && text[2] != '+' && text[2] != '-')
33 text.remove_prefix(2);
34
35 const char* const last = text.data() + text.size();
36 T value{};
37 std::from_chars_result result{};
38 if constexpr (std::is_integral_v<T>)
39 result = std::from_chars(text.data(), last, value, base);
40 else
41 result = std::from_chars(text.data(), last, value);
42
43 if (result.ec != std::errc() || result.ptr != last)
44 return std::nullopt;
45 return value;
46 }
47
49 [[nodiscard]] constexpr std::optional<bool> parseBool(std::string_view text) noexcept
50 {
52 for (const std::string_view yes : {"true", "yes", "on", "1"})
54 return true;
55 for (const std::string_view no : {"false", "no", "off", "0"})
57 return false;
58 return std::nullopt;
59 }
61}
String helpers: case, trimming, splitting, joining, replacing, parsing and hashing.
Definition Char.hpp:3
constexpr std::optional< bool > parseBool(std::string_view text) noexcept
Parses true, yes, on, 1 or false, no, off, 0, ignoring case.
Definition Convert.hpp:49
constexpr std::string_view trimView(std::string_view str, std::string_view chars=Whitespace) noexcept
Definition Trim.hpp:31
constexpr bool equalsIgnoreCase(std::string_view lhs, std::string_view rhs) noexcept
Definition Compare.hpp:15
std::optional< T > parseNumber(std::string_view text, int base=10) noexcept
Parses text as a number, or returns std::nullopt if it is not entirely one.
Definition Convert.hpp:23