Repository navigation
Expand file tree
/
Copy pathFile.mpp
More file actions
346 lines (323 loc) · 14.7 KB
/
Copy pathFile.mpp
File metadata and controls
346 lines (323 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
export module CppUtils.FileSystem.File;
import std;
import CppUtils.Type;
export namespace CppUtils::FileSystem
{
/// @brief Describes a file system operation error.
struct Error
{
/// @brief Category of the file system failure.
enum class Type
{
OpenFailed,
ReadFailed,
WriteFailed,
CallbackError
} type;
std::string_view message;
};
/**
* @brief Iterates over all regular files in @p directoryPath and invokes @p function on each path.
* @param directoryPath Root directory to inspect; returns immediately if missing or not a directory.
* @param function Callback invoked with each `std::filesystem::path`.
* @param recursively If `true`, traverses subdirectories recursively.
*/
inline auto forFiles(
const std::filesystem::path& directoryPath,
auto&& function,
bool recursively = false) -> void
{
if (not std::filesystem::exists(directoryPath) or not std::filesystem::is_directory(directoryPath))
return;
if (recursively)
{
for (const auto& directoryEntry : std::filesystem::recursive_directory_iterator(directoryPath))
if (const auto& path = directoryEntry.path(); not std::filesystem::is_directory(path))
function(path);
}
else
for (const auto& directoryEntry : std::filesystem::directory_iterator(directoryPath))
if (const auto& path = directoryEntry.path(); not std::filesystem::is_directory(path))
function(path);
}
/**
* @brief Iterates over files in @p directoryPath matching extension @p ext.
* @param directoryPath Root directory to inspect.
* @param ext Target file extension including the leading dot (e.g. `".txt"`).
* @param function Callback invoked with each matching `std::filesystem::path`.
* @param recursively If `true`, traverses subdirectories recursively.
*/
inline auto forFilesWithExtension(
const std::filesystem::path& directoryPath,
std::string_view ext,
auto&& function,
bool recursively = false) -> void
{
forFiles(directoryPath, [&ext, function = std::forward<decltype(function)>(function)](auto&& filePath) -> void {
if (filePath.extension() == ext)
function(filePath);
}, recursively);
}
/**
* @brief Streams a file in fixed-size chunks without loading the entire file into memory.
* @tparam T Block view type passed to @p function (`std::span<const std::byte>` or `std::string_view`).
* @param filePath Path to the file to read.
* @param function Callback invoked for each chunk; may return `std::expected` to abort early.
* @param blockSize Maximum chunk size in bytes (default: 4096).
* @return Empty `std::expected` on success, or an `Error` on open, read, or callback failure.
*/
template<class T = std::span<const std::byte>>
inline auto readByBlocks(
const std::filesystem::path& filePath,
auto&& function,
std::size_t blockSize = 4'096) -> std::expected<void, Error>
{
auto file = std::ifstream{filePath, std::ios::binary};
if (not file.is_open()) [[unlikely]]
return std::unexpected{Error{Error::Type::OpenFailed, "Failed to open file"}};
for (auto buffer = std::vector<char>(blockSize); file.good();)
{
file.read(std::ranges::data(buffer), static_cast<std::streamsize>(blockSize));
if (file.bad()) [[unlikely]]
return std::unexpected{Error{Error::Type::ReadFailed, "Hardware read error"}};
const auto bytesRead = static_cast<std::size_t>(file.gcount());
if (bytesRead == 0)
break;
auto block = [&]() {
if constexpr (std::same_as<T, std::string_view>)
return std::string_view{std::ranges::data(buffer), bytesRead};
else
return std::as_bytes(std::span{std::ranges::data(buffer), bytesRead});
}();
using ResultType = std::invoke_result_t<decltype(function), decltype(block)>;
if constexpr (Type::Specializes<ResultType, std::expected>)
{
if (auto result = function(block); not result)
return std::unexpected{Error{Error::Type::CallbackError, result.error()}};
}
else
function(block);
if (bytesRead < blockSize)
break;
}
return {};
}
namespace Binary
{
/**
* @brief Reads a binary file sequentially in fixed-size `std::span<const std::byte>` blocks.
* @param filePath Path to the file to read.
* @param function Callback invoked for each byte block.
* @param blockSize Size of each read chunk in bytes (default: 4096).
* @return Empty `std::expected` on success, or an `Error` on failure.
*/
[[nodiscard]] inline auto readByBlocks(const std::filesystem::path& filePath, auto&& function, std::size_t blockSize = 4'096)
{
return FileSystem::readByBlocks<std::span<const std::byte>>(filePath, std::forward<decltype(function)>(function), blockSize);
}
/**
* @brief Writes a contiguous range of trivially copyable elements in binary mode to @p filePath.
* @tparam Range Contiguous range whose elements are trivially copyable (`std::vector`, `std::span`, `std::array`, etc.).
* @param filePath Destination file path.
* @param range Elements to write as raw bytes.
* @param isAppend If `true`, appends to the end of the file; otherwise truncates it.
* @return Empty `std::expected` on success, or an `Error` on failure.
*/
template<std::ranges::contiguous_range Range>
requires Type::TriviallyCopyable<std::ranges::range_value_t<Range>>
inline auto write(const std::filesystem::path& filePath, const Range& range, bool isAppend = false) -> std::expected<void, Error>
{
const auto openMode = isAppend ? (std::ios::binary | std::ios::app) : (std::ios::binary | std::ios::trunc);
auto file = std::ofstream{filePath, openMode};
if (not file.is_open()) [[unlikely]]
return std::unexpected{Error{Error::Type::OpenFailed, "Failed to open file"}};
file.write(
reinterpret_cast<const char*>(std::ranges::data(range)),
static_cast<std::streamsize>(std::ranges::size(range) * sizeof(std::ranges::range_value_t<Range>)));
if (file.bad()) [[unlikely]]
return std::unexpected{Error{Error::Type::WriteFailed, "Hardware write error"}};
return {};
}
/**
* @brief Writes a trivially copyable object in binary mode to @p filePath.
* @tparam T Trivially copyable, non-range type to serialize.
* @param filePath Destination file path.
* @param buffer Source object to serialize as raw bytes.
* @param isAppend If `true`, appends to the end of the file; otherwise truncates it.
* @return Empty `std::expected` on success, or an `Error` on failure.
*/
template<Type::TriviallyCopyable T>
requires (not std::ranges::contiguous_range<T>)
inline auto write(const std::filesystem::path& filePath, const T& buffer, bool isAppend = false) -> std::expected<void, Error>
{
return write(filePath, std::span{std::addressof(buffer), 1uz}, isAppend);
}
/**
* @brief Appends a trivially copyable object or contiguous range in binary mode to the end of @p filePath.
* @param filePath Destination file path.
* @param data Source object or contiguous range to append as raw bytes.
* @return Empty `std::expected` on success, or an `Error` on failure.
*/
inline auto append(const std::filesystem::path& filePath, const auto& data) -> std::expected<void, Error>
requires requires { write(filePath, data, true); }
{
return write(filePath, data, true);
}
/**
* @brief Reads a trivially copyable object in binary mode from @p filePath.
* @tparam T Trivially copyable target type to deserialize.
* @param filePath Source file path.
* @return Deserialized object on success, or an `Error` on open or read failure.
*/
template<Type::TriviallyCopyable T>
[[nodiscard]] inline auto read(const std::filesystem::path& filePath) -> std::expected<T, Error>
{
auto file = std::ifstream{filePath, std::ios::binary};
if (not file.is_open()) [[unlikely]]
return std::unexpected{Error{Error::Type::OpenFailed, "Failed to open file"}};
auto buffer = T{};
file.read(reinterpret_cast<char*>(std::addressof(buffer)), sizeof(buffer));
if (file.bad()) [[unlikely]]
return std::unexpected{Error{Error::Type::ReadFailed, "Hardware read error"}};
return buffer;
}
/**
* @brief Reads an entire binary file into a `std::vector<T>` sized from the file size on disk.
* @tparam T Trivially copyable element type.
* @param filePath Source file path.
* @return Vector of elements on success, or an `Error` on open, size, or read failure.
*/
template<Type::TriviallyCopyable T>
[[nodiscard]] inline auto readVector(const std::filesystem::path& filePath) -> std::expected<std::vector<T>, Error>
{
auto file = std::ifstream{filePath, std::ios::binary};
if (not file.is_open()) [[unlikely]]
return std::unexpected{Error{Error::Type::OpenFailed, "Failed to open file"}};
auto errorCode = std::error_code{};
const auto fileSize = std::filesystem::file_size(filePath, errorCode);
if (errorCode) [[unlikely]]
return std::unexpected{Error{Error::Type::ReadFailed, "Failed to get file size"}};
const auto elementCount = fileSize / sizeof(T);
auto vector = std::vector<T>{};
vector.resize(elementCount);
if (elementCount > 0uz)
{
file.read(reinterpret_cast<char*>(std::ranges::data(vector)), static_cast<std::streamsize>(elementCount * sizeof(T)));
if (file.bad()) [[unlikely]]
return std::unexpected{Error{Error::Type::ReadFailed, "Hardware read error"}};
}
return vector;
}
/**
* @brief Reads up to @p length bytes from @p filePath starting at @p offset without loading the entire file.
* @param filePath Source file path.
* @param offset Byte offset from the beginning of the file.
* @param length Maximum number of bytes to read.
* @return Vector of bytes read, or an Error if opening, sizing, or reading fails.
*/
[[nodiscard]] inline auto readRange(const std::filesystem::path& filePath, std::size_t offset, std::size_t length) -> std::expected<std::vector<std::byte>, Error>
{
auto file = std::ifstream{filePath, std::ios::binary};
if (not file.is_open()) [[unlikely]]
return std::unexpected{Error{Error::Type::OpenFailed, "Failed to open file"}};
auto errorCode = std::error_code{};
const auto fileSize = std::filesystem::file_size(filePath, errorCode);
if (errorCode) [[unlikely]]
return std::unexpected{Error{Error::Type::ReadFailed, "Failed to get file size"}};
if (offset >= fileSize or length == 0uz)
return std::vector<std::byte>{};
const auto readableLength = std::ranges::min(length, fileSize - offset);
file.seekg(static_cast<std::streamoff>(offset), std::ios::beg);
if (file.fail()) [[unlikely]]
return std::unexpected{Error{Error::Type::ReadFailed, "Failed to seek in file"}};
auto buffer = std::vector<std::byte>(readableLength);
file.read(reinterpret_cast<char*>(std::ranges::data(buffer)), static_cast<std::streamsize>(readableLength));
if (file.bad()) [[unlikely]]
return std::unexpected{Error{Error::Type::ReadFailed, "Hardware read error"}};
buffer.resize(static_cast<std::size_t>(file.gcount()));
return buffer;
}
/**
* @brief Writes @p data at @p offset in @p filePath without rewriting the rest of the file.
* @details Preserves existing bytes outside `[offset, offset + data.size())`. Creates the file if it does not exist.
* @param filePath Destination file path.
* @param offset Byte offset from the beginning of the file.
* @param data Bytes to write at @p offset.
* @return Empty expected on success, or an Error if opening, seeking, or writing fails.
*/
inline auto writeRange(const std::filesystem::path& filePath, std::size_t offset, std::span<const std::byte> data) -> std::expected<void, Error>
{
auto errorCode = std::error_code{};
const auto fileExists = std::filesystem::exists(filePath, errorCode);
auto file = fileExists ? std::fstream{filePath, std::ios::binary | std::ios::in | std::ios::out} : std::fstream{filePath, std::ios::binary | std::ios::out};
if (not file.is_open()) [[unlikely]]
return std::unexpected{Error{Error::Type::OpenFailed, "Failed to open file"}};
file.seekp(static_cast<std::streamoff>(offset), std::ios::beg);
if (file.fail()) [[unlikely]]
return std::unexpected{Error{Error::Type::WriteFailed, "Failed to seek in file"}};
if (not std::ranges::empty(data))
{
file.write(reinterpret_cast<const char*>(std::ranges::data(data)), static_cast<std::streamsize>(std::ranges::size(data)));
if (file.bad() or file.fail()) [[unlikely]]
return std::unexpected{Error{Error::Type::WriteFailed, "Hardware write error"}};
}
return {};
}
}
namespace String
{
/**
* @brief Reads a text file sequentially in fixed-size `std::string_view` blocks.
* @param filePath Path to the file to read.
* @param function Callback invoked for each block.
* @param blockSize Size of each read chunk in bytes (default: 4096).
*/
[[nodiscard]] inline auto readByBlocks(const std::filesystem::path& filePath, auto&& function, std::size_t blockSize = 4'096)
{
return FileSystem::readByBlocks<std::string_view>(filePath, std::forward<decltype(function)>(function), blockSize);
}
/**
* @brief Writes text content to a file.
* @param filePath Destination file path.
* @param content Text content to write.
* @param isAppend If `true`, appends to the end of the file; otherwise truncates it.
* @return Empty `std::expected` on success, or an `Error` on failure.
*/
inline auto write(const std::filesystem::path& filePath, std::string_view content, bool isAppend = false) -> std::expected<void, Error>
{
const auto openMode = isAppend ? (std::ios::out | std::ios::app) : (std::ios::out | std::ios::trunc);
auto file = std::ofstream{filePath, openMode};
if (not file.is_open()) [[unlikely]]
return std::unexpected{Error{Error::Type::OpenFailed, "Failed to open file"}};
file << content;
if (file.bad()) [[unlikely]]
return std::unexpected{Error{Error::Type::WriteFailed, "Hardware write error"}};
return {};
}
/**
* @brief Appends text content to the end of a file.
* @param filePath Destination file path.
* @param content Text content to append.
* @return Empty `std::expected` on success, or an `Error` on failure.
*/
inline auto append(const std::filesystem::path& filePath, std::string_view content) -> std::expected<void, Error>
{
return write(filePath, content, true);
}
/**
* @brief Reads the entire contents of a text file into a `std::string`.
* @param filePath Source file path.
* @return File contents on success, or an `Error` on failure.
*/
[[nodiscard]] inline auto read(const std::filesystem::path& filePath) -> std::expected<std::string, Error>
{
auto file = std::ifstream{filePath};
if (not file.is_open()) [[unlikely]]
return std::unexpected{Error{Error::Type::OpenFailed, "Failed to open file"}};
auto content = std::string{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};
if (file.bad()) [[unlikely]]
return std::unexpected{Error{Error::Type::ReadFailed, "Hardware read error"}};
return content;
}
}
}