|
| 1 | +// |
| 2 | +// Copyright (C) 2026 The Android Open Source Project |
| 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 | +#include "cuttlefish/io/native_filesystem.h" |
| 17 | + |
| 18 | +#include <errno.h> |
| 19 | +#include <stdint.h> |
| 20 | +#include <unistd.h> |
| 21 | + |
| 22 | +#include <string_view> |
| 23 | + |
| 24 | +#include "cuttlefish/common/libs/fs/shared_fd.h" |
| 25 | +#include "cuttlefish/io/shared_fd.h" |
| 26 | +#include "cuttlefish/posix/strerror.h" |
| 27 | +#include "cuttlefish/result/expect.h" |
| 28 | +#include "cuttlefish/result/result_type.h" |
| 29 | + |
| 30 | +namespace cuttlefish { |
| 31 | + |
| 32 | +Result<std::unique_ptr<ReaderWriterSeeker>> NativeFilesystem::CreateFile( |
| 33 | + std::string_view path) { |
| 34 | + SharedFD fd = |
| 35 | + SharedFD::Open(std::string(path), O_CLOEXEC | O_CREAT | O_EXCL | O_RDWR); |
| 36 | + CF_EXPECTF(fd->IsOpen(), |
| 37 | + "Failed to open '{}' with O_CREAT | O_EXCL | O_RDWR: '{}'", path, |
| 38 | + fd->StrError()); |
| 39 | + return std::make_unique<SharedFdIo>(fd); |
| 40 | +} |
| 41 | + |
| 42 | +Result<void> NativeFilesystem::DeleteFile(std::string_view path) { |
| 43 | + CF_EXPECT_GE(unlink(std::string(path).c_str()), 0, StrError(errno)); |
| 44 | + return {}; |
| 45 | +} |
| 46 | + |
| 47 | +Result<std::unique_ptr<ReaderSeeker>> NativeFilesystem::OpenReadOnly( |
| 48 | + std::string_view path) { |
| 49 | + SharedFD fd = SharedFD::Open(std::string(path), O_CLOEXEC | O_RDONLY); |
| 50 | + CF_EXPECTF(fd->IsOpen(), "Failed to open '{}' with O_RDONLY: '{}'", path, |
| 51 | + fd->StrError()); |
| 52 | + return std::make_unique<SharedFdIo>(fd); |
| 53 | +} |
| 54 | + |
| 55 | +Result<std::unique_ptr<ReaderWriterSeeker>> NativeFilesystem::OpenReadWrite( |
| 56 | + std::string_view path) { |
| 57 | + SharedFD fd = SharedFD::Open(std::string(path), O_CLOEXEC | O_RDWR); |
| 58 | + CF_EXPECTF(fd->IsOpen(), "Failed to open '{}' with O_RDWR: '{}'", path, |
| 59 | + fd->StrError()); |
| 60 | + return std::make_unique<SharedFdIo>(fd); |
| 61 | +} |
| 62 | + |
| 63 | +} // namespace cuttlefish |
0 commit comments