From 8388664fc68e6742b63bf8482541111f0d02c67e Mon Sep 17 00:00:00 2001 From: ToruNiina Date: Sat, 8 Dec 2018 22:44:15 +0900 Subject: [PATCH] add map_err_or_else to result --- tests/test_result.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ toml/result.hpp | 25 +++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/tests/test_result.cpp b/tests/test_result.cpp index 472f76b..5d7bcdd 100644 --- a/tests/test_result.cpp +++ b/tests/test_result.cpp @@ -259,6 +259,49 @@ BOOST_AUTO_TEST_CASE(test_map_or_else) } } +BOOST_AUTO_TEST_CASE(test_map_err_or_else) +{ + { + const toml::result result(toml::ok(42)); + const auto mapped = result.map_err_or_else( + [](const std::string i) -> std::string { + return i + i; + }, "foobar"); + + BOOST_CHECK_EQUAL(mapped, "foobar"); + } + { + toml::result, std::string> + result(toml::ok(std::unique_ptr(new int(42)))); + const auto mapped = std::move(result).map_err_or_else( + [](const std::string i) -> std::string { + return i + i; + }, "foobar"); + + BOOST_CHECK_EQUAL(mapped, "foobar"); + } + { + const toml::result result(toml::err("hoge")); + const auto mapped = result.map_err_or_else( + [](const std::string i) -> std::string { + return i + i; + }, "foobar"); + + BOOST_CHECK_EQUAL(mapped, "hogehoge"); + } + { + toml::result, std::string> + result(toml::err("hoge")); + const auto mapped = result.map_err_or_else( + [](const std::string i) -> std::string { + return i + i; + }, "foobar"); + + BOOST_CHECK_EQUAL(mapped, "hogehoge"); + } +} + + BOOST_AUTO_TEST_CASE(test_and_then) { { diff --git a/toml/result.hpp b/toml/result.hpp index fde9729..ac08059 100644 --- a/toml/result.hpp +++ b/toml/result.hpp @@ -494,6 +494,31 @@ struct result return f(std::move(this->as_ok())); } + // prerequisities + // F: E -> U + // retval: U + template + return_type_of_t + map_err_or_else(F&& f, U&& opt) & + { + if(this->is_ok()){return std::forward(opt);} + return f(this->as_err()); + } + template + return_type_of_t + map_err_or_else(F&& f, U&& opt) const& + { + if(this->is_ok()){return std::forward(opt);} + return f(this->as_err()); + } + template + return_type_of_t + map_err_or_else(F&& f, U&& opt) && + { + if(this->is_ok()){return std::forward(opt);} + return f(std::move(this->as_err())); + } + // prerequisities: // F: func T -> U // toml::err(error_type) should be convertible to U.