50 lines
1.2 KiB
C++
50 lines
1.2 KiB
C++
#include <Void/Result/Error.hpp>
|
|
#include <Void/Result/Result.hpp>
|
|
#include <Void/Testing/Assert.hpp>
|
|
#include <Void/Testing/Test.hpp>
|
|
|
|
#include <string>
|
|
|
|
namespace
|
|
{
|
|
Void::Result::Result<int> parse_int(const std::string& s)
|
|
{
|
|
try {
|
|
return Void::Result::ok(std::stoi(s));
|
|
} catch (...) {
|
|
return Void::Result::fail("not a number");
|
|
}
|
|
}
|
|
|
|
Void::Result::Result<int> doubled(int n) { return Void::Result::ok(n * 2); }
|
|
} // namespace
|
|
|
|
Void::Testing::Test and_then_chains_on_success()
|
|
{
|
|
auto r = parse_int("21").and_then(doubled);
|
|
Void::Testing::expect(r.has_value());
|
|
Void::Testing::expect_eq(*r, 42);
|
|
}
|
|
|
|
Void::Testing::Test and_then_short_circuits_on_failure()
|
|
{
|
|
auto r = parse_int("xyz").and_then(doubled);
|
|
Void::Testing::expect(!r.has_value());
|
|
Void::Testing::expect_eq(r.error().message(), std::string{"not a number"});
|
|
}
|
|
|
|
Void::Testing::Test transform_maps_value()
|
|
{
|
|
auto r = parse_int("3").transform([](int n) { return n + 100; });
|
|
Void::Testing::expect(r.has_value());
|
|
Void::Testing::expect_eq(*r, 103);
|
|
}
|
|
|
|
Void::Testing::Test or_else_recovers_on_failure()
|
|
{
|
|
auto r = parse_int("xyz").or_else(
|
|
[](const Void::Result::Error&) { return Void::Result::ok(0); });
|
|
Void::Testing::expect(r.has_value());
|
|
Void::Testing::expect_eq(*r, 0);
|
|
}
|