Skip to content

Commit 9f5845c

Browse files
committed
partial bitcoin#25218: introduce generic 'Result' class and connect it to CreateTransaction and GetNewDestination
includes: - 7a45c33
1 parent db7e174 commit 9f5845c

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Makefile.am

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,7 @@ BITCOIN_CORE_H = \
367367
util/overloaded.h \
368368
util/ranges.h \
369369
util/readwritefile.h \
370+
util/result.h \
370371
util/underlying.h \
371372
util/serfloat.h \
372373
util/settings.h \

src/util/result.h

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright (c) 2022 The Bitcoin Core developers
2+
// Distributed under the MIT software license, see the accompanying
3+
// file COPYING or https://www.opensource.org/licenses/mit-license.php.
4+
5+
#ifndef BITCOIN_UTIL_RESULT_H
6+
#define BITCOIN_UTIL_RESULT_H
7+
8+
#include <util/translation.h>
9+
#include <variant>
10+
11+
/*
12+
* 'BResult' is a generic class useful for wrapping a return object
13+
* (in case of success) or propagating the error cause.
14+
*/
15+
template<class T>
16+
class BResult {
17+
private:
18+
std::variant<bilingual_str, T> m_variant;
19+
20+
public:
21+
BResult() : m_variant(Untranslated("")) {}
22+
BResult(const T& _obj) : m_variant(_obj) {}
23+
BResult(const bilingual_str& error) : m_variant(error) {}
24+
25+
/* Whether the function succeeded or not */
26+
bool HasRes() const { return std::holds_alternative<T>(m_variant); }
27+
28+
/* In case of success, the result object */
29+
const T& GetObj() const {
30+
assert(HasRes());
31+
return std::get<T>(m_variant);
32+
}
33+
34+
/* In case of failure, the error cause */
35+
const bilingual_str& GetError() const {
36+
assert(!HasRes());
37+
return std::get<bilingual_str>(m_variant);
38+
}
39+
40+
explicit operator bool() const { return HasRes(); }
41+
};
42+
43+
#endif // BITCOIN_UTIL_RESULT_H

0 commit comments

Comments
 (0)