1 // Copyright 2020 The Pigweed Authors
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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
18 #include "pw_assert/assert.h"
19 #include "pw_status/status.h"
23 // A Result represents the result of an operation which can fail. It is a
24 // convenient wrapper around returning a Status alongside some data when the
29 constexpr Result(T&& value) : value_(std::move(value)), status_(OkStatus()) {}
30 constexpr Result(const T& value) : value_(value), status_(OkStatus()) {}
32 template <typename... Args>
33 constexpr Result(std::in_place_t, Args&&... args)
34 : value_(std::forward<Args>(args)...), status_(OkStatus()) {}
36 // TODO(pwbug/246): This can be constexpr when tokenized asserts are fixed.
37 Result(Status status) : status_(status) { PW_CHECK(status_ != OkStatus()); }
38 // TODO(pwbug/246): This can be constexpr when tokenized asserts are fixed.
39 Result(Status::Code code) : status_(code) { PW_CHECK(status_ != OkStatus()); }
41 constexpr Result(const Result&) = default;
42 constexpr Result& operator=(const Result&) = default;
44 constexpr Result(Result&&) = default;
45 constexpr Result& operator=(Result&&) = default;
47 constexpr Status status() const { return status_; }
48 constexpr bool ok() const { return status_.ok(); }
50 // TODO(pwbug/246): This can be constexpr when tokenized asserts are fixed.
56 // TODO(pwbug/246): This can be constexpr when tokenized asserts are fixed.
57 const T& value() const& {
62 // TODO(pwbug/246): This can be constexpr when tokenized asserts are fixed.
65 return std::move(value_);
69 constexpr T value_or(U&& default_value) const& {
73 return std::forward<U>(default_value);
77 constexpr T value_or(U&& default_value) && {
79 return std::move(value_);
81 return std::forward<U>(default_value);