/* * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef UTILS_FILEMGMT_LIBFS_INCLUDE_FS_RESULT_H #define UTILS_FILEMGMT_LIBFS_INCLUDE_FS_RESULT_H #include "fs_error.h" #include #include #include #include namespace OHOS::FileManagement::ModuleFileIO { template class FsResult { using OptionalData = std::optional; public: static FsResult Success() { return FsResult(FsError(ERRNO_NOERR), std::nullopt); } static FsResult Success(const T &data) { return FsResult(FsError(ERRNO_NOERR), std::make_optional(data)); } static FsResult Success(T &&data) { return FsResult(FsError(ERRNO_NOERR), std::make_optional(std::move(data))); } template , int> = 0> static FsResult Success(const char *data) { return FsResult(FsError(ERRNO_NOERR), std::make_optional(std::string(data))); } static FsResult Error(const int32_t code) { return FsResult(FsError(code), std::nullopt); } bool IsSuccess() const { return !error_; } const OptionalData &GetData() const { return data_; } OptionalData &GetData() { return data_; } const FsError &GetError() const { return error_; } FsResult(const FsResult &) = delete; FsResult &operator=(const FsResult &) = delete; FsResult(FsResult &&other) noexcept : error_(std::move(other.error_)), data_(std::move(other.data_)) {} FsResult &operator=(FsResult &&other) noexcept { if (this != &other) { error_ = std::move(other.error_); data_ = std::move(other.data_); } return *this; } ~FsResult() = default; private: FsError error_; OptionalData data_; FsResult(const FsError &err, const OptionalData &data) : error_(err), data_(data) {} FsResult(const FsError &err, OptionalData &&data) : error_(err), data_(std::move(data)) {} }; template <> class FsResult { private: FsError error_; explicit FsResult(const FsError &err) : error_(err) {} public: static FsResult Success() { return FsResult(FsError(ERRNO_NOERR)); } static FsResult Error(const int32_t code) { return FsResult(FsError(code)); } bool IsSuccess() const { return !error_; } const FsError &GetError() const { return error_; } FsResult(const FsResult &) = delete; FsResult &operator=(const FsResult &) = delete; FsResult(FsResult &&other) noexcept : error_(std::move(other.error_)) {} FsResult &operator=(FsResult &&other) noexcept { if (this != &other) { error_ = std::move(other.error_); } return *this; } ~FsResult() = default; }; } // namespace OHOS::FileManagement::ModuleFileIO #endif // UTILS_FILEMGMT_LIBFS_INCLUDE_FS_RESULT_H