Skip to content

Commit 7a45c33

Browse files
committed
Introduce generic 'Result' class
Useful to encapsulate the function result object (in case of having it) or, in case of failure, the failure reason. This let us clean lot of boilerplate code, as now instead of returning a boolean and having to add a ref arg for the return object and another ref for the error string. We can simply return a 'BResult<Obj>'. Example of what we currently have: ``` bool doSomething(arg1, arg2, arg3, arg4, &result, &error_string) { do something... if (error) { error_string = "something bad happened"; return false; } result = goodResult; return true; } ``` Example of what we will get with this commit: ``` BResult<Obj> doSomething(arg1, arg2, arg3, arg4) { do something... if (error) return {"something happened"}; // good return {goodResult}; } ``` This allows a similar boilerplate cleanup on the function callers side as well. They don't have to add the extra pre-function-call error string and result object declarations to pass the references to the function.
1 parent b9f9ed4 commit 7a45c33

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
@@ -277,6 +277,7 @@ BITCOIN_CORE_H = \
277277
util/overloaded.h \
278278
util/rbf.h \
279279
util/readwritefile.h \
280+
util/result.h \
280281
util/serfloat.h \
281282
util/settings.h \
282283
util/sock.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)