Asylo
status_macros.h
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2018 Asylo authors
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #ifndef ASYLO_UTIL_STATUS_MACROS_H_
20 #define ASYLO_UTIL_STATUS_MACROS_H_
21 
22 #include "absl/base/optimization.h"
23 #include "asylo/util/status.h"
24 #include "asylo/util/statusor.h"
25 
26 /// Evaluates an expression that produces an `asylo::Status`. If the status is
27 /// non-OK, returns it from the current function.
28 ///
29 /// Example:
30 /// ```
31 /// ::asylo::Status MultiStepFunction() {
32 /// ASYLO_RETURN_IF_ERROR(Function(args...));
33 /// ASYLO_RETURN_IF_ERROR(foo.Method(args...));
34 /// return ::asylo::Status::OkStatus();
35 /// }
36 /// ```
37 #define ASYLO_RETURN_IF_ERROR(expr) do
38  {
39  const auto _asylo_status_to_verify = (expr);
40  if (ABSL_PREDICT_FALSE(!_asylo_status_to_verify.ok())) {
41  return _asylo_status_to_verify;
42  } \
43 }while (false)
44 
45 /// Evaluates an expression `rexpr` that returns an `asylo::StatusOr<T>`.
46 /// If the result is OK, moves its value into the variable defined by `lhs`,
47 /// otherwise returns the `asylo::Status` from the current function. The error
48 /// `asylo::Status` is returned unchanged. If there is an error, `lhs` is not
49 /// evaluated; thus any side effects that `lhs` may have only occur in the
50 /// success case.
51 ///
52 /// Interface:
53 /// ```
54 /// ASYLO_ASSIGN_OR_RETURN(lhs, rexpr)
55 /// ```
56 ///
57 /// Example: Assigning to an existing variable:
58 /// ```
59 /// ValueType value;
60 /// ASYLO_ASSIGN_OR_RETURN(value, MaybeGetValue(arg));
61 /// ```
62 ///
63 /// Example: Assigning to an expression with side effects:
64 /// ```
65 /// MyProto data;
66 /// ASYLO_ASSIGN_OR_RETURN(*data.mutable_str(), MaybeGetValue(arg));
67 /// // No field "str" is added on error.
68 /// ```
69 ///
70 /// Example: Assigning to a `std::unique_ptr`.
71 /// ```
72 /// std::unique_ptr<T> ptr;
73 /// ASYLO_ASSIGN_OR_RETURN(ptr, MaybeGetPtr(arg));
74 /// ```
75 #define ASYLO_ASSIGN_OR_RETURN(lhs, rexpr) do
76  {
77  auto _asylo_status_or_value = (rexpr);
78  if (ABSL_PREDICT_FALSE(!_asylo_status_or_value.ok())) {
79  return _asylo_status_or_value.status();
80  }
81  lhs = std::move(_asylo_status_or_value).ValueOrDie(); \
82 }while (false)
83 
84 #endif // ASYLO_UTIL_STATUS_MACROS_H_