xref: /aosp_15_r20/external/pigweed/pw_result/public/pw_result/result.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2022 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 //
15 // -----------------------------------------------------------------------------
16 // File: result.h
17 // -----------------------------------------------------------------------------
18 //
19 // An `Result<T>` represents a union of an `pw::Status` object and an object of
20 // type `T`. The `Result<T>` will either contain an object of type `T`
21 // (indicating a successful operation), or an error (of type `Status`)
22 // explaining why such a value is not present.
23 //
24 // In general, check the success of an operation returning an `Result<T>` like
25 // you would an `pw::Status` by using the `ok()` member function.
26 //
27 // Example:
28 //
29 //   Result<Foo> result = Calculation();
30 //   if (result.ok()) {
31 //     result->DoSomethingCool();
32 //   } else {
33 //     PW_LOG_ERROR("Calculation failed: %s",  result.status().str());
34 //   }
35 #pragma once
36 
37 #include <exception>
38 #include <functional>
39 #include <initializer_list>
40 #include <new>
41 #include <string>
42 #include <type_traits>
43 #include <utility>
44 
45 #include "pw_preprocessor/compiler.h"
46 #include "pw_result/internal/result_internal.h"
47 #include "pw_status/status.h"
48 
49 namespace pw {
50 
51 // Returned Result objects may not be ignored.
52 template <typename T>
53 class [[nodiscard]] Result;
54 
55 // Result<T>
56 //
57 // The `Result<T>` class template is a union of an `pw::Status` object and an
58 // object of type `T`. The `Result<T>` models an object that is either a usable
59 // object, or an error (of type `Status`) explaining why such an object is not
60 // present. An `Result<T>` is typically the return value of a function which may
61 // fail.
62 //
63 // An `Result<T>` can never hold an "OK" status; instead, the presence of an
64 // object of type `T` indicates success. Instead of checking for a `kOk` value,
65 // use the `Result<T>::ok()` member function. (It is for this reason, and code
66 // readability, that using the `ok()` function is preferred for `Status` as
67 // well.)
68 //
69 // Example:
70 //
71 //   Result<Foo> result = DoBigCalculationThatCouldFail();
72 //   if (result.ok()) {
73 //     result->DoSomethingCool();
74 //   } else {
75 //     PW_LOG_ERROR("Calculation failed: %s", result.status().str());
76 //   }
77 //
78 // Accessing the object held by an `Result<T>` should be performed via
79 // `operator*` or `operator->`, after a call to `ok()` confirms that the
80 // `Result<T>` holds an object of type `T`:
81 //
82 // Example:
83 //
84 //   Result<int> i = GetCount();
85 //   if (i.ok()) {
86 //     updated_total += *i
87 //   }
88 //
89 // NOTE: using `Result<T>::value()` when no valid value is present will trigger
90 // a PW_ASSERT.
91 //
92 // Example:
93 //
94 //   Result<Foo> result = DoBigCalculationThatCouldFail();
95 //   const Foo& foo = result.value();    // Crash/exception if no value present
96 //   foo.DoSomethingCool();
97 //
98 // A `Result<T*>` can be constructed from a null pointer like any other pointer
99 // value, and the result will be that `ok()` returns `true` and `value()`
100 // returns `nullptr`. Checking the value of pointer in an `Result<T>` generally
101 // requires a bit more care, to ensure both that a value is present and that
102 // value is not null:
103 //
104 //  Result<Foo*> result = LookUpTheFoo(arg);
105 //  if (!result.ok()) {
106 //    PW_LOG_ERROR("Unable to look up the Foo: %s", result.status().str());
107 //  } else if (*result == nullptr) {
108 //    PW_LOG_ERROR("Unexpected null pointer");
109 //  } else {
110 //    (*result)->DoSomethingCool();
111 //  }
112 //
113 // Example factory implementation returning Result<T>:
114 //
115 //  Result<Foo> FooFactory::MakeFoo(int arg) {
116 //    if (arg <= 0) {
117 //      return pw::Status::InvalidArgument();
118 //    }
119 //    return Foo(arg);
120 //  }
121 template <typename T>
122 class Result : private internal_result::StatusOrData<T>,
123                private internal_result::CopyCtorBase<T>,
124                private internal_result::MoveCtorBase<T>,
125                private internal_result::CopyAssignBase<T>,
126                private internal_result::MoveAssignBase<T> {
127   template <typename U>
128   friend class Result;
129 
130   using Base = internal_result::StatusOrData<T>;
131 
132  public:
133   // Result<T>::value_type
134   //
135   // This instance data provides a generic `value_type` member for use within
136   // generic programming. This usage is analogous to that of
137   // `optional::value_type` in the case of `std::optional`.
138   typedef T value_type;
139 
140   // Constructors
141 
142   // Constructs a new `Result` with an `pw::Status::Unknown()` status. This
143   // constructor is marked 'explicit' to prevent usages in return values such as
144   // 'return {};', under the misconception that `Result<std::vector<int>>` will
145   // be initialized with an empty vector, instead of a `Status::Unknown()` error
146   // code.
147   explicit constexpr Result();
148 
149   // `Result<T>` is copy constructible if `T` is copy constructible.
150   constexpr Result(const Result&) = default;
151   // `Result<T>` is copy assignable if `T` is copy constructible and copy
152   // assignable.
153   constexpr Result& operator=(const Result&) = default;
154 
155   // `Result<T>` is move constructible if `T` is move constructible.
156   constexpr Result(Result&&) = default;
157   // `Result<T>` is moveAssignable if `T` is move constructible and move
158   // assignable.
159   constexpr Result& operator=(Result&&) = default;
160 
161   // Converting Constructors
162 
163   // Constructs a new `Result<T>` from an `pw::Result<U>`, when `T` is
164   // constructible from `U`. To avoid ambiguity, these constructors are disabled
165   // if `T` is also constructible from `Result<U>.`. This constructor is
166   // explicit if and only if the corresponding construction of `T` from `U` is
167   // explicit. (This constructor inherits its explicitness from the underlying
168   // constructor.)
169   template <
170       typename U,
171       std::enable_if_t<
172           std::conjunction<
173               std::negation<std::is_same<T, U>>,
174               std::is_constructible<T, const U&>,
175               std::is_convertible<const U&, T>,
176               std::negation<internal_result::
177                                 IsConstructibleOrConvertibleFromResult<T, U>>>::
178               value,
179           int> = 0>
Result(const Result<U> & other)180   constexpr Result(const Result<U>& other)  // NOLINT
181       : Base(static_cast<const typename Result<U>::Base&>(other)) {}
182   template <
183       typename U,
184       std::enable_if_t<
185           std::conjunction<
186               std::negation<std::is_same<T, U>>,
187               std::is_constructible<T, const U&>,
188               std::negation<std::is_convertible<const U&, T>>,
189               std::negation<internal_result::
190                                 IsConstructibleOrConvertibleFromResult<T, U>>>::
191               value,
192           int> = 0>
Result(const Result<U> & other)193   explicit constexpr Result(const Result<U>& other)
194       : Base(static_cast<const typename Result<U>::Base&>(other)) {}
195 
196   template <
197       typename U,
198       std::enable_if_t<
199           std::conjunction<
200               std::negation<std::is_same<T, U>>,
201               std::is_constructible<T, U&&>,
202               std::is_convertible<U&&, T>,
203               std::negation<internal_result::
204                                 IsConstructibleOrConvertibleFromResult<T, U>>>::
205               value,
206           int> = 0>
Result(Result<U> && other)207   constexpr Result(Result<U>&& other)  // NOLINT
208       : Base(static_cast<typename Result<U>::Base&&>(other)) {}
209   template <
210       typename U,
211       std::enable_if_t<
212           std::conjunction<
213               std::negation<std::is_same<T, U>>,
214               std::is_constructible<T, U&&>,
215               std::negation<std::is_convertible<U&&, T>>,
216               std::negation<internal_result::
217                                 IsConstructibleOrConvertibleFromResult<T, U>>>::
218               value,
219           int> = 0>
Result(Result<U> && other)220   explicit constexpr Result(Result<U>&& other)
221       : Base(static_cast<typename Result<U>::Base&&>(other)) {}
222 
223   // Converting Assignment Operators
224 
225   // Creates an `Result<T>` through assignment from an
226   // `Result<U>` when:
227   //
228   //   * Both `Result<T>` and `pw::Result<U>` are OK by assigning
229   //     `U` to `T` directly.
230   //   * `Result<T>` is OK and `pw::Result<U>` contains an error
231   //      code by destroying `Result<T>`'s value and assigning from
232   //      `Result<U>'
233   //   * `Result<T>` contains an error code and `pw::Result<U>` is
234   //      OK by directly initializing `T` from `U`.
235   //   * Both `Result<T>` and `pw::Result<U>` contain an error
236   //     code by assigning the `Status` in `Result<U>` to
237   //     `Result<T>`
238   //
239   // These overloads only apply if `Result<T>` is constructible and
240   // assignable from `Result<U>` and `Result<T>` cannot be directly
241   // assigned from `Result<U>`.
242   template <typename U,
243             std::enable_if_t<
244                 std::conjunction<
245                     std::negation<std::is_same<T, U>>,
246                     std::is_constructible<T, const U&>,
247                     std::is_assignable<T, const U&>,
248                     std::negation<
249                         internal_result::
250                             IsConstructibleOrConvertibleOrAssignableFromResult<
251                                 T,
252                                 U>>>::value,
253                 int> = 0>
254   constexpr Result& operator=(const Result<U>& other) {
255     this->Assign(other);
256     return *this;
257   }
258   template <typename U,
259             std::enable_if_t<
260                 std::conjunction<
261                     std::negation<std::is_same<T, U>>,
262                     std::is_constructible<T, U&&>,
263                     std::is_assignable<T, U&&>,
264                     std::negation<
265                         internal_result::
266                             IsConstructibleOrConvertibleOrAssignableFromResult<
267                                 T,
268                                 U>>>::value,
269                 int> = 0>
270   constexpr Result& operator=(Result<U>&& other) {
271     this->Assign(std::move(other));
272     return *this;
273   }
274 
275   // Constructs a new `Result<T>` with a non-ok status. After calling this
276   // constructor, `this->ok()` will be `false` and calls to `value()` will
277   // crash, or produce an exception if exceptions are enabled.
278   //
279   // The constructor also takes any type `U` that is convertible to `Status`.
280   // This constructor is explicit if an only if `U` is not of type `Status` and
281   // the conversion from `U` to `Status` is explicit.
282   //
283   // REQUIRES: !Status(std::forward<U>(v)).ok(). This requirement is DCHECKed.
284   // In optimized builds, passing OkStatus() here will have the effect of
285   // passing Status::Internal() as a fallback.
286   template <
287       typename U = Status,
288       std::enable_if_t<
289           std::conjunction<
290               std::is_convertible<U&&, Status>,
291               std::is_constructible<Status, U&&>,
292               std::negation<std::is_same<std::decay_t<U>, Result<T>>>,
293               std::negation<std::is_same<std::decay_t<U>, T>>,
294               std::negation<std::is_same<std::decay_t<U>, std::in_place_t>>,
295               std::negation<internal_result::
296                                 HasConversionOperatorToResult<T, U&&>>>::value,
297           int> = 0>
Result(U && v)298   constexpr Result(U&& v) : Base(std::forward<U>(v)) {}
299 
300   template <
301       typename U = Status,
302       std::enable_if_t<
303           std::conjunction<
304               std::negation<std::is_convertible<U&&, Status>>,
305               std::is_constructible<Status, U&&>,
306               std::negation<std::is_same<std::decay_t<U>, Result<T>>>,
307               std::negation<std::is_same<std::decay_t<U>, T>>,
308               std::negation<std::is_same<std::decay_t<U>, std::in_place_t>>,
309               std::negation<internal_result::
310                                 HasConversionOperatorToResult<T, U&&>>>::value,
311           int> = 0>
Result(U && v)312   constexpr explicit Result(U&& v) : Base(std::forward<U>(v)) {}
313 
314   template <
315       typename U = Status,
316       std::enable_if_t<
317           std::conjunction<
318               std::is_convertible<U&&, Status>,
319               std::is_constructible<Status, U&&>,
320               std::negation<std::is_same<std::decay_t<U>, Result<T>>>,
321               std::negation<std::is_same<std::decay_t<U>, T>>,
322               std::negation<std::is_same<std::decay_t<U>, std::in_place_t>>,
323               std::negation<internal_result::
324                                 HasConversionOperatorToResult<T, U&&>>>::value,
325           int> = 0>
326   constexpr Result& operator=(U&& v) {
327     this->AssignStatus(std::forward<U>(v));
328     return *this;
329   }
330 
331   // Perfect-forwarding value assignment operator.
332 
333   // If `*this` contains a `T` value before the call, the contained value is
334   // assigned from `std::forward<U>(v)`; Otherwise, it is directly-initialized
335   // from `std::forward<U>(v)`.
336   // This function does not participate in overload unless:
337   // 1. `std::is_constructible_v<T, U>` is true,
338   // 2. `std::is_assignable_v<T&, U>` is true.
339   // 3. `std::is_same_v<Result<T>, std::remove_cvref_t<U>>` is false.
340   // 4. Assigning `U` to `T` is not ambiguous:
341   //  If `U` is `Result<V>` and `T` is constructible and assignable from
342   //  both `Result<V>` and `V`, the assignment is considered bug-prone and
343   //  ambiguous thus will fail to compile. For example:
344   //    Result<bool> s1 = true;  // s1.ok() && *s1 == true
345   //    Result<bool> s2 = false;  // s2.ok() && *s2 == false
346   //    s1 = s2;  // ambiguous, `s1 = *s2` or `s1 = bool(s2)`?
347   template <
348       typename U = T,
349       typename = typename std::enable_if<std::conjunction<
350           std::is_constructible<T, U&&>,
351           std::is_assignable<T&, U&&>,
352           std::disjunction<
353               std::is_same<std::remove_cv_t<std::remove_reference_t<U>>, T>,
354               std::conjunction<
355                   std::negation<std::is_convertible<U&&, Status>>,
356                   std::negation<
357                       internal_result::HasConversionOperatorToResult<T, U&&>>>>,
358           internal_result::IsForwardingAssignmentValid<T, U&&>>::value>::type>
359   constexpr Result& operator=(U&& v) {
360     this->Assign(std::forward<U>(v));
361     return *this;
362   }
363 
364   // Constructs the inner value `T` in-place using the provided args, using the
365   // `T(args...)` constructor.
366   template <typename... Args>
367   explicit constexpr Result(std::in_place_t, Args&&... args);
368   template <typename U, typename... Args>
369   explicit constexpr Result(std::in_place_t,
370                             std::initializer_list<U> ilist,
371                             Args&&... args);
372 
373   // Constructs the inner value `T` in-place using the provided args, using the
374   // `T(U)` (direct-initialization) constructor. This constructor is only valid
375   // if `T` can be constructed from a `U`. Can accept move or copy constructors.
376   //
377   // This constructor is explicit if `U` is not convertible to `T`. To avoid
378   // ambiguity, this constructor is disabled if `U` is a `Result<J>`, where
379   // `J` is convertible to `T`.
380   template <
381       typename U = T,
382       std::enable_if_t<
383           std::conjunction<
384               internal_result::IsDirectInitializationValid<T, U&&>,
385               std::is_constructible<T, U&&>,
386               std::is_convertible<U&&, T>,
387               std::disjunction<
388                   std::is_same<std::remove_cv_t<std::remove_reference_t<U>>, T>,
389                   std::conjunction<
390                       std::negation<std::is_convertible<U&&, Status>>,
391                       std::negation<
392                           internal_result::
393                               HasConversionOperatorToResult<T, U&&>>>>>::value,
394           int> = 0>
Result(U && u)395   constexpr Result(U&& u)  // NOLINT
396       : Result(std::in_place, std::forward<U>(u)) {}
397 
398   template <
399       typename U = T,
400       std::enable_if_t<
401           std::conjunction<
402               internal_result::IsDirectInitializationValid<T, U&&>,
403               std::disjunction<
404                   std::is_same<std::remove_cv_t<std::remove_reference_t<U>>, T>,
405                   std::conjunction<
406                       std::negation<std::is_constructible<Status, U&&>>,
407                       std::negation<
408                           internal_result::
409                               HasConversionOperatorToResult<T, U&&>>>>,
410               std::is_constructible<T, U&&>,
411               std::negation<std::is_convertible<U&&, T>>>::value,
412           int> = 0>
Result(U && u)413   explicit constexpr Result(U&& u)  // NOLINT
414       : Result(std::in_place, std::forward<U>(u)) {}
415 
416   // Result<T>::ok()
417   //
418   // Returns whether or not this `Result<T>` holds a `T` value. This
419   // member function is analagous to `Status::ok()` and should be used
420   // similarly to check the status of return values.
421   //
422   // Example:
423   //
424   // Result<Foo> result = DoBigCalculationThatCouldFail();
425   // if (result.ok()) {
426   //    // Handle result
427   // else {
428   //    // Handle error
429   // }
ok()430   [[nodiscard]] constexpr bool ok() const { return this->status_.ok(); }
431 
432   // Result<T>::status()
433   //
434   // Returns a reference to the current `Status` contained within the
435   // `Result<T>`. If `pw::Result<T>` contains a `T`, then this function returns
436   // `OkStatus()`.
437   constexpr const Status& status() const&;
438   constexpr Status status() &&;
439 
440   // Result<T>::value()
441   //
442   // Returns a reference to the held value if `this->ok()`. Otherwise,
443   // terminates the process.
444   //
445   // If you have already checked the status using `this->ok()`, you probably
446   // want to use `operator*()` or `operator->()` to access the value instead of
447   // `value`.
448   //
449   // Note: for value types that are cheap to copy, prefer simple code:
450   //
451   //   T value = result.value();
452   //
453   // Otherwise, if the value type is expensive to copy, but can be left
454   // in the Result, simply assign to a reference:
455   //
456   //   T& value = result.value();  // or `const T&`
457   //
458   // Otherwise, if the value type supports an efficient move, it can be
459   // used as follows:
460   //
461   //   T value = std::move(result).value();
462   //
463   // The `std::move` on result instead of on the whole expression enables
464   // warnings about possible uses of the result object after the move.
465   constexpr const T& value() const& PW_ATTRIBUTE_LIFETIME_BOUND;
466   constexpr T& value() & PW_ATTRIBUTE_LIFETIME_BOUND;
467   constexpr const T&& value() const&& PW_ATTRIBUTE_LIFETIME_BOUND;
468   constexpr T&& value() && PW_ATTRIBUTE_LIFETIME_BOUND;
469 
470   // Result<T>:: operator*()
471   //
472   // Returns a reference to the current value.
473   //
474   // REQUIRES: `this->ok() == true`, otherwise the behavior is undefined.
475   //
476   // Use `this->ok()` to verify that there is a current value within the
477   // `Result<T>`. Alternatively, see the `value()` member function for a
478   // similar API that guarantees crashing or throwing an exception if there is
479   // no current value.
480   constexpr const T& operator*() const& PW_ATTRIBUTE_LIFETIME_BOUND;
481   constexpr T& operator*() & PW_ATTRIBUTE_LIFETIME_BOUND;
482   constexpr const T&& operator*() const&& PW_ATTRIBUTE_LIFETIME_BOUND;
483   constexpr T&& operator*() && PW_ATTRIBUTE_LIFETIME_BOUND;
484 
485   // Result<T>::operator->()
486   //
487   // Returns a pointer to the current value.
488   //
489   // REQUIRES: `this->ok() == true`, otherwise the behavior is undefined.
490   //
491   // Use `this->ok()` to verify that there is a current value.
492   constexpr const T* operator->() const PW_ATTRIBUTE_LIFETIME_BOUND;
493   constexpr T* operator->() PW_ATTRIBUTE_LIFETIME_BOUND;
494 
495   // Result<T>::value_or()
496   //
497   // Returns the current value if `this->ok() == true`. Otherwise constructs a
498   // value using the provided `default_value`.
499   //
500   // Unlike `value`, this function returns by value, copying the current value
501   // if necessary. If the value type supports an efficient move, it can be used
502   // as follows:
503   //
504   //   T value = std::move(result).value_or(def);
505   //
506   // Unlike with `value`, calling `std::move()` on the result of `value_or` will
507   // still trigger a copy.
508   template <typename U>
509   constexpr T value_or(U&& default_value) const&;
510   template <typename U>
511   constexpr T value_or(U&& default_value) &&;
512 
513   // Result<T>::IgnoreError()
514   //
515   // Ignores any errors. This method does nothing except potentially suppress
516   // complaints from any tools that are checking that errors are not dropped on
517   // the floor.
518   constexpr void IgnoreError() const;
519 
520   // Result<T>::emplace()
521   //
522   // Reconstructs the inner value T in-place using the provided args, using the
523   // T(args...) constructor. Returns reference to the reconstructed `T`.
524   template <typename... Args>
emplace(Args &&...args)525   T& emplace(Args&&... args) {
526     if (ok()) {
527       this->Clear();
528       this->MakeValue(std::forward<Args>(args)...);
529     } else {
530       this->MakeValue(std::forward<Args>(args)...);
531       this->status_ = OkStatus();
532     }
533     return this->data_;
534   }
535 
536   template <
537       typename U,
538       typename... Args,
539       std::enable_if_t<
540           std::is_constructible<T, std::initializer_list<U>&, Args&&...>::value,
541           int> = 0>
emplace(std::initializer_list<U> ilist,Args &&...args)542   T& emplace(std::initializer_list<U> ilist, Args&&... args) {
543     if (ok()) {
544       this->Clear();
545       this->MakeValue(ilist, std::forward<Args>(args)...);
546     } else {
547       this->MakeValue(ilist, std::forward<Args>(args)...);
548       this->status_ = OkStatus();
549     }
550     return this->data_;
551   }
552 
553   // Result<T>::and_then()
554   //
555   // template <typename U>
556   // Result<U> and_then(Function<Result<U>(T)> func);
557   //
558   // Returns the Result from the invocation of the function on the contained
559   // value if it exists. Otherwise, returns the contained status in the Result.
560   //
561   //   Result<Foo> CreateFoo();
562   //   Result<Bar> CreateBarFromFoo(const Foo& foo);
563   //
564   //   Result<Bar> bar = CreateFoo().and_then(CreateBarFromFoo);
565   template <typename Fn,
566             typename Ret = internal_result::InvokeResultType<Fn, T&>,
567             std::enable_if_t<std::is_copy_constructible_v<Ret>, int> = 0>
and_then(Fn && function)568   constexpr Ret and_then(Fn&& function) & {
569     static_assert(internal_result::IsResult<Ret>,
570                   "Fn must return a pw::Result");
571     return ok() ? std::invoke(std::forward<Fn>(function), value())
572                 : Ret(status());
573   }
574 
575   template <typename Fn,
576             typename Ret = internal_result::InvokeResultType<Fn, T&&>,
577             std::enable_if_t<std::is_move_constructible_v<Ret>, int> = 0>
and_then(Fn && function)578   constexpr auto and_then(Fn&& function) && {
579     static_assert(internal_result::IsResult<Ret>,
580                   "Fn must return a pw::Result");
581     return ok() ? std::invoke(std::forward<Fn>(function), std::move(value()))
582                 : Ret(status());
583   }
584 
585   template <typename Fn,
586             typename Ret = internal_result::InvokeResultType<Fn, const T&>,
587             std::enable_if_t<std::is_copy_constructible_v<Ret>, int> = 0>
and_then(Fn && function)588   constexpr auto and_then(Fn&& function) const& {
589     static_assert(internal_result::IsResult<Ret>,
590                   "Fn must return a pw::Result");
591     return ok() ? std::invoke(std::forward<Fn>(function), value())
592                 : Ret(status());
593   }
594 
595   template <typename Fn,
596             typename Ret = internal_result::InvokeResultType<Fn, const T&&>,
597             std::enable_if_t<std::is_move_constructible_v<Ret>, int> = 0>
and_then(Fn && function)598   constexpr auto and_then(Fn&& function) const&& {
599     static_assert(internal_result::IsResult<Ret>,
600                   "Fn must return a pw::Result");
601     return ok() ? std::invoke(std::forward<Fn>(function), std::move(value()))
602                 : Ret(status());
603   }
604 
605   // Result<T>::or_else()
606   //
607   // template <typename U>
608   //   requires std::is_convertible_v<U, Result<T>>
609   // Result<T> or_else(Function<U(Status)> func);
610   //
611   // Result<T> or_else(Function<void(Status)> func);
612   //
613   // Returns a Result if it has a value, otherwise it invokes the given
614   // function. The function must return a type convertible to a Result<T> or a
615   // void.
616   //
617   //   Result<Foo> CreateFoo();
618   //
619   //   Result<Foo> foo = CreateFoo().or_else(
620   //       [](Status s) { PW_LOG_ERROR("Status: %d", s.code()); });
621   template <typename Fn,
622             typename Ret = internal_result::InvokeResultType<Fn, const Status&>,
623             std::enable_if_t<!std::is_void_v<Ret>, int> = 0>
or_else(Fn && function)624   constexpr Result<T> or_else(Fn&& function) const& {
625     static_assert(std::is_convertible_v<Ret, Result<T>>,
626                   "Fn must be convertible to a pw::Result");
627     return ok() ? *this : std::invoke(std::forward<Fn>(function), status());
628   }
629 
630   template <typename Fn,
631             typename Ret = internal_result::InvokeResultType<Fn, const Status&>,
632             std::enable_if_t<std::is_void_v<Ret>, int> = 0>
or_else(Fn && function)633   constexpr Result<T> or_else(Fn&& function) const& {
634     if (ok()) {
635       return *this;
636     }
637     std::invoke(std::forward<Fn>(function), status());
638     return *this;
639   }
640 
641   template <typename Fn,
642             typename Ret = internal_result::InvokeResultType<Fn, Status&&>,
643             std::enable_if_t<!std::is_void_v<Ret>, int> = 0>
or_else(Fn && function)644   constexpr Result<T> or_else(Fn&& function) && {
645     static_assert(std::is_convertible_v<Ret, Result<T>>,
646                   "Fn must be convertible to a pw::Result");
647     return ok() ? std::move(*this)
648                 : std::invoke(std::forward<Fn>(function), std::move(status()));
649   }
650 
651   template <typename Fn,
652             typename Ret = internal_result::InvokeResultType<Fn, Status&&>,
653             std::enable_if_t<std::is_void_v<Ret>, int> = 0>
or_else(Fn && function)654   constexpr Result<T> or_else(Fn&& function) && {
655     if (ok()) {
656       return *this;
657     }
658     std::invoke(std::forward<Fn>(function), status());
659     return std::move(*this);
660   }
661 
662   // Result<T>::transform()
663   //
664   // template <typename U>
665   // Result<U> transform(Function<U(T)> func);
666   //
667   // Returns a Result<U> which contains the result of the invocation of the
668   // given function if *this contains a value. Otherwise, it returns a Result<U>
669   // with the same Status as *this.
670   template <typename Fn,
671             typename Ret = internal_result::InvokeResultType<Fn, T&>,
672             std::enable_if_t<std::is_copy_constructible_v<Ret>, int> = 0>
transform(Fn && function)673   constexpr Result<Ret> transform(Fn&& function) & {
674     if (!ok()) {
675       return status();
676     }
677     return std::invoke(std::forward<Fn>(function), value());
678   }
679 
680   template <typename Fn,
681             typename Ret = internal_result::InvokeResultType<Fn, T&&>,
682             std::enable_if_t<std::is_move_constructible_v<Ret>, int> = 0>
transform(Fn && function)683   constexpr Result<Ret> transform(Fn&& function) && {
684     if (!ok()) {
685       return std::move(status());
686     }
687     return std::invoke(std::forward<Fn>(function), std::move(value()));
688   }
689 
690   template <typename Fn,
691             typename Ret = internal_result::InvokeResultType<Fn, T&>,
692             std::enable_if_t<std::is_copy_constructible_v<Ret>, int> = 0>
transform(Fn && function)693   constexpr Result<Ret> transform(Fn&& function) const& {
694     if (!ok()) {
695       return status();
696     }
697     return std::invoke(std::forward<Fn>(function), value());
698   }
699 
700   template <typename Fn,
701             typename Ret = internal_result::InvokeResultType<Fn, T&&>,
702             std::enable_if_t<std::is_move_constructible_v<Ret>, int> = 0>
transform(Fn && function)703   constexpr Result<Ret> transform(Fn&& function) const&& {
704     if (!ok()) {
705       return std::move(status());
706     }
707     return std::invoke(std::forward<Fn>(function), std::move(value()));
708   }
709 
710  private:
711   using Base::Assign;
712   template <typename U>
713   constexpr void Assign(const Result<U>& other);
714   template <typename U>
715   constexpr void Assign(Result<U>&& other);
716 };
717 
718 // Deduction guide to allow ``Result(v)`` rather than ``Result<T>(v)``.
719 template <typename T>
720 Result(T value) -> Result<T>;
721 
722 // operator==()
723 //
724 // This operator checks the equality of two `Result<T>` objects.
725 template <typename T>
726 constexpr bool operator==(const Result<T>& lhs, const Result<T>& rhs) {
727   if (lhs.ok() && rhs.ok()) {
728     return *lhs == *rhs;
729   }
730   return lhs.status() == rhs.status();
731 }
732 
733 // operator!=()
734 //
735 // This operator checks the inequality of two `Result<T>` objects.
736 template <typename T>
737 constexpr bool operator!=(const Result<T>& lhs, const Result<T>& rhs) {
738   return !(lhs == rhs);
739 }
740 
741 //------------------------------------------------------------------------------
742 // Implementation details for Result<T>
743 //------------------------------------------------------------------------------
744 
745 template <typename T>
Result()746 constexpr Result<T>::Result() : Base(Status::Unknown()) {}
747 
748 template <typename T>
749 template <typename U>
Assign(const Result<U> & other)750 constexpr inline void Result<T>::Assign(const Result<U>& other) {
751   if (other.ok()) {
752     this->Assign(*other);
753   } else {
754     this->AssignStatus(other.status());
755   }
756 }
757 
758 template <typename T>
759 template <typename U>
Assign(Result<U> && other)760 constexpr inline void Result<T>::Assign(Result<U>&& other) {
761   if (other.ok()) {
762     this->Assign(*std::move(other));
763   } else {
764     this->AssignStatus(std::move(other).status());
765   }
766 }
767 template <typename T>
768 template <typename... Args>
Result(std::in_place_t,Args &&...args)769 constexpr Result<T>::Result(std::in_place_t, Args&&... args)
770     : Base(std::in_place, std::forward<Args>(args)...) {}
771 
772 template <typename T>
773 template <typename U, typename... Args>
Result(std::in_place_t,std::initializer_list<U> ilist,Args &&...args)774 constexpr Result<T>::Result(std::in_place_t,
775                             std::initializer_list<U> ilist,
776                             Args&&... args)
777     : Base(std::in_place, ilist, std::forward<Args>(args)...) {}
778 
779 template <typename T>
status()780 constexpr const Status& Result<T>::status() const& {
781   return this->status_;
782 }
783 template <typename T>
status()784 constexpr Status Result<T>::status() && {
785   return ok() ? OkStatus() : std::move(this->status_);
786 }
787 
788 template <typename T>
value()789 constexpr const T& Result<T>::value() const& {
790   PW_ASSERT(this->status_.ok());
791   return this->data_;
792 }
793 
794 template <typename T>
value()795 constexpr T& Result<T>::value() & {
796   PW_ASSERT(this->status_.ok());
797   return this->data_;
798 }
799 
800 template <typename T>
value()801 constexpr const T&& Result<T>::value() const&& {
802   PW_ASSERT(this->status_.ok());
803   return std::move(this->data_);
804 }
805 
806 template <typename T>
value()807 constexpr T&& Result<T>::value() && {
808   PW_ASSERT(this->status_.ok());
809   return std::move(this->data_);
810 }
811 
812 template <typename T>
813 constexpr const T& Result<T>::operator*() const& {
814   PW_ASSERT(this->status_.ok());
815   return this->data_;
816 }
817 
818 template <typename T>
819 constexpr T& Result<T>::operator*() & {
820   PW_ASSERT(this->status_.ok());
821   return this->data_;
822 }
823 
824 template <typename T>
825 constexpr const T&& Result<T>::operator*() const&& {
826   PW_ASSERT(this->status_.ok());
827   return std::move(this->data_);
828 }
829 
830 template <typename T>
831 constexpr T&& Result<T>::operator*() && {
832   PW_ASSERT(this->status_.ok());
833   return std::move(this->data_);
834 }
835 
836 template <typename T>
837 constexpr const T* Result<T>::operator->() const {
838   PW_ASSERT(this->status_.ok());
839   return &this->data_;
840 }
841 
842 template <typename T>
843 constexpr T* Result<T>::operator->() {
844   PW_ASSERT(this->status_.ok());
845   return &this->data_;
846 }
847 
848 template <typename T>
849 template <typename U>
value_or(U && default_value)850 constexpr T Result<T>::value_or(U&& default_value) const& {
851   if (ok()) {
852     return this->data_;
853   }
854   return std::forward<U>(default_value);
855 }
856 
857 template <typename T>
858 template <typename U>
value_or(U && default_value)859 constexpr T Result<T>::value_or(U&& default_value) && {
860   if (ok()) {
861     return std::move(this->data_);
862   }
863   return std::forward<U>(default_value);
864 }
865 
866 template <typename T>
IgnoreError()867 constexpr void Result<T>::IgnoreError() const {
868   // no-op
869 }
870 
871 namespace internal {
872 
873 template <typename T>
ConvertToStatus(const Result<T> & result)874 constexpr Status ConvertToStatus(const Result<T>& result) {
875   return result.status();
876 }
877 
878 template <typename T>
ConvertToValue(Result<T> & result)879 constexpr T&& ConvertToValue(Result<T>& result) {
880   return std::move(result).value();
881 }
882 
883 }  // namespace internal
884 }  // namespace pw
885