1 // Copyright 2020 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 #pragma once
15
16 #include "pw_status/status.h"
17 #include "pw_status/status_with_size.h"
18
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)
22
23 #define _PW_TRY(result, expr) \
24 do { \
25 if (auto result = (expr); !result.ok()) { \
26 return ::pw::internal::ConvertToStatus(result); \
27 } \
28 } while (0)
29
30 #define PW_TRY_ASSIGN(assignment_lhs, expression) \
31 _PW_TRY_ASSIGN(_PW_TRY_UNIQUE(__LINE__), assignment_lhs, expression)
32
33 #define _PW_TRY_ASSIGN(result, lhs, expr) \
34 auto result = (expr); \
35 if (!result.ok()) { \
36 return ::pw::internal::ConvertToStatus(result); \
37 } \
38 lhs = std::move(result.size())
39
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)
43
44 #define _PW_TRY_WITH_SIZE(result, expr) \
45 do { \
46 if (auto result = (expr); !result.ok()) { \
47 return ::pw::internal::ConvertToStatusWithSize(result); \
48 } \
49 } while (0)
50
51 #define _PW_TRY_UNIQUE(line) _PW_TRY_UNIQUE_EXPANDED(line)
52 #define _PW_TRY_UNIQUE_EXPANDED(line) _pw_try_unique_name_##line
53
54 namespace pw::internal {
55
ConvertToStatus(Status status)56 constexpr Status ConvertToStatus(Status status) { return status; }
57
ConvertToStatus(StatusWithSize status_with_size)58 constexpr Status ConvertToStatus(StatusWithSize status_with_size) {
59 return status_with_size.status();
60 }
61
ConvertToStatusWithSize(Status status)62 constexpr StatusWithSize ConvertToStatusWithSize(Status status) {
63 return StatusWithSize(status, 0);
64 }
65
ConvertToStatusWithSize(StatusWithSize status_with_size)66 constexpr StatusWithSize ConvertToStatusWithSize(
67 StatusWithSize status_with_size) {
68 return status_with_size;
69 }
70
71 } // namespace pw::internal
72