Argparse: derive numeric option fields (int, unsigned, double) with strict validation

This commit is contained in:
faumaray committed 2026-12-04 01:02:06 +03:00
1 parent 1bd729147f
commit 520849f82e
2 files changed
+63

No files matched your search

+36
View File
@@ -2,6 +2,7 @@
#include <Void/Core/Meta.hpp>
#include <charconv>
#include <cstdint>
#include <expected>
#include <functional>
@@ -252,6 +253,17 @@ namespace Void::Argparse
Opts out{};
Parser parser{std::move(program), std::move(description)};
// Numeric option sinks: the parser binds text, then converts it with
// strict validation after a successful parse.
struct NumericSink {
std::string text{};
std::string option{};
std::function<bool(std::string_view)> assign{};
};
// Heap-owned so the parser's bound string pointer stays valid when the
// collection grows.
std::vector<std::unique_ptr<NumericSink>> numeric_sinks;
template for (constexpr auto m : Void::Meta::members_v<Opts>)
{
using MT = [:std::meta::type_of(m):];
@@ -278,6 +290,24 @@ namespace Void::Argparse
} else if constexpr (std::same_as<MT, std::string>) {
const std::string def = out.[:m:];
parser.option_default(lng, sht, desc, out.[:m:], def);
} else if constexpr (std::is_arithmetic_v<MT>) {
auto sink = std::make_unique<NumericSink>();
sink->option = lng;
sink->text = std::to_string(out.[:m:]);
sink->assign = [target = &out.[:m:]](std::string_view text) {
using DT = std::remove_pointer_t<decltype(target)>;
DT value{};
const auto result = std::from_chars(
text.data(), text.data() + text.size(), value);
if (result.ec != std::errc{} ||
result.ptr != text.data() + text.size()) {
return false;
}
*target = value;
return true;
};
parser.option_default(lng, sht, desc, sink->text, sink->text);
numeric_sinks.push_back(std::move(sink));
}
// other field types: ignored
}
@@ -286,6 +316,12 @@ namespace Void::Argparse
if (!r) {
return std::unexpected{r.error()};
}
for (const auto& sink : numeric_sinks) {
if (!sink->assign(sink->text)) {
return std::unexpected{"invalid numeric value '" + sink->text +
"' for " + sink->option};
}
}
return out;
}