Skip to content

Commit

Permalink
Result::assumeValue
Browse files Browse the repository at this point in the history
Signed-off-by: Mikhail Boldyrev <miboldyrev@gmail.com>
  • Loading branch information
MBoldyrev committed Dec 24, 2019
1 parent eb3ce86 commit e6f9515
Show file tree
Hide file tree
Showing 20 changed files with 111 additions and 90 deletions.
10 changes: 5 additions & 5 deletions iroha-cli/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ namespace fs = boost::filesystem;

iroha::keypair_t *makeOldModel(const shared_model::crypto::Keypair &keypair) {
return new iroha::keypair_t{
iroha::expected::resultToValue(
iroha::pubkey_t::from_string(toBinaryString(keypair.publicKey()))),
iroha::expected::resultToValue(
iroha::privkey_t::from_string(toBinaryString(keypair.privateKey())))};
iroha::pubkey_t::from_string(toBinaryString(keypair.publicKey()))
.assumeValue(),
iroha::privkey_t::from_string(toBinaryString(keypair.privateKey()))
.assumeValue()};
}

int main(int argc, char *argv[]) {
Expand Down Expand Up @@ -246,7 +246,7 @@ int main(int argc, char *argv[]) {
0,
std::make_shared<iroha::model::ModelCryptoProviderImpl>(
*std::unique_ptr<iroha::keypair_t>(
makeOldModel(iroha::expected::resultToValue(keypair)))),
makeOldModel(keypair.assumeValue()))),
response_handler_log_manager,
pb_qry_factory_log,
json_qry_factory_log,
Expand Down
2 changes: 1 addition & 1 deletion irohad/main/application.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ Irohad::RunResult Irohad::initStorage(
return expected::makeError(std::move(*error));
}

pool_wrapper_ = resultToValue(std::move(pool));
pool_wrapper_ = std::move(pool).assumeValue();

std::unique_ptr<BlockStorageFactory> temporary_block_storage_factory =
std::make_unique<PostgresBlockStorageFactory>(
Expand Down
6 changes: 3 additions & 3 deletions irohad/main/irohad.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ int main(int argc, char *argv[]) {
log->error("Failed reading the configuration file: {}", e.value());
return EXIT_FAILURE;
}
auto config = iroha::expected::resultToValue(std::move(config_result));
auto config = std::move(config_result).assumeValue();

if (not log_manager) {
log_manager = config.logger_manager.value_or(getDefaultLogManager());
Expand Down Expand Up @@ -215,7 +215,7 @@ int main(int argc, char *argv[]) {
std::chrono::milliseconds(config.vote_delay),
std::chrono::minutes(
config.mst_expiration_time.value_or(kMstExpirationTimeDefault)),
iroha::expected::resultToValue(std::move(keypair)),
std::move(keypair).assumeValue(),
std::chrono::milliseconds(
config.max_round_delay_ms.value_or(kMaxRoundsDelayDefault)),
config.stale_stream_max_rounds.value_or(kStaleStreamMaxRoundsDefault),
Expand Down Expand Up @@ -274,7 +274,7 @@ int main(int argc, char *argv[]) {
log->error("Failed to parse genesis block: {}", e.value());
return EXIT_FAILURE;
}
auto block = iroha::expected::resultToValue(std::move(block_result));
auto block = std::move(block_result).assumeValue();

if (not blockstore and overwrite) {
log->warn(
Expand Down
10 changes: 4 additions & 6 deletions irohad/model/converters/impl/pb_block_factory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,16 +59,14 @@ namespace iroha {

block.txs_number = static_cast<uint16_t>(pl.tx_number());
block.height = pl.height();
block.prev_hash = iroha::expected::resultToValue(
hash256_t::from_string(pl.prev_block_hash()));
block.prev_hash =
hash256_t::from_string(pl.prev_block_hash()).assumeValue();
block.created_ts = pl.created_time();

for (const auto &pb_sig : pb_block.block_v1().signatures()) {
model::Signature sig;
sig.signature = iroha::expected::resultToValue(
sig_t::from_string(pb_sig.signature()));
sig.pubkey = iroha::expected::resultToValue(
pubkey_t::from_string(pb_sig.public_key()));
sig.signature = sig_t::from_string(pb_sig.signature()).assumeValue();
sig.pubkey = pubkey_t::from_string(pb_sig.public_key()).assumeValue();
block.sigs.push_back(std::move(sig));
}

Expand Down
12 changes: 6 additions & 6 deletions irohad/model/converters/impl/pb_query_factory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ namespace iroha {
pb_cast.tx_hashes().end(),
std::back_inserter(query.tx_hashes),
[](auto tx_hash) {
return iroha::expected::resultToValue(
iroha::hash256_t::from_hexstring(tx_hash));
return iroha::hash256_t::from_hexstring(tx_hash)
.assumeValue();
});
val = std::make_shared<GetTransactions>(query);
break;
Expand Down Expand Up @@ -138,10 +138,10 @@ namespace iroha {
const auto &pb_sign = pb_query.signature();

Signature sign{};
sign.pubkey = iroha::expected::resultToValue(
pubkey_t::from_hexstring(pb_sign.public_key()));
sign.signature = iroha::expected::resultToValue(
sig_t::from_hexstring(pb_sign.signature()));
sign.pubkey =
pubkey_t::from_hexstring(pb_sign.public_key()).assumeValue();
sign.signature =
sig_t::from_hexstring(pb_sign.signature()).assumeValue();

val->query_counter = pl.meta().query_counter();
val->signature = sign;
Expand Down
8 changes: 4 additions & 4 deletions irohad/model/converters/impl/pb_transaction_factory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ namespace iroha {

for (const auto &pb_sig : pb_tx.signatures()) {
model::Signature sig{};
sig.pubkey = iroha::expected::resultToValue(
pubkey_t::from_hexstring(pb_sig.public_key()));
sig.signature = iroha::expected::resultToValue(
sig_t::from_hexstring(pb_sig.signature()));
sig.pubkey =
pubkey_t::from_hexstring(pb_sig.public_key()).assumeValue();
sig.signature =
sig_t::from_hexstring(pb_sig.signature()).assumeValue();
tx.signatures.push_back(sig);
}

Expand Down
20 changes: 10 additions & 10 deletions irohad/model/generators/impl/transaction_generator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ namespace iroha {
iroha::keypair_t *makeOldModel(
const shared_model::crypto::Keypair &keypair) {
return new iroha::keypair_t{
iroha::expected::resultToValue(iroha::pubkey_t::from_string(
toBinaryString(keypair.publicKey()))),
iroha::expected::resultToValue(iroha::privkey_t::from_string(
toBinaryString(keypair.privateKey())))};
iroha::pubkey_t::from_string(toBinaryString(keypair.publicKey()))
.assumeValue(),
iroha::privkey_t::from_string(toBinaryString(keypair.privateKey()))
.assumeValue()};
}

Transaction TransactionGenerator::generateGenesisTransaction(
Expand All @@ -38,8 +38,8 @@ namespace iroha {
KeysManagerImpl manager("node" + std::to_string(i),
keys_manager_logger);
manager.createKeys(boost::none);
auto keypair = *std::unique_ptr<iroha::keypair_t>(makeOldModel(
iroha::expected::resultToValue(manager.loadKeys(boost::none))));
auto keypair = *std::unique_ptr<iroha::keypair_t>(
makeOldModel(manager.loadKeys(boost::none).assumeValue()));
tx.commands.push_back(command_generator.generateAddPeer(
Peer(peers_address[i], keypair.pubkey)));
}
Expand All @@ -60,14 +60,14 @@ namespace iroha {
// Create accounts
KeysManagerImpl manager("admin@test", keys_manager_logger);
manager.createKeys(boost::none);
auto keypair = *std::unique_ptr<iroha::keypair_t>(makeOldModel(
iroha::expected::resultToValue(manager.loadKeys(boost::none))));
auto keypair = *std::unique_ptr<iroha::keypair_t>(
makeOldModel(manager.loadKeys(boost::none).assumeValue()));
tx.commands.push_back(command_generator.generateCreateAccount(
"admin", "test", keypair.pubkey));
manager = KeysManagerImpl("test@test", std::move(keys_manager_logger));
manager.createKeys(boost::none);
keypair = *std::unique_ptr<iroha::keypair_t>(makeOldModel(
iroha::expected::resultToValue(manager.loadKeys(boost::none))));
keypair = *std::unique_ptr<iroha::keypair_t>(
makeOldModel(manager.loadKeys(boost::none).assumeValue()));
tx.commands.push_back(command_generator.generateCreateAccount(
"test", "test", keypair.pubkey));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,7 @@ grpc::Status MstTransportGrpc::SendState(
}

auto batches = shared_model::interface::parseAndCreateBatches(
*batch_parser_,
*batch_factory_,
expected::resultToValue(std::move(transactions)));
*batch_parser_, *batch_factory_, std::move(transactions).assumeValue());
if (auto e = expected::resultToOptionalError(batches)) {
log_->warn("Batch deserialization failed: {}", *e);
return ::grpc::Status::OK;
Expand Down
6 changes: 2 additions & 4 deletions irohad/ordering/impl/on_demand_os_server_grpc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,13 @@ grpc::Status OnDemandOsServerGrpc::SendBatches(
}

auto batches = shared_model::interface::parseAndCreateBatches(
*batch_parser_,
*batch_factory_,
expected::resultToValue(std::move(transactions)));
*batch_parser_, *batch_factory_, std::move(transactions).assumeValue());
if (auto e = expected::resultToOptionalError(batches)) {
log_->warn("Batch deserialization failed: {}", *e);
return ::grpc::Status::OK;
}

ordering_service_->onBatches(expected::resultToValue(std::move(batches)));
ordering_service_->onBatches(std::move(batches).assumeValue());

return ::grpc::Status::OK;
}
Expand Down
4 changes: 2 additions & 2 deletions irohad/torii/impl/command_service_transport_grpc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,13 @@ namespace iroha {
auto batches = shared_model::interface::parseAndCreateBatches(
*batch_parser_,
*batch_factory_,
expected::resultToValue(std::move(transactions)));
std::move(transactions).assumeValue());
if (auto e = expected::resultToOptionalError(batches)) {
return publish_stateless_fail(
fmt::format("Batch deserialization failed: {}", *e));
}

for (auto &batch : expected::resultToValue(std::move(batches))) {
for (auto &batch : std::move(batches).assumeValue()) {
this->command_service_->handleTransactionBatch(std::move(batch));
}

Expand Down
79 changes: 55 additions & 24 deletions libs/common/result.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "common/result_fwd.hpp"

#include <ciso646>
#include <type_traits>

#include <boost/optional.hpp>
#include <boost/variant.hpp>
Expand Down Expand Up @@ -179,6 +180,60 @@ namespace iroha {
[](ValueType val) -> Result<Value, E> { return val; },
[res = new_res](ErrorType) { return res; });
}

using AssumeValueHelper =
std::conditional_t<std::is_void<ValueInnerType>::value,
void *,
ValueInnerType>;

/// @return value if present, otherwise throw ResultException
template <typename ReturnType = AssumeValueHelper &>
std::enable_if_t<not std::is_void<ValueInnerType>::value, ReturnType>
assumeValue() & {
auto val = boost::get<ValueType>(this);
if (val != nullptr) {
return val->value;
}
throw ResultException("Value expected, but got an Error.");
}

/// @return value if present, otherwise throw ResultException
template <typename ReturnType = AssumeValueHelper &&>
std::enable_if_t<not std::is_void<ValueInnerType>::value, ReturnType>
assumeValue() && {
auto val = boost::get<ValueType>(this);
if (val != nullptr) {
return std::move(val->value);
}
throw ResultException("Value expected, but got an Error.");
}

using AssumeErrorHelper =
std::conditional_t<std::is_void<ErrorInnerType>::value,
void *,
ErrorInnerType>;

/// @return error if present, otherwise throw ResultException
template <typename ReturnType = AssumeErrorHelper &>
std::enable_if_t<not std::is_void<ErrorInnerType>::value, ReturnType>
assumeError() & {
auto val = boost::get<ErrorType>(this);
if (val != nullptr) {
return val->value;
}
throw ResultException("Error expected, but got a Value.");
}

/// @return error if present, otherwise throw ResultException
template <typename ReturnType = AssumeErrorHelper &&>
std::enable_if_t<not std::is_void<ErrorInnerType>::value, ReturnType>
assumeError() && {
auto val = boost::get<ErrorType>(this);
if (val != nullptr) {
return std::move(val->value);
}
throw ResultException("Error expected, but got a Value.");
}
};

template <typename ResultType>
Expand Down Expand Up @@ -423,30 +478,6 @@ namespace iroha {
return {};
}

/// @return value if present, otherwise throw ResultException
template <typename ResultType,
typename = std::enable_if_t<isResult<ResultType>>>
typename std::decay_t<ResultType>::ValueInnerType resultToValue(
ResultType &&res) {
if (hasValue(res)) {
return boost::get<ValueOf<ResultType>>(std::forward<ResultType>(res))
.value;
}
throw ResultException("Value expected, but got an Error.");
}

/// @return error if present, otherwise throw ResultException
template <typename ResultType,
typename = std::enable_if_t<isResult<ResultType>>>
typename std::decay_t<ResultType>::ErrorInnerType resultToError(
ResultType &&res) {
if (hasError(res)) {
return boost::get<ErrorOf<ResultType>>(std::forward<ResultType>(res))
.error;
}
throw ResultException("Error expected, but got a Value.");
}

template <typename E, typename V>
Result<typename V::value_type, std::decay_t<E>> optionalValueToResult(
V &&value, E &&error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ shared_model::proto::deserializeTransactions(
if (auto e = iroha::expected::resultToOptionalError(model_tx)) {
return *e;
}
tx_collection.emplace_back(
iroha::expected::resultToValue(std::move(model_tx)));
tx_collection.emplace_back(std::move(model_tx).assumeValue());
}
return tx_collection;
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ shared_model::interface::parseAndCreateBatches(
if (auto e = iroha::expected::resultToOptionalError(batch)) {
return *e;
}
batches.push_back(iroha::expected::resultToValue(std::move(batch)));
batches.push_back(std::move(batch).assumeValue());
}
return batches;
}
2 changes: 1 addition & 1 deletion test/framework/test_db_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ TestDbManager::createWithRandomDbName(
if (auto e = resultToOptionalError(db_exists_result)) {
return std::move(e).value();
}
const bool db_exists = resultToValue(db_exists_result);
const bool db_exists = db_exists_result.assumeValue();
if (not db_exists) {
return PgConnectionInit::createDatabaseIfNotExist(*pg_opts) |
[&](bool db_was_created) {
Expand Down
2 changes: 1 addition & 1 deletion test/integration/executor/executor_fixture.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ void ExecutorTestBase::SetUp() {
auto executor_itf_result =
ExecutorItf::create(getBackendParam()->getExecutorItfParam());
IROHA_ASSERT_RESULT_VALUE(executor_itf_result);
executor_itf_ = resultToValue((std::move(executor_itf_result)));
executor_itf_ = std::move(executor_itf_result).assumeValue();
}

ExecutorItf &ExecutorTestBase::getItf() const {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ PostgresExecutorTestParam::PostgresExecutorTestParam() {
if (auto e = resultToOptionalError(db_manager_result)) {
throw std::runtime_error(e.value());
}
db_manager_ = resultToValue(std::move(db_manager_result));
db_manager_ = std::move(db_manager_result).assumeValue();

executor_itf_target_ = createPostgresExecutorItfTarget(*db_manager_);
}
Expand Down
2 changes: 1 addition & 1 deletion test/module/irohad/ametsuchi/ametsuchi_fixture.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ namespace iroha {
std::terminate();
}

pool_wrapper_ = expected::resultToValue(std::move(pool));
pool_wrapper_ = std::move(pool).assumeValue();

StorageImpl::create(std::move(options),
std::move(pool_wrapper_),
Expand Down
2 changes: 1 addition & 1 deletion test/module/irohad/common/raw_block_loader_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ TEST(BlockLoaderTest, BlockLoaderJsonParsing) {
auto block = loader.parseBlock(str);

IROHA_ASSERT_RESULT_VALUE(block);
auto b = iroha::expected::resultToValue(std::move(block));
auto b = std::move(block).assumeValue();

ASSERT_EQ(b->transactions().size(), 0);
ASSERT_EQ(b->height(), 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ using namespace shared_model::proto;
using namespace shared_model::converters::protobuf;
using namespace shared_model;

using iroha::expected::resultToValue;

/**
* Converts json into arbitrary transaction shared model object
* @tparam T type of shared model object converted from json
Expand Down

0 comments on commit e6f9515

Please sign in to comment.