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 <utility>
17
18 #include "pw_status/status.h"
19 #include "pw_status/status_with_size.h"
20
21 // Macros for cleanly working with Status or StatusWithSize objects in functions
22 // that return Status.
23 #define PW_TRY(expr) _PW_TRY(_PW_TRY_UNIQUE(__LINE__), expr)
24
25 #define _PW_TRY(result, expr) \
26 do { \
27 if (auto result = (expr); !result.ok()) { \
28 return ::pw::internal::ConvertToStatus(result); \
29 } \
30 } while (0)
31
32 #define PW_TRY_ASSIGN(assignment_lhs, expression) \
33 _PW_TRY_ASSIGN(_PW_TRY_UNIQUE(__LINE__), assignment_lhs, expression)
34
35 #define _PW_TRY_ASSIGN(result, lhs, expr) \
36 auto result = (expr); \
37 if (!result.ok()) { \
38 return ::pw::internal::ConvertToStatus(result); \
39 } \
40 lhs = ::pw::internal::ConvertToValue(result);
41
42 // Macro for cleanly working with Status or StatusWithSize objects in functions
43 // that return StatusWithSize.
44 #define PW_TRY_WITH_SIZE(expr) _PW_TRY_WITH_SIZE(_PW_TRY_UNIQUE(__LINE__), expr)
45
46 #define _PW_TRY_WITH_SIZE(result, expr) \
47 do { \
48 if (auto result = (expr); !result.ok()) { \
49 return ::pw::internal::ConvertToStatusWithSize(result); \
50 } \
51 } while (0)
52
53 #define _PW_TRY_UNIQUE(line) _PW_TRY_UNIQUE_EXPANDED(line)
54 #define _PW_TRY_UNIQUE_EXPANDED(line) _pw_try_unique_name_##line
55
56 namespace pw::internal {
57
ConvertToStatus(Status status)58 constexpr Status ConvertToStatus(Status status) { return status; }
59
ConvertToStatus(StatusWithSize status_with_size)60 constexpr Status ConvertToStatus(StatusWithSize status_with_size) {
61 return status_with_size.status();
62 }
63
ConvertToValue(StatusWithSize status_with_size)64 constexpr size_t ConvertToValue(StatusWithSize status_with_size) {
65 return status_with_size.size();
66 }
67
ConvertToStatusWithSize(Status status)68 constexpr StatusWithSize ConvertToStatusWithSize(Status status) {
69 return StatusWithSize(status, 0);
70 }
71
ConvertToStatusWithSize(StatusWithSize status_with_size)72 constexpr StatusWithSize ConvertToStatusWithSize(
73 StatusWithSize status_with_size) {
74 return status_with_size;
75 }
76
77 } // namespace pw::internal
78