status_macros.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright 2020 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef RLWE_STATUS_MACROS_H_
  17. #define RLWE_STATUS_MACROS_H_
  18. #include "absl/status/status.h"
  19. #include "statusor.h"
  20. // Helper macro that checks if the right hand side (rexpression) evaluates to a
  21. // StatusOr with Status OK, and if so assigns the value to the value on the left
  22. // hand side (lhs), otherwise returns the error status. Example:
  23. // RLWE_RLWE_ASSIGN_OR_RETURN(lhs, rexpression);
  24. #define RLWE_ASSIGN_OR_RETURN(lhs, rexpr) \
  25. RLWE_ASSIGN_OR_RETURN_IMPL_( \
  26. RLWE_STATUS_MACROS_IMPL_CONCAT_(_status_or_value, __LINE__), lhs, rexpr)
  27. // Internal helper.
  28. #define RLWE_ASSIGN_OR_RETURN_IMPL_(statusor, lhs, rexpr) \
  29. auto statusor = (rexpr); \
  30. if (ABSL_PREDICT_FALSE(!statusor.ok())) { \
  31. return std::move(statusor).status(); \
  32. } \
  33. lhs = std::move(statusor).value()
  34. // Internal helper for concatenating macro values.
  35. #define RLWE_STATUS_MACROS_IMPL_CONCAT_INNER_(x, y) x##y
  36. #define RLWE_STATUS_MACROS_IMPL_CONCAT_(x, y) \
  37. RLWE_STATUS_MACROS_IMPL_CONCAT_INNER_(x, y)
  38. #define RLWE_RETURN_IF_ERROR(expr) \
  39. RLWE_RETURN_IF_ERROR_IMPL_( \
  40. RLWE_STATUS_MACROS_IMPL_CONCAT_(_status, __LINE__), expr)
  41. #define RLWE_RETURN_IF_ERROR_IMPL_(status, expr) \
  42. auto status = (expr); \
  43. if (ABSL_PREDICT_FALSE(!status.ok())) { \
  44. return status; \
  45. }
  46. #endif // RLWE_STATUS_MACROS_H_