Implements merging of Result<T>.

This commit is contained in:
Erik Kundt 2019-02-27 16:21:56 +01:00
parent d1d6d59c80
commit 6ac5c52528
2 changed files with 41 additions and 2 deletions

View File

@ -17,6 +17,7 @@
#pragma once
#include <string>
#include <iostream>
namespace dev
{
@ -39,8 +40,8 @@ template <class ResultType>
class Result
{
public:
Result(ResultType _value): Result(_value, std::string{}) {}
Result(std::string _message): Result(ResultType{}, std::move(_message)) {}
Result(ResultType _value): Result(_value, std::string{}) { }
Result(std::string _message): Result(ResultType{}, std::move(_message)) { }
/// @{
/// @name Wrapper functions
@ -53,6 +54,16 @@ public:
/// @returns the error message (can be empty).
std::string const& message() const { return m_message; }
/// Merges _other into this using the _merger
/// and appends the error messages. Meant to be called
/// with logical operators like logical_and, etc.
template<typename F>
void merge(Result<ResultType> const& _other, F _merger)
{
m_value = _merger(m_value, _other.get());
m_message += _other.message();
}
private:
explicit Result(ResultType _value, std::string _message):
m_value(std::move(_value)),

View File

@ -243,6 +243,34 @@ BOOST_AUTO_TEST_CASE(encoded_sizes)
BOOST_CHECK_EQUAL(twoDimArray.calldataEncodedSize(false), 9 * 3 * 32);
}
BOOST_AUTO_TEST_CASE(helper_bool_result)
{
BoolResult r1{true};
BoolResult r2{string{"Failure."}};
r1.merge(r2, logical_and<bool>());
BOOST_REQUIRE_EQUAL(r1.get(), false);
BOOST_REQUIRE_EQUAL(r1.message(), "Failure.");
BoolResult r3{false};
BoolResult r4{true};
r3.merge(r4, logical_and<bool>());
BOOST_REQUIRE_EQUAL(r3.get(), false);
BOOST_REQUIRE_EQUAL(r3.message(), "");
BoolResult r5{true};
BoolResult r6{true};
r5.merge(r6, logical_and<bool>());
BOOST_REQUIRE_EQUAL(r5.get(), true);
BOOST_REQUIRE_EQUAL(r5.message(), "");
BoolResult r7{true};
// Attention: this will implicitely convert to bool.
BoolResult r8{"true"};
r7.merge(r8, logical_and<bool>());
BOOST_REQUIRE_EQUAL(r7.get(), true);
BOOST_REQUIRE_EQUAL(r7.message(), "");
}
BOOST_AUTO_TEST_SUITE_END()
}