userver: userver/fs/blocking/file_descriptor.hpp Source File
Loading...
Searching...
No Matches
file_descriptor.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/fs/blocking/file_descriptor.hpp
4/// @brief @copybrief fs::blocking::FileDescriptor
5
6#include <string>
7#include <string_view>
8
9#include <boost/filesystem/operations.hpp>
10
11#include <userver/fs/blocking/open_mode.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace fs::blocking {
16
17/// @ingroup userver_universal userver_containers
18///
19/// @brief A file descriptor wrapper
20/// @details The file is closed in the destructor
21/// @note The operations on the file are blocking and not thread-safe
22class FileDescriptor final {
23 public:
24 /// @brief Open a file using ::open
25 /// @throws std::runtime_error
26 static FileDescriptor Open(
27 const std::string& path, OpenMode flags,
28 boost::filesystem::perms perms = boost::filesystem::perms::owner_read |
29 boost::filesystem::perms::owner_write);
30
31 /// @brief Open a directory node
32 /// @note The only valid operation for such a `FileDescriptor` is `FSync`.
33 /// @throws std::runtime_error
34 static FileDescriptor OpenDirectory(const std::string& path);
35
36 /// @brief Use the file descriptor directly
37 static FileDescriptor AdoptFd(int fd) noexcept;
38
39 FileDescriptor() = delete;
40 FileDescriptor(FileDescriptor&& other) noexcept;
41 FileDescriptor& operator=(FileDescriptor&& other) noexcept;
42 ~FileDescriptor();
43
44 /// @brief Checks if the file is open
45 /// @note Operations can only be performed on an open `FileDescriptor`.
46 bool IsOpen() const;
47
48 /// @brief Closes the file manually
49 /// @throws std::runtime_error
50 void Close() &&;
51
52 /// Returns the native file handle
53 int GetNative() const;
54
55 /// Passes the ownership of the file descriptor to the caller
56 int Release() &&;
57
58 /// @brief Writes data to the file
59 /// @warning Unless `FSync` is called, there is no guarantee the data
60 /// is stored on disk safely.
61 /// @throws std::runtime_error
62 void Write(std::string_view contents);
63
64 /// @brief Reads data from the file at current offset
65 /// @returns The amount of bytes actually acquired, which can be equal
66 /// to `max_size`, or less on end-of-file
67 /// @throws std::runtime_error
68 std::size_t Read(char* buffer, std::size_t max_size);
69
70 /// @brief Sets the file read/write offset from the beginning of the file
71 /// @throws std::runtime_error
72 void Seek(std::size_t offset_in_bytes);
73
74 /// @brief Makes sure the written data is actually stored on disk
75 /// @throws std::runtime_error
76 void FSync();
77
78 /// @brief Fetches the file size
79 /// @throws std::runtime_error
80 std::size_t GetSize() const;
81
82 private:
83 explicit FileDescriptor(int fd);
84
85 friend class TempFile;
86
87 int fd_;
88};
89
90} // namespace fs::blocking
91
92USERVER_NAMESPACE_END