Echo Writes Code

posix_filesystem.cpp

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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
#include "crucible/core/filesystem.hpp"

#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "crucible/core/iterators.hpp"
#include "crucible/core/platform.hpp"

#if !CRUCIBLE_PLATFORM_HAS_DIRENT_D_NAMLEN
#include <cstring>
#endif // CRUCIBLE_PLATFORM_HAS_DIRENT_D_NAMLEN

namespace crucible
{
	// POSIX native path API -----------------------

	struct native_directory_list_iterator_data
	{
		::DIR *directory_handle { nullptr };
	};

	struct file_reader_data
	{
		int file_descriptor { -1 };
	};

	struct file_writer_data
	{
		int file_descriptor { -1 };
	};

	native_directory_list_iterator::native_directory_list_iterator(std::unique_ptr<native_directory_list_iterator_data> data) :
		my_data { std::move(data) }
	{}

	native_directory_list_iterator::native_directory_list_iterator(native_directory_list_iterator &&that) :
		my_data { std::move(that.my_data) }
	{}

	native_directory_list_iterator::~native_directory_list_iterator()
	{
		if (my_data) {
			CRUCIBLE_ASSERT_NE(my_data->directory_handle, nullptr);

			errno = 0;
			::closedir(my_data->directory_handle);
		}
	}

	auto native_directory_list_iterator::operator=(native_directory_list_iterator &&that) -> native_directory_list_iterator &
	{
		if (my_data) {
			CRUCIBLE_ASSERT_NE(my_data->directory_handle, nullptr);

			errno = 0;
			::closedir(my_data->directory_handle);
		}

		my_data = std::move(that.my_data);
		return *this;
	}

	auto native_directory_list_iterator::advance() -> std::optional<filesystem_result<native_directory_entry>>
	{
		CRUCIBLE_ASSERT_NE(my_data, nullptr);
		CRUCIBLE_ASSERT_NE(my_data->directory_handle, nullptr);

		std::optional<native_directory_entry> next_element { std::nullopt };
		struct ::dirent *entry { nullptr };

		while ((errno = 0, entry = ::readdir(my_data->directory_handle)) != nullptr) {

#if CRUCIBLE_PLATFORM_HAS_DIRENT_D_NAMLEN
			std::size_t const name_length { entry->d_namlen };
#else // CRUCIBLE_PLATFORM_HAS_DIRENT_D_NAMLEN
			std::size_t const name_length { std::strlen(entry->d_name) };
#endif // CRUCIBLE_PLATFORM_HAS_DIRENT_D_NAMLEN

			bool const is_dot { std::strncmp(entry->d_name, ".", name_length) == 0 };
			bool const is_dot_dot { std::strncmp(entry->d_name, "..", name_length) == 0 };

			if (is_dot || is_dot_dot) {
				continue;
			}

			next_element = native_directory_entry {};
			next_element->name = ffi_string<char>(entry->d_name, name_length);

			if (entry->d_type == DT_LNK) {
				next_element->type = file_type::symbolic_link;
			} else if (entry->d_type == DT_DIR) {
				next_element->type = file_type::directory;
			} else {
				next_element->type = file_type::normal;
			}

			break;
		}

		if (errno != 0) {
			return make_failure<filesystem_error>(readdir_failed {});
		}

		if (next_element) {
			return make_success(std::move(next_element).value());
		}

		return std::nullopt;
	}

	auto try_make_directory_list_iterator_native(ffi_string<char> const &path) -> filesystem_result<native_directory_list_iterator>
	{
		auto data { std::make_unique<native_directory_list_iterator_data>() };

		errno = 0;
		data->directory_handle = ::opendir(path.data());

		if (!data->directory_handle) {
			return make_failure<filesystem_error>(opendir_failed {});
		}

		return make_success<native_directory_list_iterator>(std::move(data));
	}

	auto try_make_file_reader_native(ffi_string<char> const &path) -> filesystem_result<file_reader>
	{
		auto data { std::make_unique<file_reader_data>() };

		errno = 0;
		data->file_descriptor = ::open(path.data(), O_RDONLY);

		if (data->file_descriptor < 0) {
			return make_failure<filesystem_error>(open_failed {});
		}

		return make_success<file_reader>(std::move(data));
	}

	auto try_make_file_writer_native(ffi_string<char> const &path, file_creation_mode const mode) -> filesystem_result<file_writer>
	{
		// TODO: add an API for this information
		constexpr ::mode_t PERMISSION_BITS {
			S_IRUSR |
			S_IWUSR |
			S_IRGRP |
			S_IROTH
		};

		int flags { O_WRONLY | O_CREAT | O_TRUNC };

		switch (mode) {
		case file_creation_mode::create:
			flags |= O_EXCL;
			break;

		case file_creation_mode::overwrite:
			break;
		}

		auto data { std::make_unique<file_writer_data>() };

		errno = 0;
		data->file_descriptor = ::open(path.data(), flags, PERMISSION_BITS);

		if (data->file_descriptor < 0) {
			return make_failure<filesystem_error>(open_failed {});
		}

		return make_success<file_writer>(std::move(data));
	}

	auto try_read_file_type_native(ffi_string<char> const &path) -> filesystem_result<file_type>
	{
		struct ::stat metadata {};

		errno = 0;
		int const stat_status { ::stat(path.data(), &metadata) };

		if (stat_status < 0) {
			return make_failure<filesystem_error>(stat_failed {});
		}

		if ((metadata.st_mode & S_IFMT) == S_IFDIR) {
			return make_success(file_type::directory);
		}

		if ((metadata.st_mode & S_IFMT) == S_IFLNK) {
			return make_success(file_type::symbolic_link);
		}

		// We could check for `S_IFREG`, but `file_type` has no cases besides `normal`
		return make_success(file_type::normal);
	}

	auto try_read_directory_list_native(ffi_string<char> const &path) -> filesystem_result<heap_buffer<native_directory_entry>>
	{
		return try_make_directory_list_iterator_native(path)
			.take_success_then([](native_directory_list_iterator iterator) {
				return make_iterator_pipeline(std::move(iterator))
					.try_materialize<heap_buffer<native_directory_entry>>();
			});
	}

	auto try_read_file_size_native(ffi_string<char> const &path) -> filesystem_result<std::size_t>
	{
		// We don't use `file_reader::try_read_size()` here because we can save two system calls by
		// using `::stat()` instead of `::open()` + `::fstat()` + `::close()`

		struct ::stat metadata {};

		errno = 0;
		int const stat_status { ::stat(path.data(), &metadata) };

		if (stat_status < 0) {
			return make_failure<filesystem_error>(stat_failed {});
		}

		if (metadata.st_size < 0) {
			return make_failure<filesystem_error>(negative_file_size {});
		}

		static_assert(sizeof(metadata.st_size) <= sizeof(std::size_t));
		std::size_t const size { static_cast<std::size_t>(metadata.st_size) };

		return make_success(size);
	}

	auto try_read_text_file_native(ffi_string<char> const &path) -> filesystem_result<string>
	{
		return try_make_file_reader_native(path)
			.take_success_then([](file_reader file) {
				return file.try_read_text();
			});
	}

	auto try_read_data_file_native(ffi_string<char> const &path) -> filesystem_result<heap_buffer<std::byte>>
	{
		return try_make_file_reader_native(path)
			.take_success_then([](file_reader file) {
				return file.try_read_data();
			});
	}

	auto try_create_directory_native(ffi_string<char> const &path) -> filesystem_result<none>
	{
		// TODO: add an API for this information
		constexpr ::mode_t PERMISSION_BITS {
			S_IRUSR |
			S_IWUSR |
			S_IXUSR |
			S_IRGRP |
			S_IXGRP |
			S_IROTH |
			S_IXOTH
		};

		errno = 0;
		int const mkdir_status { ::mkdir(path.data(), PERMISSION_BITS) };

		if (mkdir_status < 0) {
			return make_failure<filesystem_error>(mkdir_failed {});
		}

		return make_success<none>();
	}

	auto try_create_text_file_native(ffi_string<char> const &path, string_view const text) -> filesystem_result<none>
	{
		return try_make_file_writer_native(path, file_creation_mode::create)
			.take_success_then([&text](file_writer writer) {
				return writer.try_write_text(text);
			});
	}

	auto try_create_data_file_native(ffi_string<char> const &path, immutable_view<std::byte> const &data) -> filesystem_result<none>
	{
		return try_make_file_writer_native(path, file_creation_mode::create)
			.take_success_then([&data](file_writer writer) {
				return writer.try_write_data(data);
			});
	}

	auto try_overwrite_text_file_native(ffi_string<char> const &path, string_view const text) -> filesystem_result<none>
	{
		return try_make_file_writer_native(path, file_creation_mode::overwrite)
			.take_success_then([&text](file_writer writer) {
				return writer.try_write_text(text);
			});
	}

	auto try_overwrite_data_file_native(ffi_string<char> const &path, immutable_view<std::byte> const &data) -> filesystem_result<none>
	{
		return try_make_file_writer_native(path, file_creation_mode::overwrite)
			.take_success_then([&data](file_writer writer) {
				return writer.try_write_data(data);
			});
	}

	auto try_delete_directory_recursive_native(ffi_string<char> const &path) -> filesystem_result<none>
	{
		CRUCIBLE_TRY_BIND(auto, iterator,
			try_make_directory_list_iterator_native(path));

		CRUCIBLE_TRY_BIND(auto, entries,
			make_iterator_pipeline(std::move(iterator))
			.try_materialize<heap_buffer<native_directory_entry>>());

		CRUCIBLE_TRY(
			iterate(entries)
			.map([&path](native_directory_entry const &entry) {
					ffi_string<char> const path_to_entry = path + "/" + entry.name;

					if (entry.type == file_type::directory) {
						return try_delete_directory_recursive_native(path_to_entry);
					}

					return try_delete_file_native(path_to_entry);
			})
			.try_consume()
		);

		return try_delete_directory_native(path);
	}

	auto try_delete_directory_native(ffi_string<char> const &path) -> filesystem_result<none>
	{
		errno = 0;
		int const rmdir_status { ::rmdir(path.data()) };

		if (rmdir_status < 0) {
			return make_failure<filesystem_error>(rmdir_failed {});
		}

		return make_success<none>();
	}

	auto try_delete_file_native(ffi_string<char> const &path) -> filesystem_result<none>
	{
		errno = 0;
		int const unlink_status { ::unlink(path.data()) };

		if (unlink_status < 0) {
			return make_failure<filesystem_error>(unlink_failed {});
		}

		return make_success<none>();
	}

	// Platform-neutral path API -------------------

	directory_list_iterator::directory_list_iterator(native_directory_list_iterator native_iterator) :
		my_native_iterator { std::move(native_iterator) }
	{}

	auto directory_list_iterator::advance() -> std::optional<filesystem_result<directory_entry>>
	{
		auto const native_result { my_native_iterator.advance() };

		if (native_result == std::nullopt)
		{
			return std::nullopt;
		}

		return native_result
			.value()
			.map_success([](native_directory_entry const &native_entry) {
				directory_entry entry;
				entry.name = string { native_entry.name.data(), native_entry.name.size() };
				entry.type = native_entry.type;
				return entry;
			});
	}

	file_reader::file_reader(std::unique_ptr<file_reader_data> data) :
		my_data { std::move(data) }
	{}

	file_reader::file_reader(file_reader &&that) :
		my_data { std::move(that.my_data) }
	{}

	file_reader::~file_reader()
	{
		if (my_data) {
			CRUCIBLE_ASSERT_GE(my_data->file_descriptor, 0);

			errno = 0;
			::close(my_data->file_descriptor);
		}
	}

	auto file_reader::operator=(file_reader &&that) -> file_reader &
	{
		if (my_data) {
			CRUCIBLE_ASSERT_GE(my_data->file_descriptor, 0);

			errno = 0;
			::close(my_data->file_descriptor);
		}

		my_data = std::move(that.my_data);
		return *this;
	}

	auto file_reader::try_read_size() -> filesystem_result<std::size_t>
	{
		CRUCIBLE_ASSERT_NE(my_data, nullptr);
		CRUCIBLE_ASSERT_GE(my_data->file_descriptor, 0);

		struct ::stat metadata {};

		errno = 0;
		int const fstat_status { ::fstat(my_data->file_descriptor, &metadata) };

		if (fstat_status < 0) {
			return make_failure<filesystem_error>(stat_failed {});
		}

		if (metadata.st_size < 0) {
			return make_failure<filesystem_error>(negative_file_size {});
		}

		static_assert(sizeof(metadata.st_size) <= sizeof(std::size_t));
		std::size_t const size { static_cast<std::size_t>(metadata.st_size) };

		return make_success(size);
	}

	auto file_reader::try_read_text() -> filesystem_result<string>
	{
		CRUCIBLE_ASSERT_NE(my_data, nullptr);
		CRUCIBLE_ASSERT_GE(my_data->file_descriptor, 0);

		return try_read_data()
			.map_success([](heap_buffer<std::byte> const &data) {
				auto text { make_heap_buffer<char>(data.size()) };
				std::memcpy(text.data(), data.data(), data.size());

				return string { std::move(text) };
			});
	}

	auto file_reader::try_read_data() -> filesystem_result<heap_buffer<std::byte>>
	{
		CRUCIBLE_ASSERT_NE(my_data, nullptr);
		CRUCIBLE_ASSERT_GE(my_data->file_descriptor, 0);

		return try_read_size()
			.take_success_then([this](std::size_t const size) -> filesystem_result<heap_buffer<std::byte>> {
				std::size_t bytes_read { 0 };

				heap_buffer<std::byte> buffer { size };
				int read_status { 0 };

				// ::read() is allowed to not read the whole buffer, so we do it in a loop until we're sure we're done
				do {
					errno = 0;
					read_status = ::read(my_data->file_descriptor, buffer.data() + bytes_read, size - bytes_read);

					if (read_status > 0) {
						bytes_read += read_status;
					}
				} while (bytes_read < size && read_status > 0);

				if (read_status < 0) {
					return make_failure<filesystem_error>(read_failed {});
				}

				if (bytes_read < size) {
					return make_failure<filesystem_error>(incomplete_read {});
				}

				return make_success(std::move(buffer));
			});
	}

	file_writer::file_writer(std::unique_ptr<file_writer_data> data) :
		my_data { std::move(data) }
	{}

	file_writer::file_writer(file_writer &&that) :
		my_data { std::move(that.my_data) }
	{}

	file_writer::~file_writer()
	{
		if (my_data) {
			CRUCIBLE_ASSERT_GE(my_data->file_descriptor, 0);

			errno = 0;
			::close(my_data->file_descriptor);
		}
	}

	auto file_writer::operator=(file_writer &&that) -> file_writer &
	{
		if (my_data) {
			CRUCIBLE_ASSERT_GE(my_data->file_descriptor, 0);

			errno = 0;
			::close(my_data->file_descriptor);
		}

		my_data = std::move(that.my_data);
		return *this;
	}

	auto file_writer::try_write_text(string_view const text) -> filesystem_result<none>
	{
		return try_write_data(view_representation(text.view_data()));
	}

	auto file_writer::try_write_data(immutable_view<std::byte> const &data) -> filesystem_result<none>
	{
		CRUCIBLE_ASSERT_NE(my_data, nullptr);
		CRUCIBLE_ASSERT_GE(my_data->file_descriptor, 0);

		std::size_t total_bytes_written { 0 };
		int write_status { 0 };

		// ::write() is allowed to not write the full contents, so we do it in a loop until we're sure we're done
		do {
			errno = 0;
			write_status = ::write(my_data->file_descriptor, data.data() + total_bytes_written, data.size() - total_bytes_written);

			if (write_status > 0) {
				total_bytes_written += write_status;
			}
		} while (total_bytes_written < data.size() && write_status > 0);

		if (write_status < 0) {
			return make_failure<filesystem_error>(write_failed {});
		}

		if (total_bytes_written < data.size()) {
			return make_failure<filesystem_error>(incomplete_write {});
		}

		return make_success<none>();
	}

	auto try_make_directory_list_iterator(string_view const path) -> filesystem_result<directory_list_iterator>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };

		return try_make_directory_list_iterator_native(ffi_path)
			.map_success([](native_directory_list_iterator native_iterator) {
				return directory_list_iterator { std::move(native_iterator) };
			});
	}

	auto try_make_file_reader(string_view const path) -> filesystem_result<file_reader>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_make_file_reader_native(ffi_path);
	}

	auto try_make_file_writer(string_view const path, file_creation_mode const mode) -> filesystem_result<file_writer>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_make_file_writer_native(ffi_path, mode);
	}

	auto try_read_file_type(string_view const path) -> filesystem_result<file_type>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_read_file_type_native(ffi_path);
	}

	auto try_read_directory_list(string_view const path) -> filesystem_result<heap_buffer<directory_entry>>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_make_directory_list_iterator(path)
			.take_success_then([](directory_list_iterator iterator) {
				return make_iterator_pipeline(std::move(iterator))
					.try_materialize<heap_buffer<directory_entry>>();
			});
	}

	auto try_read_file_size(string_view const path) -> filesystem_result<std::size_t>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_read_file_size_native(ffi_path);
	}

	auto try_read_text_file(string_view const path) -> filesystem_result<string>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_read_text_file_native(ffi_path);
	}

	auto try_read_data_file(string_view const path) -> filesystem_result<heap_buffer<std::byte>>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_read_data_file_native(ffi_path);
	}

	auto try_create_directory(string_view const path) -> filesystem_result<none>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_create_directory_native(ffi_path);
	}

	auto try_create_text_file(string_view const path, string_view const text) -> filesystem_result<none>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_create_text_file_native(ffi_path, text);
	}

	auto try_create_data_file(string_view const path, immutable_view<std::byte> const &data) -> filesystem_result<none>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_create_data_file_native(ffi_path, data);
	}

	auto try_overwrite_text_file(string_view const path, string_view const text) -> filesystem_result<none>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_overwrite_text_file_native(ffi_path, text);
	}

	auto try_overwrite_data_file(string_view const path, immutable_view<std::byte> const &data) -> filesystem_result<none>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_overwrite_data_file_native(ffi_path, data);
	}

	auto try_delete_directory_recursive(string_view const path) -> filesystem_result<none>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_delete_directory_recursive_native(ffi_path);
	}

	auto try_delete_directory(string_view const path) -> filesystem_result<none>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_delete_directory_native(ffi_path);
	}

	auto try_delete_file(string_view const path) -> filesystem_result<none>
	{
		ffi_string<char> const ffi_path { path.data(), path.size() };
		return try_delete_file_native(ffi_path);
	}
}