-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathfilesystem
4474 lines (3714 loc) · 189 KB
/
filesystem
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// filesystem standard header
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef _FILESYSTEM_
#define _FILESYSTEM_
#include <yvals_core.h>
#if _STL_COMPILER_PREPROCESSOR
#if !_HAS_CXX17
_EMIT_STL_WARNING(STL4038, "The contents of <filesystem> are available only with C++17 or later.");
#else // ^^^ !_HAS_CXX17 / _HAS_CXX17 vvv
#include <algorithm>
#include <chrono>
#include <cwchar>
#include <iomanip>
#include <locale>
#include <memory>
#include <system_error>
#include <utility>
#include <vector>
#include <xfilesystem_abi.h>
#include <xstring>
#if _HAS_CXX20
#include <compare>
#endif // _HAS_CXX20
#pragma pack(push, _CRT_PACKING)
#pragma warning(push, _STL_WARNING_LEVEL)
#pragma warning(disable : _STL_DISABLED_WARNINGS)
_STL_DISABLE_CLANG_WARNINGS
#pragma push_macro("new")
#undef new
_STD_BEGIN
namespace filesystem {
_NODISCARD inline wstring _Convert_narrow_to_wide(const __std_code_page _Code_page, const string_view _Input) {
wstring _Output;
if (!_Input.empty()) {
if (!_STD _In_range<int>(_Input.size())) {
_Throw_system_error(errc::invalid_argument);
}
const int _Len = _Check_convert_result(__std_fs_convert_narrow_to_wide(
_Code_page, _Input.data(), static_cast<int>(_Input.size()), nullptr, 0));
_Output.resize(static_cast<size_t>(_Len));
(void) _Check_convert_result(__std_fs_convert_narrow_to_wide(
_Code_page, _Input.data(), static_cast<int>(_Input.size()), _Output.data(), _Len));
}
return _Output;
}
// More lenient version of _Convert_wide_to_narrow: Instead of failing on non-representable characters,
// replace them with a replacement character.
template <class _Traits, class _Alloc>
_NODISCARD basic_string<typename _Traits::char_type, _Traits, _Alloc> _Convert_wide_to_narrow_replace_chars(
const __std_code_page _Code_page, const wstring_view _Input, const _Alloc& _Al) {
basic_string<typename _Traits::char_type, _Traits, _Alloc> _Output(_Al);
if (!_Input.empty()) {
if (!_STD _In_range<int>(_Input.size())) {
_Throw_system_error(errc::invalid_argument);
}
const int _Len = _Check_convert_result(__std_fs_convert_wide_to_narrow_replace_chars(
_Code_page, _Input.data(), static_cast<int>(_Input.size()), nullptr, 0));
_Output.resize(static_cast<size_t>(_Len));
const auto _Data_as_char = reinterpret_cast<char*>(_Output.data());
(void) _Check_convert_result(__std_fs_convert_wide_to_narrow_replace_chars(
_Code_page, _Input.data(), static_cast<int>(_Input.size()), _Data_as_char, _Len));
}
return _Output;
}
_NODISCARD inline wstring _Convert_utf32_to_wide(const u32string_view _Input) {
wstring _Output;
_Output.reserve(_Input.size()); // ideal when surrogate pairs are uncommon
for (const auto& _Code_point : _Input) {
if (_Code_point <= 0xD7FFU) {
_Output.push_back(static_cast<wchar_t>(_Code_point));
} else if (_Code_point <= 0xDFFFU) {
_Throw_system_error(errc::invalid_argument);
} else if (_Code_point <= 0xFFFFU) {
_Output.push_back(static_cast<wchar_t>(_Code_point));
} else if (_Code_point <= 0x10FFFFU) {
_Output.push_back(static_cast<wchar_t>(0xD7C0U + (_Code_point >> 10)));
_Output.push_back(static_cast<wchar_t>(0xDC00U + (_Code_point & 0x3FFU)));
} else {
_Throw_system_error(errc::invalid_argument);
}
}
return _Output;
}
template <class _Traits, class _Alloc>
_NODISCARD basic_string<char32_t, _Traits, _Alloc> _Convert_wide_to_utf32(
const wstring_view _Input, const _Alloc& _Al) {
basic_string<char32_t, _Traits, _Alloc> _Output(_Al);
_Output.reserve(_Input.size()); // ideal when surrogate pairs are uncommon
const wchar_t* _First = _Input.data();
const wchar_t* const _Last = _First + _Input.size();
for (; _First != _Last; ++_First) {
if (*_First <= 0xD7FFU) {
_Output.push_back(*_First);
} else if (*_First <= 0xDBFFU) { // found leading surrogate
const char32_t _Leading = *_First; // widen for later math
++_First;
if (_First == _Last) { // missing trailing surrogate
_Throw_system_error(errc::invalid_argument);
}
const char32_t _Trailing = *_First; // widen for later math
if (0xDC00U <= _Trailing && _Trailing <= 0xDFFFU) { // valid trailing surrogate
_Output.push_back(0xFCA02400U + (_Leading << 10) + _Trailing);
} else { // invalid trailing surrogate
_Throw_system_error(errc::invalid_argument);
}
} else if (*_First <= 0xDFFFU) { // found trailing surrogate by itself, invalid
_Throw_system_error(errc::invalid_argument);
} else {
_Output.push_back(*_First);
}
}
return _Output;
}
template <class _Traits, class _Alloc, class _EcharT = typename _Traits::char_type>
_NODISCARD basic_string<_EcharT, _Traits, _Alloc> _Convert_wide_to(const wstring_view _Input, const _Alloc& _Al) {
if constexpr (is_same_v<_EcharT, char>) {
return _Convert_wide_to_narrow<_Traits>(__std_fs_code_page(), _Input, _Al);
}
#ifdef __cpp_char8_t
else if constexpr (is_same_v<_EcharT, char8_t>) {
return _Convert_wide_to_narrow<_Traits>(__std_code_page::_Utf8, _Input, _Al);
}
#endif // defined(__cpp_char8_t)
else if constexpr (is_same_v<_EcharT, char32_t>) {
return _Convert_wide_to_utf32<_Traits>(_Input, _Al);
} else { // wchar_t, char16_t
return basic_string<_EcharT, _Traits, _Alloc>(_Input.data(), _Input.data() + _Input.size(), _Al);
}
}
template <class _Ty, class = void>
constexpr bool _Is_Source_impl = false;
template <class _Ty>
constexpr bool _Is_Source_impl<_Ty, void_t<typename iterator_traits<_Ty>::value_type>> =
_Is_EcharT<typename iterator_traits<_Ty>::value_type>;
template <class _Ty>
constexpr bool _Is_Source = _Is_Source_impl<decay_t<_Ty>>;
_EXPORT_STD class path;
template <>
inline constexpr bool _Is_Source<path> = false; // to avoid constraint recursion via the converting constructor and
// iterator_traits when determining if path is copyable.
template <class _Elem, class _Traits, class _Alloc>
constexpr bool _Is_Source<basic_string<_Elem, _Traits, _Alloc>> = _Is_EcharT<_Elem>;
template <class _Elem, class _Traits>
constexpr bool _Is_Source<basic_string_view<_Elem, _Traits>> = _Is_EcharT<_Elem>;
struct _Normal_conversion {};
struct _Utf8_conversion {};
// A "stringoid" is basic_string_view<_EcharT> or basic_string<_EcharT>.
template <class _Conversion>
_NODISCARD wstring _Convert_stringoid_to_wide(const string_view _Input, _Conversion) {
_STL_INTERNAL_STATIC_ASSERT(_Is_any_of_v<_Conversion, _Normal_conversion, _Utf8_conversion>);
if constexpr (is_same_v<_Conversion, _Normal_conversion>) {
return _Convert_narrow_to_wide(__std_fs_code_page(), _Input);
} else {
return _Convert_narrow_to_wide(__std_code_page::_Utf8, _Input);
}
}
template <class _Conversion>
_NODISCARD wstring _Convert_stringoid_to_wide(const wstring_view _Input, _Conversion) {
static_assert(
is_same_v<_Conversion, _Normal_conversion>, "invalid value_type, see N4950 [depr.fs.path.factory]/1");
return wstring{_Input};
}
#ifdef __cpp_char8_t
template <class _Conversion>
_NODISCARD wstring _Convert_stringoid_to_wide(const basic_string_view<char8_t> _Input, _Conversion) {
_STL_INTERNAL_STATIC_ASSERT(_Is_any_of_v<_Conversion, _Normal_conversion, _Utf8_conversion>);
const string_view _Input_as_char{reinterpret_cast<const char*>(_Input.data()), _Input.size()};
return _Convert_narrow_to_wide(__std_code_page::_Utf8, _Input_as_char);
}
#endif // defined(__cpp_char8_t)
template <class _Conversion>
_NODISCARD wstring _Convert_stringoid_to_wide(const u16string_view _Input, _Conversion) {
static_assert(
is_same_v<_Conversion, _Normal_conversion>, "invalid value_type, see N4950 [depr.fs.path.factory]/1");
return wstring{_Input.data(), _Input.data() + _Input.size()};
}
template <class _Conversion>
_NODISCARD wstring _Convert_stringoid_to_wide(const u32string_view _Input, _Conversion) {
static_assert(
is_same_v<_Conversion, _Normal_conversion>, "invalid value_type, see N4950 [depr.fs.path.factory]/1");
return _Convert_utf32_to_wide(_Input);
}
template <class _EcharT, class _Traits>
_NODISCARD auto _Stringoid_from_Source(const basic_string_view<_EcharT, _Traits>& _Source) {
return basic_string_view<_EcharT>(_Source.data(), _Source.size()); // erase mismatching _Traits
}
template <class _EcharT, class _Traits, class _Alloc>
_NODISCARD auto _Stringoid_from_Source(const basic_string<_EcharT, _Traits, _Alloc>& _Source) {
return basic_string_view<_EcharT>(_Source.data(), _Source.size()); // erase mismatching _Traits
}
template <class _Src>
_NODISCARD auto _Stringoid_from_Source(const _Src& _Source) {
using _EcharT = _Iter_value_t<decay_t<_Src>>;
if constexpr (is_pointer_v<_Unwrapped_unverified_t<const _Src&>>) {
return basic_string_view<_EcharT>(_Get_unwrapped_unverified(_Source));
} else if constexpr (is_pointer_v<_Unwrapped_t<const _Src&>>) {
const auto _Data = _Get_unwrapped(_Source);
auto _Next = _Source;
while (*_Next != _EcharT{}) {
++_Next;
}
return basic_string_view<_EcharT>(_Data, static_cast<size_t>(_Get_unwrapped(_Next) - _Data));
} else {
basic_string<_EcharT> _Str;
for (auto _Next = _Source; *_Next != _EcharT{}; ++_Next) {
_Str.push_back(*_Next);
}
return _Str;
}
}
#if _ITERATOR_DEBUG_LEVEL == 2
template <class _EcharT, size_t _SourceSize>
_NODISCARD basic_string_view<_EcharT> _Stringoid_from_Source(const _EcharT (&_Src)[_SourceSize]) {
for (size_t _Idx = 0;; ++_Idx) {
_STL_VERIFY(_Idx < _SourceSize, "path input not null terminated");
if (_Src[_Idx] == _EcharT{}) {
return basic_string_view<_EcharT>(_Src, _Idx);
}
}
}
#endif // _ITERATOR_DEBUG_LEVEL == 2
template <class _Src, class _Conversion = _Normal_conversion>
_NODISCARD wstring _Convert_Source_to_wide(const _Src& _Source, _Conversion _Tag = {}) {
return _Convert_stringoid_to_wide(_Stringoid_from_Source(_Source), _Tag);
}
template <class _InIt>
_NODISCARD auto _Stringoid_from_range(_InIt _First, _InIt _Last) {
_Adl_verify_range(_First, _Last);
const auto _UFirst = _Get_unwrapped(_First);
const auto _ULast = _Get_unwrapped(_Last);
if constexpr (is_pointer_v<decltype(_UFirst)>) {
return basic_string_view<_Iter_value_t<_InIt>>(_UFirst, static_cast<size_t>(_ULast - _UFirst));
} else {
return basic_string<_Iter_value_t<_InIt>>(_UFirst, _ULast);
}
}
template <class _InIt, class _Conversion = _Normal_conversion>
_NODISCARD wstring _Convert_range_to_wide(_InIt _First, _InIt _Last, _Conversion _Tag = {}) {
return _Convert_stringoid_to_wide(_Stringoid_from_range(_First, _Last), _Tag);
}
_NODISCARD inline wstring _Convert_stringoid_with_locale_to_wide(const string_view _Input, const locale& _Loc) {
const auto& _Facet = _STD use_facet<codecvt<wchar_t, char, mbstate_t>>(_Loc);
wstring _Output(_Input.size(), L'\0'); // almost always sufficient
for (;;) {
mbstate_t _State{};
const char* const _From_begin = _Input.data();
const char* const _From_end = _From_begin + _Input.size();
const char* _From_next = nullptr;
wchar_t* const _To_begin = _Output.data();
wchar_t* const _To_end = _To_begin + _Output.size();
wchar_t* _To_next = nullptr;
const auto _Result = _Facet.in(_State, _From_begin, _From_end, _From_next, _To_begin, _To_end, _To_next);
if (_From_next < _From_begin || _From_next > _From_end || _To_next < _To_begin || _To_next > _To_end) {
_Throw_system_error(errc::invalid_argument);
}
switch (_Result) {
case codecvt_base::ok:
_Output.resize(static_cast<size_t>(_To_next - _To_begin));
return _Output;
case codecvt_base::partial:
// N4950 [locale.codecvt.virtuals]/5:
// "A return value of partial, if (from_next == from_end), indicates that either the
// destination sequence has not absorbed all the available destination elements,
// or that additional source elements are needed before another destination element can be produced."
if ((_From_next == _From_end && _To_next != _To_end) || _Output.size() > _Output.max_size() / 2) {
_Throw_system_error(errc::invalid_argument);
}
_Output.resize(_Output.size() * 2);
break; // out of switch, keep looping
case codecvt_base::error:
case codecvt_base::noconv:
default:
_Throw_system_error(errc::invalid_argument);
}
}
}
struct _Is_slash_oper { // predicate testing if input is a preferred-separator or fallback-separator
_NODISCARD _STATIC_CALL_OPERATOR constexpr bool operator()(const wchar_t _Ch) _CONST_CALL_OPERATOR {
return _Ch == L'\\' || _Ch == L'/';
}
};
inline constexpr _Is_slash_oper _Is_slash{};
template <class _Ty>
_NODISCARD _Ty _Unaligned_load(const void* _Ptr) { // load a _Ty from _Ptr
static_assert(is_trivial_v<_Ty>, "Unaligned loads require trivial types");
_Ty _Tmp;
_CSTD memcpy(&_Tmp, _Ptr, sizeof(_Tmp));
return _Tmp;
}
_NODISCARD inline bool _Is_drive_prefix(const wchar_t* const _First) {
// test if _First points to a prefix of the form X:
// pre: _First points to at least 2 wchar_t instances
// pre: Little endian
auto _Value = _Unaligned_load<unsigned int>(_First);
_Value &= 0xFFFF'FFDFu; // transform lowercase drive letters into uppercase ones
_Value -= (static_cast<unsigned int>(L':') << (sizeof(wchar_t) * CHAR_BIT)) | L'A';
return _Value < 26;
}
_NODISCARD inline bool _Has_drive_letter_prefix(const wchar_t* const _First, const wchar_t* const _Last) {
// test if [_First, _Last) has a prefix of the form X:
return _Last - _First >= 2 && _Is_drive_prefix(_First);
}
_NODISCARD inline const wchar_t* _Find_root_name_end(const wchar_t* const _First, const wchar_t* const _Last) {
// attempt to parse [_First, _Last) as a path and return the end of root-name if it exists; otherwise, _First
// This is the place in the generic grammar where library implementations have the most freedom.
// Below are example Windows paths, and what we've decided to do with them:
// * X:DriveRelative, X:\DosAbsolute
// We parse X: as root-name, if and only if \ is present we consider that root-directory
// * \RootRelative
// We parse no root-name, and \ as root-directory
// * \\server\share
// We parse \\server as root-name, \ as root-directory, and share as the first element in relative-path.
// Technically, Windows considers all of \\server\share the logical "root", but for purposes
// of decomposition we want those split, so that path{R"(\\server\share)"}.replace_filename("other_share")
// is \\server\other_share
// * \\?\device
// * \??\device
// * \\.\device
// CreateFile appears to treat these as the same thing; we will set the first three characters as root-name
// and the first \ as root-directory. Support for these prefixes varies by particular Windows version, but
// for the purposes of path decomposition we don't need to worry about that.
// * \\?\UNC\server\share
// MSDN explicitly documents the \\?\UNC syntax as a special case. What actually happens is that the device
// Mup, or "Multiple UNC provider", owns the path \\?\UNC in the NT namespace, and is responsible for the
// network file access. When the user says \\server\share, CreateFile translates that into
// \\?\UNC\server\share to get the remote server access behavior. Because NT treats this like any other
// device, we have chosen to treat this as the \\?\ case above.
if (_Last - _First < 2) {
return _First;
}
if (_Has_drive_letter_prefix(_First, _Last)) { // check for X: first because it's the most common root-name
return _First + 2;
}
if (!_Is_slash(_First[0])) { // all the other root-names start with a slash; check that first because
// we expect paths without a leading slash to be very common
return _First;
}
// $ means anything other than a slash, including potentially the end of the input
if (_Last - _First >= 4 && _Is_slash(_First[3]) && (_Last - _First == 4 || !_Is_slash(_First[4])) // \xx\$
&& ((_Is_slash(_First[1]) && (_First[2] == L'?' || _First[2] == L'.')) // \\?\$ or \\.\$
|| (_First[1] == L'?' && _First[2] == L'?'))) { // \??\$
return _First + 3;
}
if (_Last - _First >= 3 && _Is_slash(_First[1]) && !_Is_slash(_First[2])) { // \\server
return _STD find_if(_First + 3, _Last, _Is_slash);
}
// no match
return _First;
}
_NODISCARD inline wstring_view _Parse_root_name(const wstring_view _Str) {
// attempt to parse _Str as a path and return the root-name if it exists; otherwise, an empty view
const auto _First = _Str.data();
const auto _Last = _First + _Str.size();
return wstring_view(_First, static_cast<size_t>(_Find_root_name_end(_First, _Last) - _First));
}
_NODISCARD inline const wchar_t* _Find_relative_path(const wchar_t* const _First, const wchar_t* const _Last) {
// attempt to parse [_First, _Last) as a path and return the start of relative-path
return _STD find_if_not(_Find_root_name_end(_First, _Last), _Last, _Is_slash);
}
_NODISCARD inline wstring_view _Parse_root_directory(const wstring_view _Str) {
// attempt to parse _Str as a path and return the root-directory if it exists; otherwise, an empty view
const auto _First = _Str.data();
const auto _Last = _First + _Str.size();
const auto _Root_name_end = _Find_root_name_end(_First, _Last);
const auto _Relative_path = _STD find_if_not(_Root_name_end, _Last, _Is_slash);
return wstring_view(_Root_name_end, static_cast<size_t>(_Relative_path - _Root_name_end));
}
_NODISCARD inline wstring_view _Parse_root_path(const wstring_view _Str) {
// attempt to parse _Str as a path and return the root-path if it exists; otherwise, an empty view
const auto _First = _Str.data();
const auto _Last = _First + _Str.size();
return wstring_view(_First, static_cast<size_t>(_Find_relative_path(_First, _Last) - _First));
}
_NODISCARD inline wstring_view _Parse_relative_path(const wstring_view _Str) {
// attempt to parse _Str as a path and return the relative-path if it exists; otherwise, an empty view
const auto _First = _Str.data();
const auto _Last = _First + _Str.size();
const auto _Relative_path = _Find_relative_path(_First, _Last);
return wstring_view(_Relative_path, static_cast<size_t>(_Last - _Relative_path));
}
_NODISCARD inline wstring_view _Parse_parent_path(const wstring_view _Str) {
// attempt to parse _Str as a path and return the parent_path if it exists; otherwise, an empty view
const auto _First = _Str.data();
auto _Last = _First + _Str.size();
const auto _Relative_path = _Find_relative_path(_First, _Last);
// case 1: relative-path ends in a directory-separator, remove the separator to remove "magic empty path"
// for example: R"(/cat/dog/\//\)"
// case 2: relative-path doesn't end in a directory-separator, remove the filename and last directory-separator
// to prevent creation of a "magic empty path"
// for example: "/cat/dog"
while (_Relative_path != _Last && !_Is_slash(_Last[-1])) {
// handle case 2 by removing trailing filename, puts us into case 1
--_Last;
}
while (_Relative_path != _Last && _Is_slash(_Last[-1])) { // handle case 1 by removing trailing slashes
--_Last;
}
return wstring_view(_First, static_cast<size_t>(_Last - _First));
}
_NODISCARD inline const wchar_t* _Find_filename(const wchar_t* const _First, const wchar_t* _Last) {
// attempt to parse [_First, _Last) as a path and return the start of filename if it exists; otherwise, _Last
const auto _Relative_path = _Find_relative_path(_First, _Last);
while (_Relative_path != _Last && !_Is_slash(_Last[-1])) {
--_Last;
}
return _Last;
}
_NODISCARD inline wstring_view _Parse_filename(const wstring_view _Str) {
// attempt to parse _Str as a path and return the filename if it exists; otherwise, an empty view
const auto _First = _Str.data();
const auto _Last = _First + _Str.size();
const auto _Filename = _Find_filename(_First, _Last);
return wstring_view(_Filename, static_cast<size_t>(_Last - _Filename));
}
_NODISCARD constexpr const wchar_t* _Find_extension(const wchar_t* const _Filename, const wchar_t* const _Ads) {
// find dividing point between stem and extension in a generic format filename consisting of [_Filename, _Ads)
auto _Extension = _Ads;
if (_Filename == _Extension) { // empty path
return _Ads;
}
--_Extension;
if (_Filename == _Extension) {
// path is length 1 and either dot, or has no dots; either way, extension() is empty
return _Ads;
}
if (*_Extension == L'.') { // we might have found the end of stem
if (_Filename == _Extension - 1 && _Extension[-1] == L'.') { // dotdot special case
return _Ads;
} else { // x.
return _Extension;
}
}
while (_Filename != --_Extension) {
if (*_Extension == L'.') { // found a dot which is not in first position, so it starts extension()
return _Extension;
}
}
// if we got here, either there are no dots, in which case extension is empty, or the first element
// is a dot, in which case we have the leading single dot special case, which also makes extension empty
return _Ads;
}
_NODISCARD inline wstring_view _Parse_stem(const wstring_view _Str) {
// attempt to parse _Str as a path and return the stem if it exists; otherwise, an empty view
const auto _First = _Str.data();
const auto _Last = _First + _Str.size();
const auto _Filename = _Find_filename(_First, _Last);
const auto _Ads =
_STD find(_Filename, _Last, L':'); // strip alternate data streams in intra-filename decomposition
const auto _Extension = _Find_extension(_Filename, _Ads);
return wstring_view(_Filename, static_cast<size_t>(_Extension - _Filename));
}
_NODISCARD inline wstring_view _Parse_extension(const wstring_view _Str) {
// attempt to parse _Str as a path and return the extension if it exists; otherwise, an empty view
const auto _First = _Str.data();
const auto _Last = _First + _Str.size();
const auto _Filename = _Find_filename(_First, _Last);
const auto _Ads =
_STD find(_Filename, _Last, L':'); // strip alternate data streams in intra-filename decomposition
const auto _Extension = _Find_extension(_Filename, _Ads);
return wstring_view(_Extension, static_cast<size_t>(_Ads - _Extension));
}
_NODISCARD inline int _Range_compare(const wchar_t* const _Lfirst, const wchar_t* const _Llast,
const wchar_t* const _Rfirst, const wchar_t* const _Rlast) {
// 3 way compare [_Lfirst, _Llast) with [_Rfirst, _Rlast)
return _Traits_compare<char_traits<wchar_t>>(
_Lfirst, static_cast<size_t>(_Llast - _Lfirst), _Rfirst, static_cast<size_t>(_Rlast - _Rfirst));
}
_NODISCARD inline bool _Is_drive_prefix_with_slash_slash_question(const wstring_view _Text) {
// test if _Text starts with a \\?\X: prefix
return _Text.size() >= 6 && _Text._Starts_with(LR"(\\?\)"sv) && _Is_drive_prefix(_Text.data() + 4);
}
_NODISCARD inline bool _Is_dot_or_dotdot(const __std_fs_find_data& _Data) {
// tests if _File_name of __std_fs_find_data is . or ..
if (_Data._File_name[0] != L'.') {
return false;
}
const auto _Second_char = _Data._File_name[1];
if (_Second_char == 0) {
return true;
}
if (_Second_char != L'.') {
return false;
}
return _Data._File_name[2] == 0;
}
struct _Find_file_handle {
__std_fs_dir_handle _Handle = __std_fs_dir_handle::_Invalid;
_Find_file_handle() noexcept = default;
_Find_file_handle(_Find_file_handle&& _Rhs) noexcept
: _Handle(_STD exchange(_Rhs._Handle, __std_fs_dir_handle::_Invalid)) {}
_Find_file_handle& operator=(_Find_file_handle&& _Rhs) noexcept {
auto _Tmp = _STD exchange(_Rhs._Handle, __std_fs_dir_handle::_Invalid);
_Tmp = _STD exchange(_Handle, _Tmp);
__std_fs_directory_iterator_close(_Tmp);
return *this;
}
_NODISCARD __std_win_error _Open(const wchar_t* _Path_spec, __std_fs_find_data* _Results) noexcept {
return __std_fs_directory_iterator_open(_Path_spec, &_Handle, _Results);
}
~_Find_file_handle() noexcept {
__std_fs_directory_iterator_close(_Handle);
}
explicit operator bool() const noexcept {
return _Handle != __std_fs_dir_handle::_Invalid;
}
};
template <class _Base_iter>
class _Path_iterator;
_EXPORT_STD class path {
template <class _Base_iter>
friend class _Path_iterator;
friend inline path absolute(const path& _Input, error_code& _Ec);
friend inline __std_win_error _Canonical(path& _Result, const wstring& _Text);
friend inline path temp_directory_path(error_code& _Ec);
friend inline path current_path(error_code& _Ec);
friend inline void current_path(const path& _To);
friend inline void current_path(const path& _To, error_code& _Ec) noexcept;
friend inline __std_win_error _Read_symlink(const path& _Symlink_path, path& _Result);
public:
using value_type = wchar_t;
using string_type = _STD wstring;
static constexpr wchar_t preferred_separator = L'\\';
enum format { auto_format, native_format, generic_format };
path() = default;
path(const path&) = default;
path(path&&) = default;
~path() = default;
path& operator=(const path&) = default;
path& operator=(path&&) noexcept = default;
path(string_type&& _Source) : _Text(_STD move(_Source)) {}
path(string_type&& _Source, format) : _Text(_STD move(_Source)) {
// format has no meaning for this implementation, as the generic grammar is acceptable as a native path
}
template <class _Src, enable_if_t<_Is_Source<_Src>, int> = 0>
path(const _Src& _Source, format = auto_format) : _Text(_Convert_Source_to_wide(_Source)) {
// format has no meaning for this implementation, as the generic grammar is acceptable as a native path
}
template <class _InIt>
path(_InIt _First, _InIt _Last, format = auto_format) : _Text(_Convert_range_to_wide(_First, _Last)) {
// format has no meaning for this implementation, as the generic grammar is acceptable as a native path
static_assert(_Is_EcharT<_Iter_value_t<_InIt>>, "invalid value_type, see N4950 [fs.req]/3");
}
template <class _Src, enable_if_t<_Is_Source<_Src>, int> = 0>
path(const _Src& _Source, const locale& _Loc, format = auto_format)
: _Text(_Convert_stringoid_with_locale_to_wide(_Stringoid_from_Source(_Source), _Loc)) {
// format has no meaning for this implementation, as the generic grammar is acceptable as a native path
using _Stringoid = decltype(_Stringoid_from_Source(_Source));
static_assert(is_same_v<typename _Stringoid::value_type, char>,
"invalid value_type, see N4950 [fs.path.construct]/5");
}
template <class _InIt>
path(_InIt _First, _InIt _Last, const locale& _Loc, format = auto_format)
: _Text(_Convert_stringoid_with_locale_to_wide(_Stringoid_from_range(_First, _Last), _Loc)) {
// format has no meaning for this implementation, as the generic grammar is acceptable as a native path
static_assert(is_same_v<_Iter_value_t<_InIt>, char>, "invalid value_type, see N4950 [fs.path.construct]/5");
}
path& operator=(string_type&& _Source) noexcept /* strengthened */ {
// set native() to _Source
_Text = _STD move(_Source);
return *this;
}
path& assign(string_type&& _Source) noexcept /* strengthened */ {
// set native() to _Source
_Text = _STD move(_Source);
return *this;
}
template <class _Src, enable_if_t<_Is_Source<_Src>, int> = 0>
path& operator=(const _Src& _Source) { // set native() to _Source
_Text = _Convert_Source_to_wide(_Source);
return *this;
}
template <class _Src, enable_if_t<_Is_Source<_Src>, int> = 0>
path& assign(const _Src& _Source) { // set native() to _Source
_Text = _Convert_Source_to_wide(_Source);
return *this;
}
template <class _InIt>
path& assign(_InIt _First, _InIt _Last) { // set native() to [_First, _Last)
static_assert(_Is_EcharT<_Iter_value_t<_InIt>>, "invalid value_type, see N4950 [fs.req]/3");
_Text = _Convert_range_to_wide(_First, _Last);
return *this;
}
path& operator/=(const path& _Other) {
// set *this to the path lexically resolved by _Other relative to *this
// examples:
// path{"cat"} / "c:/dog"; // yields "c:/dog"
// path{"cat"} / "c:"; // yields "c:"
// path{"c:"} / ""; // yields "c:"
// path{"c:cat"} / "/dog"; // yields "c:/dog"
// path{"c:cat"} / "c:dog"; // yields "c:cat/dog"
// path{"c:cat"} / "d:dog"; // yields "d:dog"
// several places herein quote the standard, but the standard's variable p is replaced with _Other
if (_Other.is_absolute()) { // if _Other.is_absolute(), then op=(_Other)
return operator=(_Other);
}
const auto _My_first = _Text.data();
const auto _My_last = _My_first + _Text.size();
const auto _Other_first = _Other._Text.data();
const auto _Other_last = _Other_first + _Other._Text.size();
const auto _My_root_name_end = _Find_root_name_end(_My_first, _My_last);
const auto _Other_root_name_end = _Find_root_name_end(_Other_first, _Other_last);
if (_Other_first != _Other_root_name_end
&& _Range_compare(_My_first, _My_root_name_end, _Other_first, _Other_root_name_end) != 0) {
// if _Other.has_root_name() && _Other.root_name() != root_name(), then op=(_Other)
return operator=(_Other);
}
if (_Other_root_name_end != _Other_last && _Is_slash(*_Other_root_name_end)) {
// If _Other.has_root_directory() removes any root directory and relative-path from *this
_Text.erase(static_cast<size_t>(_My_root_name_end - _My_first));
} else {
// Otherwise, if (!has_root_directory && is_absolute) || has_filename appends path::preferred_separator
if (_My_root_name_end == _My_last) {
// Here, !has_root_directory && !has_filename
// Going through our root_name kinds:
// X: can't be absolute here, since those paths are absolute only when has_root_directory
// \\?\ can't exist without has_root_directory
// \\server can be absolute here
if (_My_root_name_end - _My_first >= 3) {
_Text.push_back(preferred_separator);
}
} else {
// Here, has_root_directory || has_filename
// If there is a trailing slash, the trailing slash might be part of root_directory.
// If it is, has_root_directory && !has_filename, so the test fails.
// If there is a trailing slash not part of root_directory, then !has_filename, so only
// (!has_root_directory && is_absolute) remains
// Going through our root_name kinds:
// X:cat\ needs a root_directory to be absolute
// \\server\cat must have a root_directory to exist with a relative_path
// \\?\ must have a root_directory to exist
// As a result, the test fails if there is a trailing slash.
// If there is no trailing slash, then has_filename, so the test passes.
// Therefore, the test passes if and only if there is no trailing slash.
if (!_Is_slash(_My_last[-1])) {
_Text.push_back(preferred_separator);
}
}
}
// Then appends the native format pathname of _Other, omitting any root-name from its generic format
// pathname, to the native format pathname.
_Text.append(_Other_root_name_end, static_cast<size_t>(_Other_last - _Other_root_name_end));
return *this;
}
template <class _Src, enable_if_t<_Is_Source<_Src>, int> = 0>
path& operator/=(const _Src& _Source) {
return operator/=(path{_Source});
}
template <class _Src, enable_if_t<_Is_Source<_Src>, int> = 0>
path& append(const _Src& _Source) {
return operator/=(path{_Source});
}
template <class _InIt>
path& append(_InIt _First, _InIt _Last) {
static_assert(_Is_EcharT<_Iter_value_t<_InIt>>, "invalid value_type, see N4950 [fs.req]/3");
return operator/=(path{_First, _Last});
}
path& operator+=(const path& _Added) { // concat _Added to native()
return operator+=(_Added._Text);
}
path& operator+=(const string_type& _Added) { // concat _Added to native()
_Text._Orphan_all();
_Text += _Added;
return *this;
}
path& operator+=(const wstring_view _Added) { // concat _Added to native()
_Text._Orphan_all();
_Text += _Added;
return *this;
}
path& operator+=(const value_type* const _Added) { // concat _Added to native()
_Text._Orphan_all();
_Text += _Added;
return *this;
}
path& operator+=(const value_type _Added) { // concat _Added to native()
_Text._Orphan_all();
_Text += _Added;
return *this;
}
template <class _Src, enable_if_t<_Is_Source<_Src>, int> = 0>
path& operator+=(const _Src& _Added) { // concat _Added to native()
return operator+=(path{_Added}._Text);
}
template <class _EcharT, enable_if_t<_Is_EcharT<_EcharT>, int> = 0>
path& operator+=(const _EcharT _Added) { // concat _Added to native()
return operator+=(path{&_Added, &_Added + 1}._Text);
}
template <class _Src, enable_if_t<_Is_Source<_Src>, int> = 0>
path& concat(const _Src& _Added) { // concat _Added to native()
return operator+=(path{_Added}._Text);
}
template <class _InIt>
path& concat(_InIt _First, _InIt _Last) { // concat [_First, _Last) to native()
static_assert(_Is_EcharT<_Iter_value_t<_InIt>>, "invalid value_type, see N4950 [fs.req]/3");
return operator+=(path{_First, _Last}._Text);
}
void clear() noexcept { // set *this to the empty path
_Text._Orphan_all();
_Text.clear();
}
path& make_preferred() noexcept /* strengthened */ {
// transform each fallback-separator into preferred-separator
_Text._Orphan_all();
_STD replace(_Text.begin(), _Text.end(), L'/', L'\\');
return *this;
}
path& remove_filename() noexcept /* strengthened */ {
// remove any filename from *this
const auto _First = _Text.data();
const auto _Last = _First + _Text.size();
const auto _Filename = _Find_filename(_First, _Last);
_Text._Orphan_all();
_Text.erase(static_cast<size_t>(_Filename - _First));
return *this;
}
void _Remove_filename_and_separator() noexcept { // remove filename and preceding non-root directory-separator
const auto _First = _Text.data();
const auto _Last = _First + _Text.size();
const auto _Root_name_end = _Find_root_name_end(_First, _Last);
const auto _Root_dir_end =
(_Root_name_end != _Last && _Is_slash(*_Root_name_end)) ? _Root_name_end + 1 : _Root_name_end;
using _Reverse_iter = reverse_iterator<const wchar_t*>;
const _Reverse_iter _Rbegin{_Last};
const _Reverse_iter _Rend{_Root_dir_end};
const auto _Rslash_first = _STD find_if(_Rbegin, _Rend, _Is_slash);
const auto _Rslash_last = _STD find_if_not(_Rslash_first, _Rend, _Is_slash);
const _Reverse_iter _Rlast{_First};
_Text._Orphan_all();
_Text.erase(static_cast<size_t>(_Rlast - _Rslash_last));
}
path& replace_filename(const path& _Replacement) { // remove any filename from *this and append _Replacement
remove_filename();
return operator/=(_Replacement);
}
path& replace_extension(/* const path& _Replacement = {} */) noexcept /* strengthened */ {
// remove any extension() (and alternate data stream references) from *this's filename()
const wchar_t* _First = _Text.data();
const auto _Last = _First + _Text.size();
const auto _Filename = _Find_filename(_First, _Last);
const auto _Ads = _STD find(_Filename, _Last, L':');
const auto _Extension = _Find_extension(_Filename, _Ads);
_Text._Orphan_all();
_Text.erase(static_cast<size_t>(_Extension - _First));
return *this;
}
path& replace_extension(const path& _Replacement) {
// remove any extension() (and alternate data stream references) from *this's filename(), and concatenate
// _Replacement
replace_extension();
if (!_Replacement.empty() && _Replacement._Text[0] != L'.') {
_Text.push_back(L'.');
}
return operator+=(_Replacement._Text);
}
void swap(path& _Rhs) noexcept {
_Text.swap(_Rhs._Text);
}
_NODISCARD const string_type& native() const noexcept {
// return a reference to the internally stored wstring in the native format
return _Text;
}
_NODISCARD const value_type* c_str() const noexcept {
// return a NTCTS to the internally stored path in the native format
return _Text.c_str();
}
operator string_type() const { // implicitly convert *this into a string containing the native format
return _Text;
}
template <class _EcharT, class _Traits = char_traits<_EcharT>, class _Alloc = allocator<_EcharT>,
enable_if_t<_Is_EcharT<_EcharT>, int> = 0>
_NODISCARD basic_string<_EcharT, _Traits, _Alloc> string(const _Alloc& _Al = _Alloc()) const {
// convert the native path from this instance into a basic_string
return _Convert_wide_to<_Traits>(_Text, _Al);
}
_NODISCARD _STD string string() const { // convert the native path from this instance into a string
return string<char>();
}
_NODISCARD _STD wstring wstring() const { // copy the native path from this instance into a wstring
return _Text;
}
_NODISCARD auto u8string() const { // convert the native path from this instance into a UTF-8 string
#ifdef __cpp_lib_char8_t
using _U8Ty = char8_t;
#else // ^^^ defined(__cpp_lib_char8_t) / !defined(__cpp_lib_char8_t) vvv
using _U8Ty = char;
#endif // ^^^ !defined(__cpp_lib_char8_t) ^^^
return _Convert_wide_to_narrow<char_traits<_U8Ty>>(__std_code_page::_Utf8, _Text, allocator<_U8Ty>{});
}
_NODISCARD _STD u16string u16string() const { // convert the native path from this instance into a u16string
return string<char16_t>();
}
_NODISCARD _STD u32string u32string() const { // convert the native path from this instance into a u32string
return string<char32_t>();
}
template <class _EcharT, class _Traits = char_traits<_EcharT>, class _Alloc = allocator<_EcharT>,
enable_if_t<_Is_EcharT<_EcharT>, int> = 0>
_NODISCARD basic_string<_EcharT, _Traits, _Alloc> generic_string(const _Alloc& _Al = _Alloc()) const {
// convert the native path from this instance into a generic basic_string
using _Alwide = _Rebind_alloc_t<_Alloc, wchar_t>;
_Alwide _Al_wchar(_Al);
basic_string<wchar_t, char_traits<wchar_t>, _Alwide> _Generic_str(_Al_wchar);
_Generic_str.resize(_Text.size());
_STD replace_copy(_Text.begin(), _Text.end(), _Generic_str.begin(), L'\\', L'/');
return _Convert_wide_to<_Traits>(_Generic_str, _Al);
}
_NODISCARD _STD string generic_string() const {
// convert the native path from this instance into a generic string
return generic_string<char>();
}
_NODISCARD _STD wstring generic_wstring() const {
// convert the current native path into a copy of it in the generic format
// note: intra-filename() observers stem() and extension() strip alternate data
// streams, but filenames with alternate data streams inside can serve as
// perfectly valid values of filename in the generic format, so in the interest of
// destroying less information we have preserved them here.
_STD wstring _Result;
_Result.resize(_Text.size());
_STD replace_copy(_Text.begin(), _Text.end(), _Result.begin(), L'\\', L'/');
return _Result;
}
_NODISCARD auto generic_u8string() const {
// convert the native path from this instance into a generic UTF-8 string
auto _Result = u8string();
using _U8Ty = decltype(_Result)::value_type;
_STD replace(_Result.begin(), _Result.end(), _U8Ty{u8'\\'}, _U8Ty{u8'/'});
return _Result;
}