OR-Tools  8.1
status_macros.h
Go to the documentation of this file.
1 // Copyright 2010-2018 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #ifndef OR_TOOLS_BASE_STATUS_MACROS_H_
15 #define OR_TOOLS_BASE_STATUS_MACROS_H_
16 
17 #include "absl/status/status.h"
18 #include "absl/status/statusor.h"
19 
20 namespace absl {
21 
22 // Run a command that returns a absl::Status. If the called code returns an
23 // error status, return that status up out of this method too.
24 //
25 // Example:
26 // RETURN_IF_ERROR(DoThings(4));
27 #define RETURN_IF_ERROR(expr) \
28  do { \
29  /* Using _status below to avoid capture problems if expr is "status". */ \
30  const ::absl::Status _status = (expr); \
31  if (!_status.ok()) return _status; \
32  } while (0)
33 
34 // Internal helper for concatenating macro values.
35 #define STATUS_MACROS_CONCAT_NAME_INNER(x, y) x##y
36 #define STATUS_MACROS_CONCAT_NAME(x, y) STATUS_MACROS_CONCAT_NAME_INNER(x, y)
37 
38 template <typename T>
39 ::absl::Status DoAssignOrReturn(T& lhs, ::absl::StatusOr<T> result) { // NOLINT
40  if (result.ok()) {
41  lhs = result.value();
42  }
43  return result.status();
44 }
45 
46 #define ASSIGN_OR_RETURN_IMPL(status, lhs, rexpr) \
47  ::absl::Status status = DoAssignOrReturn(lhs, (rexpr)); \
48  if (!status.ok()) return status;
49 
50 // Executes an expression that returns an absl::StatusOr, extracting its value
51 // into the variable defined by lhs (or returning on error).
52 //
53 // Example: Assigning to an existing value
54 // ValueType value;
55 // ASSIGN_OR_RETURN(value, MaybeGetValue(arg));
56 //
57 // WARNING: ASSIGN_OR_RETURN expands into multiple statements; it cannot be used
58 // in a single statement (e.g. as the body of an if statement without {})!
59 #define ASSIGN_OR_RETURN(lhs, rexpr) \
60  ASSIGN_OR_RETURN_IMPL( \
61  STATUS_MACROS_CONCAT_NAME(_status_or_value, __COUNTER__), lhs, rexpr);
62 
63 } // namespace absl
64 
65 #endif // OR_TOOLS_BASE_STATUS_MACROS_H_
absl
Definition: cleanup.h:22
absl::DoAssignOrReturn
::absl::Status DoAssignOrReturn(T &lhs, ::absl::StatusOr< T > result)
Definition: status_macros.h:39