aboutsummaryrefslogtreecommitdiff
path: root/src/conversion.cpp
blob: 078d66b0b43148b466f309d9b119c1e35435f205 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "conversion.hpp"

#include <climits>
#include <stdexcept>

auto str_to_uint(const std::string_view &str) noexcept -> ConversionResult<uint32_t>
{
	if (!ctre::match<IS_VALID_UINT>(str))
	{
		return ConversionResult(false, 0U, "Not a number");
	}

	if (!ctre::match<IS_UINT_IN_RANGE>(str))
	{
		return ConversionResult(false, 0U, "Out of range");
	}

	std::size_t waste_pos = 0;

	auto num = std::stoul(str.data(), &waste_pos, NUMBER_BASE);

	if (waste_pos != str.length())
	{
		return ConversionResult(false, 0U, "Not a number");
	}

	if (num > UINT_MAX)
	{
		return ConversionResult(false, 0U, "Out of range");
	}

	return ConversionResult(true, static_cast<uint32_t>(num));
}