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
16 #include "pw_status/status.h"
17 #include "pw_status/status_with_size.h"
19 // Macros for cleanly working with Status or StatusWithSize objects in functions
20 // that return Status.
21 #define PW_TRY(expr) _PW_TRY(_PW_TRY_UNIQUE(__LINE__), expr)
23 #define _PW_TRY(result, expr) \
25 if (auto result = (expr); !result.ok()) { \
26 return ::pw::internal::ConvertToStatus(result); \
30 #define PW_TRY_ASSIGN(assignment_lhs, expression) \
31 _PW_TRY_ASSIGN(_PW_TRY_UNIQUE(__LINE__), assignment_lhs, expression)
33 #define _PW_TRY_ASSIGN(result, lhs, expr) \
34 auto result = (expr); \
36 return ::pw::internal::ConvertToStatus(result); \
38 lhs = std::move(result.size())
40 // Macro for cleanly working with Status or StatusWithSize objects in functions
41 // that return StatusWithSize.
42 #define PW_TRY_WITH_SIZE(expr) _PW_TRY_WITH_SIZE(_PW_TRY_UNIQUE(__LINE__), expr)
44 #define _PW_TRY_WITH_SIZE(result, expr) \
46 if (auto result = (expr); !result.ok()) { \
47 return ::pw::internal::ConvertToStatusWithSize(result); \
51 #define _PW_TRY_UNIQUE(line) _PW_TRY_UNIQUE_EXPANDED(line)
52 #define _PW_TRY_UNIQUE_EXPANDED(line) _pw_try_unique_name_##line
54 namespace pw::internal {
56 constexpr Status ConvertToStatus(Status status) { return status; }
58 constexpr Status ConvertToStatus(StatusWithSize status_with_size) {
59 return status_with_size.status();
62 constexpr StatusWithSize ConvertToStatusWithSize(Status status) {
63 return StatusWithSize(status, 0);
66 constexpr StatusWithSize ConvertToStatusWithSize(
67 StatusWithSize status_with_size) {
68 return status_with_size;
71 } // namespace pw::internal