ErrorHolder.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2016-present, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. */
  9. #pragma once
  10. #include <atomic>
  11. #include <cassert>
  12. #include <stdexcept>
  13. #include <string>
  14. namespace pzstd {
  15. // Coordinates graceful shutdown of the pzstd pipeline
  16. class ErrorHolder {
  17. std::atomic<bool> error_;
  18. std::string message_;
  19. public:
  20. ErrorHolder() : error_(false) {}
  21. bool hasError() noexcept {
  22. return error_.load();
  23. }
  24. void setError(std::string message) noexcept {
  25. // Given multiple possibly concurrent calls, exactly one will ever succeed.
  26. bool expected = false;
  27. if (error_.compare_exchange_strong(expected, true)) {
  28. message_ = std::move(message);
  29. }
  30. }
  31. bool check(bool predicate, std::string message) noexcept {
  32. if (!predicate) {
  33. setError(std::move(message));
  34. }
  35. return !hasError();
  36. }
  37. std::string getError() noexcept {
  38. error_.store(false);
  39. return std::move(message_);
  40. }
  41. ~ErrorHolder() {
  42. assert(!hasError());
  43. }
  44. };
  45. }