Echo Writes Code

windows_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
#include "crucible/core/filesystem.inl"

#include <cstdint>
#include <limits>
#include <memory>
#include <utility>

#include <Windows.h>

#include "crucible/core/iterators.inl"

namespace crucible::core
{
  // Windows native path API ---------------------

  struct Native_Directory_List_Iterator_Data
  {
    FFI_String<wchar_t> pattern {};

    ::HANDLE handle { INVALID_HANDLE_VALUE };

    ::WIN32_FIND_DATAW current {};

    bool is_first { true };

    bool is_done { false };
  };

  struct File_Reader_Data
  {
    ::HANDLE handle { INVALID_HANDLE_VALUE };
  };

  struct File_Writer_Data
  {
    ::HANDLE handle { INVALID_HANDLE_VALUE };
  };

  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_CORE_ASSERT_NE(my_data->handle, INVALID_HANDLE_VALUE);

      ::SetLastError(0);
      ::FindClose(my_data->handle);
    }
  }

  auto Native_Directory_List_Iterator::operator=(Native_Directory_List_Iterator &&that) -> Native_Directory_List_Iterator &
  {
    if (my_data) {
      CRUCIBLE_CORE_ASSERT_NE(my_data->handle, INVALID_HANDLE_VALUE);

      ::SetLastError(0);
      ::FindClose(my_data->handle);
    }

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

  auto Native_Directory_List_Iterator::advance() -> std::optional<Filesystem_Result<FFI_String<wchar_t>>>
  {
    // Moved-from or no matching files
    if (my_data == nullptr) {
      return std::nullopt;
    }

    // Already finished
    if (my_data->is_done) {
      return std::nullopt;
    }

    // Either `my_data` should be `nullptr` or `my_data->handle` should be valid by this point
    CRUCIBLE_CORE_ASSERT_NE(my_data->handle, INVALID_HANDLE_VALUE);

    // Trick to avoid duplicating code in the case where `is_first` is `false`: we would need to
    // call `::FindFirstFileW()` once to prime the loop, but since we're skipping `L"."` and `L".."`
    // we can just initialize `filename` to one of those values to get one guaranteed free loop
    FFI_String<wchar_t> filename { L"." };

    if (my_data->is_first) {
      my_data->is_first = false;
      filename = my_data->current.cFileName;
    }

    while (filename == L"." || filename == L"..") {
      ::SetLastError(0);
      if (::FindNextFileW(my_data->handle, &my_data->current) == 0) {
        if (::GetLastError() == ERROR_NO_MORE_FILES) {
          my_data->is_done = true;
          return std::nullopt;
        } else {
          return make_failure<Filesystem_Error>(FindNextFileW_Failed {});
        }
      }

      filename = my_data->current.cFileName;
    }

    return filename;
  }

  auto try_make_directory_list_iterator_native(FFI_String<wchar_t> const &path) -> Filesystem_Result<Native_Directory_List_Iterator>
  {
    auto data { std::make_unique<Native_Directory_List_Iterator_Data>() };
    data->pattern = path + L"\\*";

    ::SetLastError(0);
    data->handle = ::FindFirstFileW(data->pattern.data(), &data->current);

    if (data->handle == INVALID_HANDLE_VALUE) {
      if (::GetLastError() == ERROR_FILE_NOT_FOUND) {
        // Pattern didn't match anything, but it's not an error
        return make_success<Native_Directory_List_Iterator>(nullptr);
      } else {
        return make_failure<Filesystem_Error>(FindFirstFileW_Failed {});
      }
    }

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

  auto try_make_file_reader_native(FFI_String<wchar_t> const &path) -> Filesystem_Result<File_Reader>
  {
    auto data { std::make_unique<File_Reader_Data>() };

    ::SetLastError(0);
    data->handle = ::CreateFileW(path.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)

    if (data->handle == INVALID_HANDLE_VALUE) {
      return make_failure<Filesystem_Error>(CreateFileW_Failed {});
    }

    return File_Reader { std::move(data) };
  }

  auto try_make_file_writer_native(FFI_String<wchar_t> const &path, File_Creation_Mode const mode) -> Filesystem_Result<File_Reader>
  {
    ::DWORD access_mode { 0 };
    ::DWORD share_mode { 0 };
    ::DWORD create_mode { 0 };

    switch (mode) {
    case File_Creation_Mode::Create:
      access_mode = GENERIC_WRITE;
      share_mode = FILE_SHARE_WRITE;
      create_mode = CREATE_NEW;
      break;

    case File_Creation_Mode::Overwrite:
      access_mode = GENERIC_WRITE;
      share_mode = FILE_SHARE_WRITE;
      create_mode = CREATE_ALWAYS;
      break;
    };

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

    ::SetLastError(0);
    data->handle = ::CreateFileW(path.data(), access_mode, share_mode, nullptr, create_mode, FILE_ATTRIBUTE_NORMAL, nullptr);

    if (data->handle == INVALID_HANDLE_VALUE) {
      return make_failure<Filesystem_Error>(CreateFileW_Failed {});
    }

    return File_Writer { std::move(data) };
  }

  auto try_read_file_type_native(FFI_String<wchar_t> const &path) -> Filesystem_Result<File_Type>
  {
    ::SetLastError(0);
    ::DWORD const attributes { ::GetFileAttributesW(path.data()) };

    if (attributes == INVALID_FILE_ATTRIBUTES) {
      return make_failure<Filesystem_Error>(GetFileAttributesW_Failed {});
    }

    if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
      return make_success(File_Type::Directory);
    }

    // We could check for `FILE_ATTRIBUTE_NORMAL`, but `File_Type` has no cases besides `Normal`
    return make_success(File_Type::Normal);
  }

  auto try_read_directory_list_native(FFI_String<wchar_t> const &path) -> Filesystem_Result<Heap_Buffer<FFI_String<wchar_t>>>
  {
    return make_pipeline(Native_Directory_List_Iterator { path })
      .try_materialize<Heap_Buffer<FFI_String<wchar_t>>();
  }

  auto try_read_file_size_native(FFI_String<wchar_t> const &path) -> Filesystem_Result<std::size_t>
  {
    return try_open_file_native(path)
      .take_success_then([](File_Reader const &file) {
          return file.read_size();
      });
  }

  auto try_read_text_file_native(FFI_String<wchar_t> const &path) -> Filesystem_Result<String>
  {
    return try_make_file_reader_native(path)
      .take_success_then([](File_Reader const &file) {
        return file.try_read_text();
      });
  }

  auto try_read_data_file_native(FFI_String<wchar_t> const &path) -> Filesystem_Result<Heap_Buffer<std::byte>>
  {
    return try_make_file_reader_native(path)
      .take_success_then([](File_Reader const &file) {
        return file.try_read_data();
      });
  }

  auto try_create_directory_native(FFI_String<wchar_t> const &path) -> Filesystem_Result<None>
  {
    ::SetLastError(0);
    bool const succeeded { ::CreateDirectoryW(path.data(), nullptr) != 0 };

    if (!succeeded) {
      return make_failure<Filesystem_Error>(CreateDirectoryW_Failed {});
    }

    return make_success(make_none());
  }

  auto try_create_text_file_native(FFI_String<wchar_t> 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 const &writer) {
        return writer.try_write_text(text);
      });
  }

  auto try_create_data_file_native(FFI_String<wchar_t> 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 const &file) {
        return writer.try_write_data(data);
      });
  }

  auto try_overwrite_text_file_native(FFI_String<wchar_t> 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 const &writer) {
        return writer.try_write_text(text);
      });
  }

  auto try_overwrite_data_file_native(FFI_String<wchar_t> 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 const &writer) {
        return writer.try_write_data(data);
      });
  }

  auto try_delete_directory_native(FFI_String<wchar_t> const &path) -> Filesystem_Result<None>
  {
    ::SetLastError(0);
    bool const succeeded { ::RemoveDirectoryW(path.data()) != 0 };

    if (!succeeded) {
      return make_failure<Filesystem_Error>(RemoveDirectoryW_Failed {});
    }

    return make_success<None>();
  }

  auto try_delete_file_native(FFI_String<wchar_t> const &path) -> Filesystem_Result<None>
  {
    ::SetLastError(0);
    bool const succeeded { ::DeleteFileW(path.data()) != 0 };

    if (!succeeded) {
      return make_failure<Filesystem_Error>(DeleteFileW_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<String>>
  {
    auto native_result { my_native_iterator.advance() };

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

    return native_result
      .value()
      .take_success_then(bulk_transcode_wide_to_utf8);
  }

  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_CORE_ASSERT_NE(my_data->handle, INVALID_HANDLE_VALUE);

      ::SetLastError(0);
      ::CloseHandle(my_data->handle);
    }
  }

  auto File_Reader::operator=(File_Reader &&that) -> File_Reader &
  {
    if (my_data) {
      CRUCIBLE_CORE_ASSERT_NE(my_data->handle, INVALID_HANDLE_VALUE);

      ::SetLastError(0);
      ::CloseHandle(my_data->handle);
    }

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

  auto File_Reader::try_read_size() -> Filesystem_Result<std::size_t>
  {
    CRUCIBLE_CORE_ASSERT_NE(my_data, nullptr);
    CRUCIBLE_CORE_ASSERT_NE(my_data->handle, INVALID_HANDLE_VALUE);

    std::size_t file_size { 0 };

    {
      ::LARGE_INTEGER raw_size {};

      ::SetLastError(0);
      bool const succeeded { ::GetFileSizeEx(my_data->handle.value(), &raw_size) != 0 };

      if (!succeeded) {
        return make_failure<Filesystem_Error>(GetFileSizeEx_Failed {});
      }

      static_assert(sizeof(raw_size.QuadPart) >= sizeof(std::uint64_t));
      static_assert(sizeof(raw_size.QuadPart) <= sizeof(file_size));

      if (raw_size.QuadPart < 0) {
        return make_failure<Filesystem_Error>(Negative_File_Size {});
      }

      file_size = raw_size.QuadPart;
    }

    return make_success(file_size);
  }

  auto File_Reader::try_read_text() -> Filesystem_Result<String>
  {
    return try_read_data()
      .map_success([](Heap_Buffer<std::byte> const &data) {
        return String { data.data(), data.size() };
      });
  }

  auto File_Reader::try_read_data() -> Filesystem_Result<Heap_Buffer<std::byte>>
  {
    CRUCIBLE_CORE_ASSERT_NE(my_data, nullptr);
    CRUCIBLE_CORE_ASSERT_NE(my_data->handle, INVALID_HANDLE_VALUE);

    return try_read_size()
      .take_success_then([](std::size_t const size) {
        HeapBuffer<std::byte> buffer { size };
        std::size_t total_bytes_read { 0 };

        // ::ReadFile() is allowed to not read the whole buffer, so we do it in a loop until we're sure we're done
        do {
          constexpr ::DWORD DWORD_MAX { std::numeric_limits<::DWORD>::max() };
          std::size_t const remaining_size { size - total_bytes_read };

          ::DWORD const intended_read_size { remaining_size >= DWORD_MAX ? DWORD_MAX : static_cast<::DWORD>(remaining_size) };
          ::DWORD bytes_actually_read { 0 };

          ::SetLastError(0);
          ::BOOL const succeeded {
            ::ReadFile(my_data->handle.value(), buffer.data() + total_bytes_read, intended_read_size, &bytes_actually_read, nullptr)
          };

          if (!succeeded) {
            break;
          }

          total_bytes_read += bytes_actually_read;
        } while (total_bytes_read < size);

        if (total_bytes_read < size) {
          return make_failure<Filesystem_Error>(ReadFile_Failed {});
        }

        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_CORE_ASSERT_NE(my_data->handle, INVALID_HANDLE_VALUE);

      ::SetLastError(0);
      ::CloseHandle(my_data->handle);
    }
  }

  auto File_Writer::operator=(File_Writer &&that) -> File_Writer &
  {
    if (my_data) {
      CRUCIBLE_CORE_ASSERT_NE(my_data->handle, INVALID_HANDLE_VALUE);

      ::SetLastError(0);
      ::CloseHandle(my_data->handle);
    }

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

  auto File_Writer::try_write_text(String_View const &text) -> Filesystem_Result<None>
  {
    Immutable_View<std::byte> const data { text.data(), text.size() };
    return try_write_data(data);
  }

  auto File_Writer::try_write_data(Immutable_View<std::byte> const &data) -> Filesystem_Result<None>
  {
    CRUCIBLE_CORE_ASSERT_NE(my_data, nullptr);
    CRUCIBLE_CORE_ASSERT_NE(my_data->handle, INVALID_HANDLE_VALUE);

    std::size_t total_bytes_written { 0 };

    // ::WriteFile() is allowed to not write the whole buffer, so we do it in a loop until we're sure we're done
    do {
      constexpr ::DWORD DWORD_MAX { std::numeric_limits<::DWORD>::max() };
      std::size_t const remaining_size { data.size() - total_bytes_written };

      ::DWORD const intended_write_size { remaining_size >= DWORD_MAX ? DWORD_MAX : static_cast<::DWORD>(remaining_size) };
      ::DWORD bytes_actually_written { 0 };

      ::SetLastError(0);
      ::BOOL const succeeded {
        ::WriteFile(my_data->handle, data.data() + total_bytes_written, intended_write_size, &bytes_actually_written, nullptr)
      };

      if (!succeeded) {
        break;
      }

      total_bytes_written += bytes_actually_written;
    } while (total_bytes_written < data.size());

    if (total_bytes_written < data.size()) {
      return make_failure<Filesystem_Error>(WriteFile_Failed {});
    }

    return make_success<None>();
  }

  auto try_make_directory_list_iterator(String_View const &path) -> Filesystem_Result<Directory_List_Iterator>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_make_directory_list_iterator_native)
      .map([](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>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_make_file_reader_native);
  }

  auto try_make_file_writer(String_View const &path, File_Creation_Mode const mode) -> Filesystem_Result<File_Writer>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then([](FFI_String<wchar_t> const &wide_path) {
        return try_make_file_writer_native(wide_path, mode);
      });
  }

  auto try_read_file_type(String_View const &path) -> Filesystem_Result<File_Type>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_read_file_type_native);
  }

  auto try_read_directory_list(String_View const &path) -> Filesystem_Result<Heap_Buffer<String>>
  {
    return make_pipeline(try_make_directory_list_iterator(path))
      .try_materialize<Heap_Buffer<String>>();
  }

  auto try_read_file_size(String_View const &path) -> Filesystem_Result<std::size_t>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_read_file_size_native);
  }

  auto try_read_text_file(String_View const &path) -> Filesystem_Result<String>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_read_text_file_native);
  }

  auto try_read_data_file(String_View const &path) -> Filesystem_Result<Heap_Buffer<std::byte>>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_read_data_file_native);
  }

  auto try_create_directory(String_View const &path) -> Filesystem_Result<None>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_create_directory_native);
  }

  auto try_create_text_file(String_View const &path, String_View const &text) -> Filesystem_Result<None>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_create_text_file_native);
  }

  auto try_create_data_file(String_View const &path, Immutable_View<std::byte> const &data) -> Filesystem_Result<None>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_create_data_file_native);
  }

  auto try_overwrite_text_file(String_View const &path, String_View const &text) -> Filesystem_Result<None>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_overwrite_text_file_native);
  }

  auto try_overwrite_data_file(String_View const &path, Immutable_View<std::byte> const &data) -> Filesystem_Result<None>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_overwrite_data_file_native);
  }

  auto try_delete_directory(String_View const &path) -> Filesystem_Result<None>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_delete_directory_native);
  }

  auto try_delete_file(String_View const &path) -> Filesystem_Result<None>
  {
    return bulk_transcode_utf8_to_wide(path)
      .take_success_then(try_delete_file_native);
  }
}