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 
24 /// Evaluates an expression that produces an `Status`-like object with
25 /// a `.ok()` method. If this method returns false, the object is
26 /// returned from the current function.
27 ///
28 /// Example:
29 /// ```
30 /// ::asylo::Status MultiStepFunction() {
31 /// ASYLO_RETURN_IF_ERROR(Function(args...));
32 /// ASYLO_RETURN_IF_ERROR(foo.Method(args...));
33 /// return ::asylo::Status::OkStatus();
34 /// }
35 /// ```
36 #define ASYLO_RETURN_IF_ERROR(expr) do
37  {
38  const auto _asylo_status_to_verify = (expr);
39  if (ABSL_PREDICT_FALSE(!_asylo_status_to_verify.ok())) {
40  return _asylo_status_to_verify;
41  } \
42 }while (false)
43 
44 /// Evaluates an expression `rexpr` that returns a `StatusOr`-like
45 /// object with `.ok()`, `.status()`, and `.ValueOrDie()` methods. If
46 /// the result is OK, moves its value into the variable defined by
47 /// `lhs`, otherwise returns the result of the `.status()` from the
48 /// current function. The error result of `.status` is returned
49 /// unchanged. If there is an error, `lhs` is not evaluated: thus any
50 /// side effects of evaluating `lhs` will only occur if `rexpr.ok()`
51 /// is true.
52 ///
53 /// Interface:
54 /// ```
55 /// ASYLO_ASSIGN_OR_RETURN(lhs, rexpr)
56 /// ```
57 ///
58 /// Example: Assigning to an existing variable:
59 /// ```
60 /// ValueType value;
61 /// ASYLO_ASSIGN_OR_RETURN(value, MaybeGetValue(arg));
62 /// ```
63 ///
64 /// Example: Assigning to an expression with side effects:
65 /// ```
66 /// MyProto data;
67 /// ASYLO_ASSIGN_OR_RETURN(*data.mutable_str(), MaybeGetValue(arg));
68 /// // No field "str" is added on error.
69 /// ```
70 ///
71 /// Example: Assigning to a `std::unique_ptr`.
72 /// ```
73 /// std::unique_ptr<T> ptr;
74 /// ASYLO_ASSIGN_OR_RETURN(ptr, MaybeGetPtr(arg));
75 /// ```
76 #define ASYLO_ASSIGN_OR_RETURN(lhs, rexpr) do
77  {
78  auto _asylo_status_or_value = (rexpr);
79  if (ABSL_PREDICT_FALSE(!_asylo_status_or_value.ok())) {
80  return _asylo_status_or_value.status();
81  }
82  lhs = std::move(_asylo_status_or_value).ValueOrDie(); \
83 }while (false)
84 
85 #endif // ASYLO_UTIL_STATUS_MACROS_H_