Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make a stand-in for std::expected available in the code base #3916

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Builds/CMake/RippledCore.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,7 @@ target_sources (rippled PRIVATE
#]===============================]
src/test/basics/Buffer_test.cpp
src/test/basics/DetectCrash_test.cpp
src/test/basics/Expected_test.cpp
src/test/basics/FileUtilities_test.cpp
src/test/basics/IOUAmount_test.cpp
src/test/basics/KeyCache_test.cpp
Expand Down
8 changes: 4 additions & 4 deletions src/ripple/app/tx/impl/SetSignerList.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@ SetSignerList::determineOperation(
{
auto signers = SignerEntries::deserialize(tx, j, "transaction");

if (signers.second != tesSUCCESS)
return std::make_tuple(signers.second, quorum, sign, op);
if (!signers)
return std::make_tuple(signers.error(), quorum, sign, op);

std::sort(signers.first.begin(), signers.first.end());
std::sort(signers->begin(), signers->end());

// Save deserialized list for later.
sign = std::move(signers.first);
sign = std::move(*signers);
op = set;
}
else if ((quorum == 0) && !hasSignerEntries)
Expand Down
14 changes: 5 additions & 9 deletions src/ripple/app/tx/impl/SignerEntries.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

namespace ripple {

std::pair<std::vector<SignerEntries::SignerEntry>, NotTEC>
Expected<std::vector<SignerEntries::SignerEntry>, NotTEC>
SignerEntries::deserialize(
STObject const& obj,
beast::Journal journal,
Expand All @@ -37,11 +37,10 @@ SignerEntries::deserialize(
{
JLOG(journal.trace())
<< "Malformed " << annotation << ": Need signer entry array.";
s.second = temMALFORMED;
return s;
return Unexpected(temMALFORMED);
}

auto& accountVec = s.first;
std::vector<SignerEntry> accountVec;
accountVec.reserve(STTx::maxMultiSigners);

STArray const& sEntries(obj.getFieldArray(sfSignerEntries));
Expand All @@ -52,18 +51,15 @@ SignerEntries::deserialize(
{
JLOG(journal.trace())
<< "Malformed " << annotation << ": Expected SignerEntry.";
s.second = temMALFORMED;
return s;
return Unexpected(temMALFORMED);
}

// Extract SignerEntry fields.
AccountID const account = sEntry.getAccountID(sfAccount);
std::uint16_t const weight = sEntry.getFieldU16(sfSignerWeight);
accountVec.emplace_back(account, weight);
}

s.second = tesSUCCESS;
return s;
return accountVec;
}

} // namespace ripple
3 changes: 2 additions & 1 deletion src/ripple/app/tx/impl/SignerEntries.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#define RIPPLE_TX_IMPL_SIGNER_ENTRIES_H_INCLUDED

#include <ripple/app/tx/impl/Transactor.h> // NotTEC
#include <ripple/basics/Expected.h> //
#include <ripple/beast/utility/Journal.h> // beast::Journal
#include <ripple/protocol/STTx.h> // STTx::maxMultiSigners
#include <ripple/protocol/TER.h> // temMALFORMED
Expand Down Expand Up @@ -62,7 +63,7 @@ class SignerEntries
};

// Deserialize a SignerEntries array from the network or from the ledger.
static std::pair<std::vector<SignerEntry>, NotTEC>
static Expected<std::vector<SignerEntry>, NotTEC>
deserialize(
STObject const& obj,
beast::Journal journal,
Expand Down
8 changes: 4 additions & 4 deletions src/ripple/app/tx/impl/Transactor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -554,8 +554,8 @@ Transactor::checkMultiSign(PreclaimContext const& ctx)

auto accountSigners =
SignerEntries::deserialize(*sleAccountSigners, ctx.j, "ledger");
if (accountSigners.second != tesSUCCESS)
return accountSigners.second;
if (!accountSigners)
return accountSigners.error();

// Get the array of transaction signers.
STArray const& txSigners(ctx.tx.getFieldArray(sfSigners));
Expand All @@ -567,15 +567,15 @@ Transactor::checkMultiSign(PreclaimContext const& ctx)
// matching multi-signers to account signers should be a simple
// linear walk. *All* signers must be valid or the transaction fails.
std::uint32_t weightSum = 0;
auto iter = accountSigners.first.begin();
auto iter = accountSigners->begin();
for (auto const& txSigner : txSigners)
{
AccountID const txSignerAcctID = txSigner.getAccountID(sfAccount);

// Attempt to match the SignerEntry with a Signer;
while (iter->account < txSignerAcctID)
{
if (++iter == accountSigners.first.end())
if (++iter == accountSigners->end())
{
JLOG(ctx.j.trace())
<< "applyTransaction: Invalid SigningAccount.Account.";
Expand Down
4 changes: 2 additions & 2 deletions src/ripple/app/tx/impl/apply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ checkValidity(
: STTx::RequireFullyCanonicalSig::no;

auto const sigVerify = tx.checkSign(requireCanonicalSig);
if (!sigVerify.first)
if (!sigVerify)
{
router.setFlags(id, SF_SIGBAD);
return {Validity::SigBad, sigVerify.second};
return {Validity::SigBad, sigVerify.error()};
}
router.setFlags(id, SF_SIGGOOD);
}
Expand Down
243 changes: 243 additions & 0 deletions src/ripple/basics/Expected.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2021 Ripple Labs Inc.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#ifndef RIPPLE_BASICS_EXPECTED_H_INCLUDED
#define RIPPLE_BASICS_EXPECTED_H_INCLUDED

#include <ripple/basics/contract.h>
#include <boost/outcome.hpp>
#include <stdexcept>
#include <type_traits>

namespace ripple {

/** Expected is an approximation of std::expected (hoped for in C++23)

See: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0323r10.html

The implementation is entirely based on boost::outcome_v2::result.
*/

// Exception thrown by an invalid access to Expected.
struct bad_expected_access : public std::runtime_error
{
bad_expected_access() : runtime_error("bad expected access")
{
}
};

namespace detail {

// Custom policy for Expected. Always throw on an invalid access.
struct throw_policy : public boost::outcome_v2::policy::base
{
template <class Impl>
static constexpr void
wide_value_check(Impl&& self)
{
if (!base::_has_value(std::forward<Impl>(self)))
Throw<bad_expected_access>();
}

template <class Impl>
static constexpr void
wide_error_check(Impl&& self)
{
if (!base::_has_error(std::forward<Impl>(self)))
Throw<bad_expected_access>();
}

template <class Impl>
static constexpr void
wide_exception_check(Impl&& self)
{
if (!base::_has_exception(std::forward<Impl>(self)))
Throw<bad_expected_access>();
}
};

} // namespace detail

// Definition of Unexpected, which is used to construct the unexpected
// return type of an Expected.
template <class E>
class Unexpected
{
public:
static_assert(!std::is_same<E, void>::value, "E must not be void");

Unexpected() = delete;

constexpr explicit Unexpected(E const& e) : val_(e)
{
}

constexpr explicit Unexpected(E&& e) : val_(std::move(e))
{
}

constexpr const E&
value() const&
{
return val_;
}

constexpr E&
value() &
{
return val_;
}

constexpr E&&
value() &&
{
return std::move(val_);
}

constexpr const E&&
value() const&&
{
return std::move(val_);
}

private:
E val_;
};

// Unexpected deduction guide that converts array to const*.
template <typename E, std::size_t N>
Unexpected(E (&)[N]) -> Unexpected<E const*>;

// Definition of Expected. All of the machinery comes from boost::result.
template <class T, class E>
class [[nodiscard]] Expected
: private boost::outcome_v2::result<T, E, detail::throw_policy>
{
using Base = boost::outcome_v2::result<T, E, detail::throw_policy>;

public:
template <
typename U,
typename = std::enable_if_t<std::is_convertible_v<U, T>>>
constexpr Expected(U r) : Base(T{std::forward<U>(r)})
{
}

template <
typename U,
typename = std::enable_if_t<std::is_convertible_v<U, E>>>
constexpr Expected(Unexpected<U> e) : Base(E{std::forward<U>(e.value())})
{
}

constexpr bool has_value() const
{
return Base::has_value();
}

constexpr T const& value() const
{
return Base::value();
}

constexpr T& value()
{
return Base::value();
}

constexpr E const& error() const
{
return Base::error();
}

constexpr E& error()
{
return Base::error();
}

constexpr explicit operator bool() const
{
return has_value();
}

// Add operator* and operator-> so the Expected API looks a bit more like
// what std::expected is likely to look like. See:
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0323r10.html
[[nodiscard]] constexpr T& operator*()
{
return this->value();
}

[[nodiscard]] constexpr T const& operator*() const
{
return this->value();
}

[[nodiscard]] constexpr T* operator->()
{
return &this->value();
}

[[nodiscard]] constexpr T const* operator->() const
{
return &this->value();
}
};

// Specialization of Expected<void, E>. Allows returning either success
// (without a value) or the reason for the failure.
template <class E>
class [[nodiscard]] Expected<void, E>
: private boost::outcome_v2::result<void, E, detail::throw_policy>
{
using Base = boost::outcome_v2::result<void, E, detail::throw_policy>;

public:
// The default constructor makes a successful Expected<void, E>.
// This aligns with std::expected behavior proposed in P0323R10.
constexpr Expected() : Base(boost::outcome_v2::success())
{
}

template <
typename U,
typename = std::enable_if_t<std::is_convertible_v<U, E>>>
constexpr Expected(Unexpected<U> e) : Base(E{std::forward<U>(e.value())})
{
}

constexpr E const& error() const
{
return Base::error();
}

constexpr E& error()
{
return Base::error();
}

constexpr explicit operator bool() const
{
return Base::has_value();
}
};

} // namespace ripple

#endif // RIPPLE_BASICS_EXPECTED_H_INCLUDED
Loading