| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
| 2 |
* vim: set ts=8 sts=2 et sw=2 tw=80: |
| 3 |
* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
/* A type suitable for returning either a value or an error from a function. */ |
| 8 |
|
| 9 |
#ifndef mozilla_ResultVariant_h |
| 10 |
#define mozilla_ResultVariant_h |
| 11 |
|
| 12 |
#include "mozilla/MaybeStorageBase.h" |
| 13 |
#include "mozilla/Result.h" |
| 14 |
#include "mozilla/Variant.h" |
| 15 |
|
| 16 |
namespace mozilla::detail { |
| 17 |
|
| 18 |
template <typename V, typename E> |
| 19 |
class ResultImplementation<V, E, PackingStrategy::Variant> { |
| 20 |
mozilla::Variant<V, E> mStorage; |
| 21 |
|
| 22 |
public: |
| 23 |
static constexpr PackingStrategy Strategy = PackingStrategy::Variant; |
| 24 |
|
| 25 |
ResultImplementation(ResultImplementation&&) = default; |
| 26 |
ResultImplementation(const ResultImplementation&) = delete; |
| 27 |
ResultImplementation& operator=(const ResultImplementation&) = delete; |
| 28 |
ResultImplementation& operator=(ResultImplementation&&) = default; |
| 29 |
|
| 30 |
explicit ResultImplementation(V&& aValue) : mStorage(std::move(aValue)) {} |
| 31 |
explicit ResultImplementation(const V& aValue) : mStorage(aValue) {} |
| 32 |
template <typename... Args> |
| 33 |
explicit ResultImplementation(std::in_place_t, Args&&... aArgs) |
| 34 |
: mStorage(VariantType<V>{}, std::forward<Args>(aArgs)...) {} |
| 35 |
|
| 36 |
explicit ResultImplementation(const E& aErrorValue) : mStorage(aErrorValue) {} |
| 37 |
explicit ResultImplementation(E&& aErrorValue) |
| 38 |
: mStorage(std::move(aErrorValue)) {} |
| 39 |
|
| 40 |
bool isOk() const { return mStorage.template is<V>(); } |
| 41 |
|
| 42 |
// The callers of these functions will assert isOk() has the proper value, so |
| 43 |
// these functions (in all ResultImplementation specializations) don't need |
| 44 |
// to do so. |
| 45 |
V unwrap() { return std::move(mStorage.template as<V>()); } |
| 46 |
const V& inspect() const { return mStorage.template as<V>(); } |
| 47 |
|
| 48 |
E unwrapErr() { return std::move(mStorage.template as<E>()); } |
| 49 |
const E& inspectErr() const { return mStorage.template as<E>(); } |
| 50 |
|
| 51 |
void updateAfterTracing(V&& aValue) { |
| 52 |
mStorage.template emplace<V>(std::move(aValue)); |
| 53 |
} |
| 54 |
void updateErrorAfterTracing(E&& aErrorValue) { |
| 55 |
mStorage.template emplace<E>(std::move(aErrorValue)); |
| 56 |
} |
| 57 |
}; |
| 58 |
|
| 59 |
} // namespace mozilla::detail |
| 60 |
|
| 61 |
#endif // mozilla_ResultVariant_h |