C/C++ API Reference
Loading...
Searching...
No Matches
try.h
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
22
23// Macros for cleanly working with Status or StatusWithSize objects in functions
24// that return Status.
25
27#define PW_TRY(expr) _PW_TRY(_PW_TRY_UNIQUE(__LINE__), expr, return)
28
30
31#define _PW_TRY(result, expr, return_stmt) \
32 do { \
33 if (auto result = (expr); !result.ok()) { \
34 return_stmt ::pw::internal::ConvertToStatus(result); \
35 } \
36 } while (0)
37
39
42#define PW_TRY_ASSIGN(lhs, expression) \
43 _PW_TRY_ASSIGN(_PW_TRY_UNIQUE(__LINE__), lhs, expression, return)
44
46
47#define _PW_TRY_ASSIGN(result, lhs, expr, return_stmt) \
48 auto result = (expr); \
49 if (!result.ok()) { \
50 return_stmt ::pw::internal::ConvertToStatus(result); \
51 } \
52 lhs = ::pw::internal::ConvertToValue(result)
53
55
59#define PW_TRY_WITH_SIZE(expr) _PW_TRY_WITH_SIZE(_PW_TRY_UNIQUE(__LINE__), expr)
60
62
63#define _PW_TRY_WITH_SIZE(result, expr) \
64 do { \
65 if (auto result = (expr); !result.ok()) { \
66 return ::pw::internal::ConvertToStatusWithSize(result); \
67 } \
68 } while (0)
69
70#define _PW_TRY_UNIQUE(line) _PW_TRY_UNIQUE_EXPANDED(line)
71#define _PW_TRY_UNIQUE_EXPANDED(line) _pw_try_unique_name_##line
72
74
80#define PW_CO_TRY(expr) _PW_TRY(_PW_TRY_UNIQUE(__LINE__), expr, co_return)
81
87#define PW_CO_TRY_ASSIGN(lhs, expression) \
88 _PW_TRY_ASSIGN(_PW_TRY_UNIQUE(__LINE__), lhs, expression, co_return)
89