aboutsummaryrefslogtreecommitdiff
path: root/src/util/result.h
blob: 2f586a4c9b1952c81ab44d8a6254c11eaf6f0930 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright (c) 2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_UTIL_RESULT_H
#define BITCOIN_UTIL_RESULT_H

#include <util/translation.h>

#include <variant>

/*
 * 'BResult' is a generic class useful for wrapping a return object
 * (in case of success) or propagating the error cause.
*/
template<class T>
class BResult {
private:
    std::variant<bilingual_str, T> m_variant;

public:
    BResult() : m_variant{Untranslated("")} {}
    BResult(T obj) : m_variant{std::move(obj)} {}
    BResult(bilingual_str error) : m_variant{std::move(error)} {}

    /* Whether the function succeeded or not */
    bool HasRes() const { return std::holds_alternative<T>(m_variant); }

    /* In case of success, the result object */
    const T& GetObj() const {
        assert(HasRes());
        return std::get<T>(m_variant);
    }
    T ReleaseObj()
    {
        assert(HasRes());
        return std::move(std::get<T>(m_variant));
    }

    /* In case of failure, the error cause */
    const bilingual_str& GetError() const {
        assert(!HasRes());
        return std::get<bilingual_str>(m_variant);
    }

    explicit operator bool() const { return HasRes(); }
};

#endif // BITCOIN_UTIL_RESULT_H