-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetInt.cpp
More file actions
85 lines (72 loc) · 1.7 KB
/
Copy pathGetInt.cpp
File metadata and controls
85 lines (72 loc) · 1.7 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
*
* @file GetInt.cpp
* @author Gaspard Kirira
*
* Copyright 2025, Gaspard Kirira.
* All rights reserved.
* https://github.com/vixcpp/vix
*
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Vix.cpp
*/
#include <charconv>
#include <cctype>
#include <string>
#include <string_view>
#include <system_error>
#include <vix/env/EnvError.hpp>
#include <vix/env/Get.hpp>
#include <vix/env/GetInt.hpp>
namespace vix::env
{
namespace
{
[[nodiscard]] std::string_view trim(std::string_view value) noexcept
{
std::size_t begin = 0;
std::size_t end = value.size();
while (begin < end &&
std::isspace(static_cast<unsigned char>(value[begin])))
{
++begin;
}
while (end > begin &&
std::isspace(static_cast<unsigned char>(value[end - 1])))
{
--end;
}
return value.substr(begin, end - begin);
}
} // namespace
EnvIntResult get_int(std::string_view key)
{
auto result = get(key);
if (!result)
{
return result.error();
}
const std::string_view value = trim(result.value());
if (value.empty())
{
return make_env_error(
EnvErrorCode::InvalidValue,
"environment value cannot be parsed as int");
}
int parsed = 0;
const auto [ptr, ec] = std::from_chars(
value.data(),
value.data() + value.size(),
parsed,
10);
if (ec != std::errc{} || ptr != value.data() + value.size())
{
return make_env_error(
EnvErrorCode::InvalidValue,
"environment value cannot be parsed as int");
}
return parsed;
}
} // namespace vix::env