-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathis_number.hh
56 lines (43 loc) · 1.33 KB
/
is_number.hh
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright (c) 2022 Mikael Simonsson <https://mikaelsimonsson.com>.
// SPDX-License-Identifier: BSL-1.0
// # Is number
// Does string match an arbitrary precision decimal number with an optional fraction/exponent.
#pragma once
#include "snn-core/chr/common.hh"
#include "snn-core/fn/common.hh"
#include "snn-core/range/contiguous.hh"
namespace snn::json
{
// ## Functions
// ### is_number
[[nodiscard]] constexpr bool is_number(const transient<cstrview> s) noexcept
{
auto rng = s.get().range();
// Optional minus sign.
rng.drop_front('-');
// Leading zero or one or more digits.
if (rng.drop_front('0') || rng.pop_front_while(chr::is_digit))
{
// Fraction
if (rng.drop_front('.'))
{
if (!rng.pop_front_while(chr::is_digit))
{
return false;
}
}
// Exponent
if (rng.drop_front_if(fn::in_array{'e', 'E'}))
{
// Optional plus/minus sign.
rng.drop_front_if(fn::in_array{'+', '-'});
if (!rng.pop_front_while(chr::is_digit))
{
return false;
}
}
return rng.is_empty();
}
return false;
}
}