file_error_or.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_FILES_FILE_ERROR_OR_H_
  5. #define BASE_FILES_FILE_ERROR_OR_H_
  6. #include <utility>
  7. #include "base/check.h"
  8. #include "base/files/file.h"
  9. #include "base/types/expected.h"
  10. namespace base {
  11. // Helper for methods which perform file system operations and which may fail.
  12. // Objects of this type can take on EITHER a base::File::Error value OR a result
  13. // value of the specified type.
  14. template <typename ValueType>
  15. class FileErrorOr {
  16. public:
  17. // These constructors are intentionally not marked `explicit` for cleaner code
  18. // at call sites.
  19. FileErrorOr(File::Error error) : value_or_error_(unexpected(error)) {}
  20. FileErrorOr(ValueType&& value) : value_or_error_(std::move(value)) {}
  21. FileErrorOr(const FileErrorOr&) = default;
  22. FileErrorOr(FileErrorOr&&) = default;
  23. FileErrorOr& operator=(const FileErrorOr&) = default;
  24. FileErrorOr& operator=(FileErrorOr&&) = default;
  25. ~FileErrorOr() = default;
  26. bool is_error() const { return !value_or_error_.has_value(); }
  27. File::Error error() const { return value_or_error_.error(); }
  28. bool is_value() const { return value_or_error_.has_value(); }
  29. ValueType& value() { return value_or_error_.value(); }
  30. const ValueType& value() const { return value_or_error_.value(); }
  31. ValueType* operator->() { return &value(); }
  32. const ValueType* operator->() const { return &value(); }
  33. private:
  34. expected<ValueType, File::Error> value_or_error_;
  35. };
  36. } // namespace base
  37. #endif // BASE_FILES_FILE_ERROR_OR_H_