sandbox
Loading...
Searching...
No Matches
cli.hpp
1#ifndef LIBSBX_CORE_CLI_HPP_
2#define LIBSBX_CORE_CLI_HPP_
3
4#include <string>
5#include <string_view>
6#include <span>
7#include <vector>
8#include <string_view>
9#include <concepts>
10#include <cinttypes>
11#include <optional>
12#include <charconv>
13
14#include <fmt/format.h>
15
17
18namespace sbx::core {
19
20template<typename Type>
21concept argument = (std::is_same_v<Type, bool> || std::is_integral_v<Type> || std::is_floating_point_v<Type> || std::is_same_v<Type, std::string>);
22
23class cli {
24
25 friend class engine;
26
27public:
28
29 cli(std::span<std::string_view> args) {
30 for (const auto& arg : args) {
31 if (arg.substr(0, 2) != "--") {
32 continue;
33 }
34
35 const auto pos = arg.find_first_of("=");
36
37 if (pos == std::string::npos) {
38 logger::warn("Could not parse argument: '{}'", arg);
39 continue;
40 }
41
42 const auto key = std::string{arg.substr(2, pos - 2u)};
43 const auto value = std::string{arg.substr(pos + 1u)};
44
45 _arguments[key] = std::move(value);
46 }
47 }
48
49 template<argument Type>
50 auto argument(const std::string& name) const -> std::optional<Type> {
51 if (auto entry = _arguments.find(name); entry != _arguments.end()) {
52 const auto& value = entry->second;
53
54 if constexpr (std::is_same_v<Type, bool>) {
55 if (value == "true") {
56 return true;
57 } else if (value == "false") {
58 return false;
59 } else {
60 return std::nullopt;
61 }
62 } else if constexpr (std::is_floating_point_v<Type> || std::is_integral_v<Type>) {
63 auto result = Type{};
64
65 auto [ptr, ec] = std::from_chars(value.data(), value.data() + value.size(), result);
66
67 if (ec == std::errc::invalid_argument || ec == std::errc::result_out_of_range) {
68 return std::nullopt;
69 }
70
71 return result;
72 } else if constexpr (std::is_same_v<Type, std::string>) {
73 return value;
74 }
75 }
76
77 return std::nullopt;
78 }
79
80private:
81
82 auto _argument_value(const std::string& name) -> std::optional<std::string> {
83 if (auto entry = _arguments.find(name); entry != _arguments.end()) {
84 return entry->second;
85 }
86
87 return std::nullopt;
88 }
89
90 std::unordered_map<std::string, std::string> _arguments;
91
92}; // class cli
93
94} // namespace sbx::core
95
96#endif // LIBSBX_CORE_CLI_HPP_
Definition: cli.hpp:23
Definition: engine.hpp:27