FileSystem: Add some more wrappers for convenience

This commit is contained in:
Léo Lam 2018-04-08 18:42:52 +02:00
parent b2de380d16
commit 3744a6d3f5
2 changed files with 42 additions and 22 deletions

View File

@ -28,7 +28,7 @@ FileHandle::FileHandle(FileHandle&& other) : m_fs{other.m_fs}, m_fd{other.m_fd}
FileHandle& FileHandle::operator=(FileHandle&& other)
{
if (*this != other)
if (std::tie(m_fs, m_fd) != std::tie(other.m_fs, other.m_fd))
*this = std::move(other);
return *this;
}
@ -46,6 +46,16 @@ Fd FileHandle::Release()
return fd;
}
Result<u32> FileHandle::Seek(u32 offset, SeekMode mode) const
{
return m_fs->SeekFile(*m_fd, offset, mode);
}
Result<FileStatus> FileHandle::GetStatus() const
{
return m_fs->GetFileStatus(*m_fd);
}
void FileSystem::Init()
{
if (Delete(0, 0, "/tmp") == ResultCode::Success)

View File

@ -108,10 +108,18 @@ public:
FileHandle& operator=(const FileHandle&) = delete;
FileHandle& operator=(FileHandle&&);
operator Fd() const { return m_fd.value(); }
/// Release the FD so that it is not automatically closed.
Fd Release();
template <typename T>
Result<size_t> Read(T* ptr, size_t count) const;
template <typename T>
Result<size_t> Write(const T* ptr, size_t count) const;
Result<u32> Seek(u32 offset, SeekMode mode) const;
Result<FileStatus> GetStatus() const;
private:
FileSystem* m_fs;
std::optional<Fd> m_fd;
@ -140,26 +148,6 @@ public:
/// Get status for a file descriptor.
virtual Result<FileStatus> GetFileStatus(Fd fd) = 0;
template <typename T>
Result<u32> ReadFile(Fd fd, T* ptr, u32 count)
{
const Result<u32> bytes = ReadBytesFromFile(fd, reinterpret_cast<u8*>(ptr), sizeof(T) * count);
if (!bytes)
return bytes.Error();
if (*bytes != sizeof(T) * count)
return ResultCode::ShortRead;
return count;
}
template <typename T>
Result<u32> WriteFile(Fd fd, const T* ptr, u32 count)
{
const auto result = WriteBytesToFile(fd, reinterpret_cast<const u8*>(ptr), sizeof(T) * count);
if (!result)
return result.Error();
return count;
}
/// Create a file with the specified path and metadata.
virtual ResultCode CreateFile(Uid caller_uid, Gid caller_gid, const std::string& path,
FileAttribute attribute, Mode owner_mode, Mode group_mode,
@ -195,6 +183,28 @@ protected:
void Init();
};
template <typename T>
Result<size_t> FileHandle::Read(T* ptr, size_t count) const
{
const Result<u32> bytes = m_fs->ReadBytesFromFile(*m_fd, reinterpret_cast<u8*>(ptr),
static_cast<u32>(sizeof(T) * count));
if (!bytes)
return bytes.Error();
if (*bytes != sizeof(T) * count)
return ResultCode::ShortRead;
return count;
}
template <typename T>
Result<size_t> FileHandle::Write(const T* ptr, size_t count) const
{
const auto result = m_fs->WriteBytesToFile(*m_fd, reinterpret_cast<const u8*>(ptr),
static_cast<u32>(sizeof(T) * count));
if (!result)
return result.Error();
return count;
}
enum class Location
{
Configured,