Bug 1687263: part 2) Add `NodeOffsetRange::operator==(const nsRange& aRange)`. r...
[gecko.git] / mfbt / Result.h
bloba3c8ac980bdd60d9092426e719c1e6c083d30e71
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/. */
7 /* A type suitable for returning either a value or an error from a function. */
9 #ifndef mozilla_Result_h
10 #define mozilla_Result_h
12 #include <algorithm>
13 #include <cstdint>
14 #include <cstring>
15 #include <type_traits>
16 #include "mozilla/Assertions.h"
17 #include "mozilla/Attributes.h"
18 #include "mozilla/CompactPair.h"
19 #include "mozilla/MaybeStorageBase.h"
21 namespace mozilla {
23 /**
24 * Empty struct, indicating success for operations that have no return value.
25 * For example, if you declare another empty struct `struct OutOfMemory {};`,
26 * then `Result<Ok, OutOfMemory>` represents either success or OOM.
28 struct Ok {};
30 /**
31 * A tag used to differentiate between GenericErrorResult created by the Err
32 * function (completely new error) and GenericErrorResult created by the
33 * Result::propagateErr function (propagated error). This can be used to track
34 * error propagation and eventually produce error stacks for logging/debugging
35 * purposes.
37 struct ErrorPropagationTag {};
39 template <typename E>
40 class GenericErrorResult;
41 template <typename V, typename E>
42 class Result;
44 namespace detail {
46 enum class PackingStrategy {
47 Variant,
48 NullIsOk,
49 LowBitTagIsError,
50 PackedVariant,
53 template <typename T>
54 struct UnusedZero;
56 template <typename V, typename E, PackingStrategy Strategy>
57 class ResultImplementation;
59 template <typename V>
60 struct EmptyWrapper : V {
61 constexpr EmptyWrapper() = default;
62 explicit constexpr EmptyWrapper(const V&) {}
63 explicit constexpr EmptyWrapper(std::in_place_t) {}
65 constexpr V* addr() { return this; }
66 constexpr const V* addr() const { return this; }
69 // The purpose of AlignedStorageOrEmpty is to make an empty class look like
70 // std::aligned_storage_t for the purposes of the PackingStrategy::NullIsOk
71 // specializations of ResultImplementation below. We can't use
72 // std::aligned_storage_t itself with an empty class, since it would no longer
73 // be empty.
74 template <typename V>
75 using AlignedStorageOrEmpty =
76 std::conditional_t<std::is_empty_v<V>, EmptyWrapper<V>,
77 MaybeStorageBase<V>>;
79 template <typename V, typename E>
80 class ResultImplementationNullIsOkBase {
81 protected:
82 using ErrorStorageType = typename UnusedZero<E>::StorageType;
84 static constexpr auto kNullValue = UnusedZero<E>::nullValue;
86 static_assert(std::is_trivially_copyable_v<ErrorStorageType>);
88 // XXX This can't be statically asserted in general, if ErrorStorageType is
89 // not a basic type. With C++20 bit_cast, we could probably re-add such as
90 // assertion. static_assert(kNullValue == decltype(kNullValue)(0));
92 CompactPair<AlignedStorageOrEmpty<V>, ErrorStorageType> mValue;
94 public:
95 explicit constexpr ResultImplementationNullIsOkBase(const V& aSuccessValue)
96 : mValue(aSuccessValue, kNullValue) {}
97 explicit constexpr ResultImplementationNullIsOkBase(V&& aSuccessValue)
98 : mValue(std::move(aSuccessValue), kNullValue) {}
99 template <typename... Args>
100 explicit constexpr ResultImplementationNullIsOkBase(std::in_place_t,
101 Args&&... aArgs)
102 : mValue(std::piecewise_construct,
103 std::tuple(std::in_place, std::forward<Args>(aArgs)...),
104 std::tuple(kNullValue)) {}
105 explicit constexpr ResultImplementationNullIsOkBase(E aErrorValue)
106 : mValue(std::piecewise_construct, std::tuple<>(),
107 std::tuple(UnusedZero<E>::Store(std::move(aErrorValue)))) {
108 MOZ_ASSERT(mValue.second() != kNullValue);
111 constexpr ResultImplementationNullIsOkBase(
112 ResultImplementationNullIsOkBase&& aOther)
113 : mValue(std::piecewise_construct, std::tuple<>(),
114 std::tuple(aOther.mValue.second())) {
115 if constexpr (!std::is_empty_v<V>) {
116 if (isOk()) {
117 new (mValue.first().addr()) V(std::move(*aOther.mValue.first().addr()));
121 ResultImplementationNullIsOkBase& operator=(
122 ResultImplementationNullIsOkBase&& aOther) {
123 if constexpr (!std::is_empty_v<V>) {
124 if (isOk()) {
125 mValue.first().addr()->~V();
128 mValue.second() = std::move(aOther.mValue.second());
129 if constexpr (!std::is_empty_v<V>) {
130 if (isOk()) {
131 new (mValue.first().addr()) V(std::move(*aOther.mValue.first().addr()));
134 return *this;
137 constexpr bool isOk() const { return mValue.second() == kNullValue; }
139 constexpr const V& inspect() const { return *mValue.first().addr(); }
140 constexpr V unwrap() { return std::move(*mValue.first().addr()); }
142 constexpr decltype(auto) inspectErr() const {
143 return UnusedZero<E>::Inspect(mValue.second());
145 constexpr E unwrapErr() { return UnusedZero<E>::Unwrap(mValue.second()); }
148 template <typename V, typename E,
149 bool IsVTriviallyDestructible = std::is_trivially_destructible_v<V>>
150 class ResultImplementationNullIsOk;
152 template <typename V, typename E>
153 class ResultImplementationNullIsOk<V, E, true>
154 : public ResultImplementationNullIsOkBase<V, E> {
155 public:
156 using ResultImplementationNullIsOkBase<V,
157 E>::ResultImplementationNullIsOkBase;
160 template <typename V, typename E>
161 class ResultImplementationNullIsOk<V, E, false>
162 : public ResultImplementationNullIsOkBase<V, E> {
163 public:
164 using ResultImplementationNullIsOkBase<V,
165 E>::ResultImplementationNullIsOkBase;
167 ResultImplementationNullIsOk(ResultImplementationNullIsOk&&) = default;
168 ResultImplementationNullIsOk& operator=(ResultImplementationNullIsOk&&) =
169 default;
171 ~ResultImplementationNullIsOk() {
172 if (this->isOk()) {
173 this->mValue.first().addr()->~V();
179 * Specialization for when the success type is default-constructible and the
180 * error type is a value type which can never have the value 0 (as determined by
181 * UnusedZero<>).
183 template <typename V, typename E>
184 class ResultImplementation<V, E, PackingStrategy::NullIsOk>
185 : public ResultImplementationNullIsOk<V, E> {
186 public:
187 using ResultImplementationNullIsOk<V, E>::ResultImplementationNullIsOk;
190 template <size_t S>
191 using UnsignedIntType = std::conditional_t<
192 S == 1, std::uint8_t,
193 std::conditional_t<
194 S == 2, std::uint16_t,
195 std::conditional_t<S == 3 || S == 4, std::uint32_t,
196 std::conditional_t<S <= 8, std::uint64_t, void>>>>;
199 * Specialization for when alignment permits using the least significant bit
200 * as a tag bit.
202 template <typename V, typename E>
203 class ResultImplementation<V, E, PackingStrategy::LowBitTagIsError> {
204 static_assert(std::is_trivially_copyable_v<V> &&
205 std::is_trivially_destructible_v<V>);
206 static_assert(std::is_trivially_copyable_v<E> &&
207 std::is_trivially_destructible_v<E>);
209 static constexpr size_t kRequiredSize = std::max(sizeof(V), sizeof(E));
211 using StorageType = UnsignedIntType<kRequiredSize>;
213 #if defined(__clang__)
214 alignas(std::max(alignof(V), alignof(E))) StorageType mBits;
215 #else
216 // Some gcc versions choke on using std::max with alignas, see
217 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94929 (and this seems to have
218 // regressed in some gcc 9.x version before being fixed again) Keeping the
219 // code above since we would eventually drop this when we no longer support
220 // gcc versions with the bug.
221 alignas(alignof(V) > alignof(E) ? alignof(V) : alignof(E)) StorageType mBits;
222 #endif
224 public:
225 explicit constexpr ResultImplementation(V aValue) : mBits(0) {
226 if constexpr (!std::is_empty_v<V>) {
227 std::memcpy(&mBits, &aValue, sizeof(V));
228 MOZ_ASSERT((mBits & 1) == 0);
229 } else {
230 (void)aValue;
233 explicit constexpr ResultImplementation(E aErrorValue) : mBits(1) {
234 if constexpr (!std::is_empty_v<E>) {
235 std::memcpy(&mBits, &aErrorValue, sizeof(E));
236 MOZ_ASSERT((mBits & 1) == 0);
237 mBits |= 1;
238 } else {
239 (void)aErrorValue;
243 constexpr bool isOk() const { return (mBits & 1) == 0; }
245 constexpr V inspect() const {
246 V res;
247 std::memcpy(&res, &mBits, sizeof(V));
248 return res;
250 constexpr V unwrap() { return inspect(); }
252 constexpr E inspectErr() const {
253 const auto bits = mBits ^ 1;
254 E res;
255 std::memcpy(&res, &bits, sizeof(E));
256 return res;
258 constexpr E unwrapErr() { return inspectErr(); }
261 // Return true if any of the struct can fit in a word.
262 template <typename V, typename E>
263 struct IsPackableVariant {
264 struct VEbool {
265 V v;
266 E e;
267 bool ok;
269 struct EVbool {
270 E e;
271 V v;
272 bool ok;
275 using Impl =
276 std::conditional_t<sizeof(VEbool) <= sizeof(EVbool), VEbool, EVbool>;
278 static const bool value = sizeof(Impl) <= sizeof(uintptr_t);
282 * Specialization for when both type are not using all the bytes, in order to
283 * use one byte as a tag.
285 template <typename V, typename E>
286 class ResultImplementation<V, E, PackingStrategy::PackedVariant> {
287 using Impl = typename IsPackableVariant<V, E>::Impl;
288 Impl data;
290 public:
291 explicit constexpr ResultImplementation(V aValue) {
292 data.v = std::move(aValue);
293 data.ok = true;
295 explicit constexpr ResultImplementation(E aErrorValue) {
296 data.e = std::move(aErrorValue);
297 data.ok = false;
300 constexpr bool isOk() const { return data.ok; }
302 constexpr const V& inspect() const { return data.v; }
303 constexpr V unwrap() { return std::move(data.v); }
305 constexpr const E& inspectErr() const { return data.e; }
306 constexpr E unwrapErr() { return std::move(data.e); }
309 // To use nullptr as a special value, we need the counter part to exclude zero
310 // from its range of valid representations.
312 // By default assume that zero can be represented.
313 template <typename T>
314 struct UnusedZero {
315 static const bool value = false;
318 // This template can be used as a helper for specializing UnusedZero for scoped
319 // enum types which never use 0 as an error value, e.g.
321 // namespace mozilla::detail {
323 // template <>
324 // struct UnusedZero<MyEnumType> : UnusedZeroEnum<MyEnumType> {};
326 // } // namespace mozilla::detail
328 template <typename T>
329 struct UnusedZeroEnum {
330 using StorageType = std::underlying_type_t<T>;
332 static constexpr bool value = true;
333 static constexpr StorageType nullValue = 0;
335 static constexpr T Inspect(const StorageType& aValue) {
336 return static_cast<T>(aValue);
338 static constexpr T Unwrap(StorageType aValue) {
339 return static_cast<T>(aValue);
341 static constexpr StorageType Store(T aValue) {
342 return static_cast<StorageType>(aValue);
346 // A bit of help figuring out which of the above specializations to use.
348 // We begin by safely assuming types don't have a spare bit, unless they are
349 // empty.
350 template <typename T>
351 struct HasFreeLSB {
352 static const bool value = std::is_empty_v<T>;
355 // As an incomplete type, void* does not have a spare bit.
356 template <>
357 struct HasFreeLSB<void*> {
358 static const bool value = false;
361 // The lowest bit of a properly-aligned pointer is always zero if the pointee
362 // type is greater than byte-aligned. That bit is free to use if it's masked
363 // out of such pointers before they're dereferenced.
364 template <typename T>
365 struct HasFreeLSB<T*> {
366 static const bool value = (alignof(T) & 1) == 0;
369 // Select one of the previous result implementation based on the properties of
370 // the V and E types.
371 template <typename V, typename E>
372 struct SelectResultImpl {
373 static const PackingStrategy value =
374 (HasFreeLSB<V>::value && HasFreeLSB<E>::value)
375 ? PackingStrategy::LowBitTagIsError
376 : (UnusedZero<E>::value && sizeof(E) <= sizeof(uintptr_t))
377 ? PackingStrategy::NullIsOk
378 : (std::is_default_constructible_v<V> &&
379 std::is_default_constructible_v<E> && IsPackableVariant<V, E>::value)
380 ? PackingStrategy::PackedVariant
381 : PackingStrategy::Variant;
383 using Type = ResultImplementation<V, E, value>;
386 template <typename T>
387 struct IsResult : std::false_type {};
389 template <typename V, typename E>
390 struct IsResult<Result<V, E>> : std::true_type {};
392 } // namespace detail
394 template <typename V, typename E>
395 constexpr auto ToResult(Result<V, E>&& aValue)
396 -> decltype(std::forward<Result<V, E>>(aValue)) {
397 return std::forward<Result<V, E>>(aValue);
401 * Result<V, E> represents the outcome of an operation that can either succeed
402 * or fail. It contains either a success value of type V or an error value of
403 * type E.
405 * All Result methods are const, so results are basically immutable.
406 * This is just like Variant<V, E> but with a slightly different API, and the
407 * following cases are optimized so Result can be stored more efficiently:
409 * - If both the success and error types do not use their least significant bit,
410 * are trivially copyable and destructible, Result<V, E> is guaranteed to be as
411 * large as the larger type. This is determined via the HasFreeLSB trait. By
412 * default, empty classes (in particular Ok) and aligned pointer types are
413 * assumed to have a free LSB, but you can specialize this trait for other
414 * types. If the success type is empty, the representation is guaranteed to be
415 * all zero bits on success. Do not change this representation! There is JIT
416 * code that depends on it. (Implementation note: The lowest bit is used as a
417 * tag bit: 0 to indicate the Result's bits are a success value, 1 to indicate
418 * the Result's bits (with the 1 masked out) encode an error value)
420 * - Else, if the error type can't have a all-zero bits representation and is
421 * not larger than a pointer, a CompactPair is used to represent this rather
422 * than a Variant. This has shown to be better optimizable, and the template
423 * code is much simpler than that of Variant, so it should also compile faster.
424 * Whether an error type can't be all-zero bits, is determined via the
425 * UnusedZero trait. MFBT doesn't declare any public type UnusedZero, but
426 * nsresult is declared UnusedZero in XPCOM.
428 * The purpose of Result is to reduce the screwups caused by using `false` or
429 * `nullptr` to indicate errors.
430 * What screwups? See <https://bugzilla.mozilla.org/show_bug.cgi?id=912928> for
431 * a partial list.
433 * Result<const V, E> or Result<V, const E> are not meaningful. The success or
434 * error values in a Result instance are non-modifiable in-place anyway. This
435 * guarantee must also be maintained when evolving Result. They can be
436 * unwrap()ped, but this loses const qualification. However, Result<const V, E>
437 * or Result<V, const E> may be misleading and prevent movability. Just use
438 * Result<V, E>. (Result<const V*, E> may make sense though, just Result<const
439 * V* const, E> is not possible.)
441 template <typename V, typename E>
442 class MOZ_MUST_USE_TYPE Result final {
443 // See class comment on Result<const V, E> and Result<V, const E>.
444 static_assert(!std::is_const_v<V>);
445 static_assert(!std::is_const_v<E>);
446 static_assert(!std::is_reference_v<V>);
447 static_assert(!std::is_reference_v<E>);
449 using Impl = typename detail::SelectResultImpl<V, E>::Type;
451 Impl mImpl;
453 public:
454 using ok_type = V;
455 using err_type = E;
457 /** Create a success result. */
458 MOZ_IMPLICIT constexpr Result(V&& aValue) : mImpl(std::forward<V>(aValue)) {
459 MOZ_ASSERT(isOk());
462 /** Create a success result. */
463 MOZ_IMPLICIT constexpr Result(const V& aValue) : mImpl(aValue) {
464 MOZ_ASSERT(isOk());
467 /** Create a success result in-place. */
468 template <typename... Args>
469 explicit constexpr Result(std::in_place_t, Args&&... aArgs)
470 : mImpl(std::in_place, std::forward<Args>(aArgs)...) {
471 MOZ_ASSERT(isOk());
474 /** Create an error result. */
475 explicit constexpr Result(E aErrorValue) : mImpl(std::move(aErrorValue)) {
476 MOZ_ASSERT(isErr());
480 * Create a (success/error) result from another (success/error) result with a
481 * different but convertible error type. */
482 template <typename E2,
483 typename = std::enable_if_t<std::is_convertible_v<E2, E>>>
484 MOZ_IMPLICIT constexpr Result(Result<V, E2>&& aOther)
485 : mImpl(aOther.isOk() ? Impl{aOther.unwrap()}
486 : Impl{aOther.unwrapErr()}) {}
489 * Implementation detail of MOZ_TRY().
490 * Create an error result from another error result.
492 template <typename E2>
493 MOZ_IMPLICIT constexpr Result(GenericErrorResult<E2>&& aErrorResult)
494 : mImpl(std::move(aErrorResult.mErrorValue)) {
495 static_assert(std::is_convertible_v<E2, E>, "E2 must be convertible to E");
496 MOZ_ASSERT(isErr());
500 * Implementation detail of MOZ_TRY().
501 * Create an error result from another error result.
503 template <typename E2>
504 MOZ_IMPLICIT constexpr Result(const GenericErrorResult<E2>& aErrorResult)
505 : mImpl(aErrorResult.mErrorValue) {
506 static_assert(std::is_convertible_v<E2, E>, "E2 must be convertible to E");
507 MOZ_ASSERT(isErr());
510 Result(const Result&) = delete;
511 Result(Result&&) = default;
512 Result& operator=(const Result&) = delete;
513 Result& operator=(Result&&) = default;
515 /** True if this Result is a success result. */
516 constexpr bool isOk() const { return mImpl.isOk(); }
518 /** True if this Result is an error result. */
519 constexpr bool isErr() const { return !mImpl.isOk(); }
521 /** Take the success value from this Result, which must be a success result.
523 constexpr V unwrap() {
524 MOZ_ASSERT(isOk());
525 return mImpl.unwrap();
529 * Take the success value from this Result, which must be a success result.
530 * If it is an error result, then return the aValue.
532 constexpr V unwrapOr(V aValue) {
533 return MOZ_LIKELY(isOk()) ? mImpl.unwrap() : std::move(aValue);
536 /** Take the error value from this Result, which must be an error result. */
537 constexpr E unwrapErr() {
538 MOZ_ASSERT(isErr());
539 return mImpl.unwrapErr();
542 /** See the success value from this Result, which must be a success result. */
543 constexpr decltype(auto) inspect() const {
544 static_assert(!std::is_reference_v<
545 std::invoke_result_t<decltype(&Impl::inspect), Impl>> ||
546 std::is_const_v<std::remove_reference_t<
547 std::invoke_result_t<decltype(&Impl::inspect), Impl>>>);
548 MOZ_ASSERT(isOk());
549 return mImpl.inspect();
552 /** See the error value from this Result, which must be an error result. */
553 constexpr decltype(auto) inspectErr() const {
554 static_assert(
555 !std::is_reference_v<
556 std::invoke_result_t<decltype(&Impl::inspectErr), Impl>> ||
557 std::is_const_v<std::remove_reference_t<
558 std::invoke_result_t<decltype(&Impl::inspectErr), Impl>>>);
559 MOZ_ASSERT(isErr());
560 return mImpl.inspectErr();
563 /** Propagate the error value from this Result, which must be an error result.
565 * This can be used to propagate an error from a function call to the caller
566 * with a different value type, but the same error type:
568 * Result<T1, E> Func1() {
569 * Result<T2, E> res = Func2();
570 * if (res.isErr()) { return res.propagateErr(); }
573 constexpr GenericErrorResult<E> propagateErr() {
574 MOZ_ASSERT(isErr());
575 return GenericErrorResult<E>{mImpl.unwrapErr(), ErrorPropagationTag{}};
579 * Map a function V -> V2 over this result's success variant. If this result
580 * is an error, do not invoke the function and propagate the error.
582 * Mapping over success values invokes the function to produce a new success
583 * value:
585 * // Map Result<int, E> to another Result<int, E>
586 * Result<int, E> res(5);
587 * Result<int, E> res2 = res.map([](int x) { return x * x; });
588 * MOZ_ASSERT(res.isOk());
589 * MOZ_ASSERT(res2.unwrap() == 25);
591 * // Map Result<const char*, E> to Result<size_t, E>
592 * Result<const char*, E> res("hello, map!");
593 * Result<size_t, E> res2 = res.map(strlen);
594 * MOZ_ASSERT(res.isOk());
595 * MOZ_ASSERT(res2.unwrap() == 11);
597 * Mapping over an error does not invoke the function and propagates the
598 * error:
600 * Result<V, int> res(5);
601 * MOZ_ASSERT(res.isErr());
602 * Result<V2, int> res2 = res.map([](V v) { ... });
603 * MOZ_ASSERT(res2.isErr());
604 * MOZ_ASSERT(res2.unwrapErr() == 5);
606 template <typename F>
607 constexpr auto map(F f) -> Result<std::result_of_t<F(V)>, E> {
608 using RetResult = Result<std::result_of_t<F(V)>, E>;
609 return MOZ_LIKELY(isOk()) ? RetResult(f(unwrap())) : RetResult(unwrapErr());
613 * Map a function E -> E2 over this result's error variant. If this result is
614 * a success, do not invoke the function and move the success over.
616 * Mapping over error values invokes the function to produce a new error
617 * value:
619 * // Map Result<V, int> to another Result<V, int>
620 * Result<V, int> res(5);
621 * Result<V, int> res2 = res.mapErr([](int x) { return x * x; });
622 * MOZ_ASSERT(res2.isErr());
623 * MOZ_ASSERT(res2.unwrapErr() == 25);
625 * // Map Result<V, const char*> to Result<V, size_t>
626 * Result<V, const char*> res("hello, mapErr!");
627 * Result<V, size_t> res2 = res.mapErr(strlen);
628 * MOZ_ASSERT(res2.isErr());
629 * MOZ_ASSERT(res2.unwrapErr() == 14);
631 * Mapping over a success does not invoke the function and moves the success:
633 * Result<int, E> res(5);
634 * MOZ_ASSERT(res.isOk());
635 * Result<int, E2> res2 = res.mapErr([](E e) { ... });
636 * MOZ_ASSERT(res2.isOk());
637 * MOZ_ASSERT(res2.unwrap() == 5);
639 template <typename F>
640 constexpr auto mapErr(F f) {
641 using RetResult = Result<V, std::result_of_t<F(E)>>;
642 return MOZ_UNLIKELY(isErr()) ? RetResult(f(unwrapErr()))
643 : RetResult(unwrap());
647 * Map a function E -> Result<V, E2> over this result's error variant. If
648 * this result is a success, do not invoke the function and move the success
649 * over.
651 * `orElse`ing over error values invokes the function to produce a new
652 * result:
654 * // `orElse` Result<V, int> error variant to another Result<V, int>
655 * // error variant or Result<V, int> success variant
656 * auto orElse = [](int x) -> Result<V, int> {
657 * if (x != 6) {
658 * return Err(x * x);
660 * return V(...);
661 * };
663 * Result<V, int> res(5);
664 * auto res2 = res.orElse(orElse);
665 * MOZ_ASSERT(res2.isErr());
666 * MOZ_ASSERT(res2.unwrapErr() == 25);
668 * Result<V, int> res3(6);
669 * auto res4 = res3.orElse(orElse);
670 * MOZ_ASSERT(res4.isOk());
671 * MOZ_ASSERT(res4.unwrap() == ...);
673 * // `orElse` Result<V, const char*> error variant to Result<V, size_t>
674 * // error variant or Result<V, size_t> success variant
675 * auto orElse = [](const char* s) -> Result<V, size_t> {
676 * if (strcmp(s, "foo")) {
677 * return Err(strlen(s));
679 * return V(...);
680 * };
682 * Result<V, const char*> res("hello, orElse!");
683 * auto res2 = res.orElse(orElse);
684 * MOZ_ASSERT(res2.isErr());
685 * MOZ_ASSERT(res2.unwrapErr() == 14);
687 * Result<V, const char*> res3("foo");
688 * auto res4 = ress.orElse(orElse);
689 * MOZ_ASSERT(res4.isOk());
690 * MOZ_ASSERT(res4.unwrap() == ...);
692 * `orElse`ing over a success does not invoke the function and moves the
693 * success:
695 * Result<int, E> res(5);
696 * MOZ_ASSERT(res.isOk());
697 * Result<int, E2> res2 = res.orElse([](E e) { ... });
698 * MOZ_ASSERT(res2.isOk());
699 * MOZ_ASSERT(res2.unwrap() == 5);
701 template <typename F>
702 auto orElse(F f) -> Result<V, typename std::result_of_t<F(E)>::err_type> {
703 return MOZ_UNLIKELY(isErr()) ? f(unwrapErr()) : unwrap();
707 * Given a function V -> Result<V2, E>, apply it to this result's success
708 * value and return its result. If this result is an error value, it is
709 * propagated.
711 * This is sometimes called "flatMap" or ">>=" in other contexts.
713 * `andThen`ing over success values invokes the function to produce a new
714 * result:
716 * Result<const char*, Error> res("hello, andThen!");
717 * Result<HtmlFreeString, Error> res2 = res.andThen([](const char* s) {
718 * return containsHtmlTag(s)
719 * ? Result<HtmlFreeString, Error>(Error("Invalid: contains HTML"))
720 * : Result<HtmlFreeString, Error>(HtmlFreeString(s));
722 * });
723 * MOZ_ASSERT(res2.isOk());
724 * MOZ_ASSERT(res2.unwrap() == HtmlFreeString("hello, andThen!");
726 * `andThen`ing over error results does not invoke the function, and just
727 * propagates the error result:
729 * Result<int, const char*> res("some error");
730 * auto res2 = res.andThen([](int x) { ... });
731 * MOZ_ASSERT(res2.isErr());
732 * MOZ_ASSERT(res.unwrapErr() == res2.unwrapErr());
734 template <typename F, typename = std::enable_if_t<detail::IsResult<
735 std::invoke_result_t<F, V&&>>::value>>
736 constexpr auto andThen(F f) -> std::invoke_result_t<F, V&&> {
737 return MOZ_LIKELY(isOk()) ? f(unwrap()) : propagateErr();
742 * A type that auto-converts to an error Result. This is like a Result without
743 * a success type. It's the best return type for functions that always return
744 * an error--functions designed to build and populate error objects. It's also
745 * useful in error-handling macros; see MOZ_TRY for an example.
747 template <typename E>
748 class MOZ_MUST_USE_TYPE GenericErrorResult {
749 E mErrorValue;
751 template <typename V, typename E2>
752 friend class Result;
754 public:
755 explicit constexpr GenericErrorResult(const E& aErrorValue)
756 : mErrorValue(aErrorValue) {}
758 explicit constexpr GenericErrorResult(E&& aErrorValue)
759 : mErrorValue(std::move(aErrorValue)) {}
761 constexpr GenericErrorResult(const E& aErrorValue, const ErrorPropagationTag&)
762 : GenericErrorResult(aErrorValue) {}
764 constexpr GenericErrorResult(E&& aErrorValue, const ErrorPropagationTag&)
765 : GenericErrorResult(std::move(aErrorValue)) {}
768 template <typename E>
769 inline constexpr auto Err(E&& aErrorValue) {
770 return GenericErrorResult<std::decay_t<E>>(std::forward<E>(aErrorValue));
773 } // namespace mozilla
776 * MOZ_TRY(expr) is the C++ equivalent of Rust's `try!(expr);`. First, it
777 * evaluates expr, which must produce a Result value. On success, it
778 * discards the result altogether. On error, it immediately returns an error
779 * Result from the enclosing function.
781 #define MOZ_TRY(expr) \
782 do { \
783 auto mozTryTempResult_ = ::mozilla::ToResult(expr); \
784 if (MOZ_UNLIKELY(mozTryTempResult_.isErr())) { \
785 return mozTryTempResult_.propagateErr(); \
787 } while (0)
790 * MOZ_TRY_VAR(target, expr) is the C++ equivalent of Rust's `target =
791 * try!(expr);`. First, it evaluates expr, which must produce a Result value. On
792 * success, the result's success value is assigned to target. On error,
793 * immediately returns the error result. |target| must be an lvalue.
795 #define MOZ_TRY_VAR(target, expr) \
796 do { \
797 auto mozTryVarTempResult_ = (expr); \
798 if (MOZ_UNLIKELY(mozTryVarTempResult_.isErr())) { \
799 return mozTryVarTempResult_.propagateErr(); \
801 (target) = mozTryVarTempResult_.unwrap(); \
802 } while (0)
804 #endif // mozilla_Result_h