OR-Tools  9.2
status_macros.h
Go to the documentation of this file.
1// Copyright 2010-2021 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"
20
21namespace absl {
22
23// Run a command that returns a absl::Status. If the called code returns an
24// error status, return that status up out of this method too.
25//
26// Example:
27// RETURN_IF_ERROR(DoThings(4));
28// RETURN_IF_ERROR(DoThings(5)) << "Additional error context";
29#define RETURN_IF_ERROR(expr) \
30 switch (0) \
31 case 0: \
32 default: \
33 if (const ::absl::Status status = (expr); status.ok()) { \
34 } else /* NOLINT */ \
35 return ::util::StatusBuilder(status)
36
37// Internal helper for concatenating macro values.
38#define STATUS_MACROS_CONCAT_NAME_INNER(x, y) x##y
39#define STATUS_MACROS_CONCAT_NAME(x, y) STATUS_MACROS_CONCAT_NAME_INNER(x, y)
40
41#define ASSIGN_OR_RETURN_IMPL(statusor, lhs, rexpr) \
42 auto statusor = (rexpr); \
43 RETURN_IF_ERROR(statusor.status()); \
44 lhs = *std::move(statusor)
45
46// Executes an expression that returns an absl::StatusOr, extracting its value
47// into the variable defined by lhs (or returning on error).
48//
49// Example: Assigning to an existing value
50// ValueType value;
51// ASSIGN_OR_RETURN(value, MaybeGetValue(arg));
52//
53// WARNING: ASSIGN_OR_RETURN expands into multiple statements; it cannot be used
54// in a single statement (e.g. as the body of an if statement without {})!
55#define ASSIGN_OR_RETURN(lhs, rexpr) \
56 ASSIGN_OR_RETURN_IMPL( \
57 STATUS_MACROS_CONCAT_NAME(_status_or_value, __COUNTER__), lhs, rexpr);
58
59} // namespace absl
60
61#endif // OR_TOOLS_BASE_STATUS_MACROS_H_
Definition: cleanup.h:22