Debian Codegraph @

libstdc++-v3/src/c++17/fs_path.cc

raw
1 // Class filesystem::path -*- C++ -*-
2
3 // Copyright (C) 2014-2025 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
9 // any later version.
10
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
19
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
24
25 #ifndef _GLIBCXX_USE_CXX11_ABI
26 # define _GLIBCXX_USE_CXX11_ABI 1
27 #endif
28
29 #ifdef __CYGWIN__
30 // Interpret "//x" as a root-name, not root-dir + filename
31 # define SLASHSLASH_IS_ROOTNAME 1
32 #endif
33
34 #include <filesystem>
35 #include <algorithm>
36 #include <array>
37 #include <bits/stl_uninitialized.h>
38 #include <ext/numeric_traits.h> // __gnu_cxx::__int_traits
39
40 namespace fs = std::filesystem;
41 using fs::path;
42
43 static inline bool is_dir_sep(path::value_type ch)
44 {
45 #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
46 return ch == L'/' || ch == path::preferred_separator;
47 #else
48 return ch == '/';
49 #endif
50 }
51
52 #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
53 static inline bool is_disk_designator(std::wstring_view s)
54 {
55 return s.length() == 2 && s[1] == L':';
56 }
57 #endif
58
59 struct path::_Parser
60 {
61 using string_view_type = std::basic_string_view<value_type>;
62
63 struct cmpt
64 {
65 string_view_type str;
66 _Type type = _Type::_Multi;
67
68 bool valid() const { return type != _Type::_Multi; }
69 };
70
71 string_view_type input;
72 string_view_type::size_type pos = 0;
73 size_t origin;
74 _Type last_type = _Type::_Multi;
75
76 _Parser(string_view_type s, size_t o = 0) : input(s), origin(o) { }
77
78 pair<cmpt, cmpt> root_path() noexcept
79 {
80 pos = 0;
81 pair<cmpt, cmpt> root;
82
83 const size_t len = input.size();
84
85 // look for root name or root directory
86 if (len && is_dir_sep(input[0]))
87 {
88 #if SLASHSLASH_IS_ROOTNAME
89 // look for root name, such as "//foo"
90 if (len > 2 && input[1] == input[0])
91 {
92 if (!is_dir_sep(input[2]))
93 {
94 // got root name, find its end
95 pos = 3;
96 while (pos < len && !is_dir_sep(input[pos]))
97 ++pos;
98 root.first.str = input.substr(0, pos);
99 root.first.type = _Type::_Root_name;
100
101 if (pos < len) // also got root directory
102 {
103 root.second.str = input.substr(pos, 1);
104 root.second.type = _Type::_Root_dir;
105 ++pos;
106 }
107 }
108 else
109 {
110 // got something like "///foo" which is just a root directory
111 // composed of multiple redundant directory separators
112 root.first.str = input.substr(0, 1);
113 root.first.type = _Type::_Root_dir;
114 pos += 2;
115 }
116 }
117 else
118 #endif
119 {
120 root.first.str = input.substr(0, 1);
121 root.first.type = _Type::_Root_dir;
122 ++pos;
123 }
124 // Find the start of the first filename
125 while (pos < len && is_dir_sep(input[pos]))
126 ++pos;
127 }
128 #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
129 else if (is_disk_designator(input.substr(0, 2)))
130 {
131 // got disk designator
132 root.first.str = input.substr(0, 2);
133 root.first.type = _Type::_Root_name;
134 if (len > 2 && is_dir_sep(input[2]))
135 {
136 root.second.str = input.substr(2, 1);
137 root.second.type = _Type::_Root_dir;
138 }
139 pos = input.find_first_not_of(L"/\\", 2);
140 }
141 #endif
142
143 if (root.second.valid())
144 last_type = root.second.type;
145 else
146 last_type = root.first.type;
147
148 return root;
149 }
150
151 cmpt next() noexcept
152 {
153 #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
154 string_view_type sep = L"/\\";
155 #else
156 char sep = '/';
157 #endif
158
159 const int last_pos = pos;
160
161 cmpt f;
162 if (pos != input.npos)
163 {
164 pos = input.find_first_not_of(sep, pos);
165 if (pos != input.npos)
166 {
167 const auto end = input.find_first_of(sep, pos);
168 f.str = input.substr(pos, end - pos);
169 f.type = _Type::_Filename;
170 pos = end;
171 }
172 else if (last_type == _Type::_Filename
173 || (last_pos == 0 && !input.empty()))
174 {
175 // [fs.path.itr]/4 An empty element, if trailing non-root
176 // directory-separator present.
177 __glibcxx_assert(is_dir_sep(input.back()));
178 f.str = input.substr(input.length(), 0);
179 f.type = _Type::_Filename;
180 }
181 }
182 last_type = f.type;
183 return f;
184 }
185
186 string_view_type::size_type
187 offset(const cmpt& c) const noexcept
188 { return origin + c.str.data() - input.data(); }
189 };
190
191 inline
192 path::path(basic_string_view<value_type> __str, _Type __type)
193 : _M_pathname(__str)
194 {
195 __glibcxx_assert(__type != _Type::_Multi);
196 _M_cmpts.type(__type);
197 }
198
199 inline
200 path::_Cmpt::_Cmpt(basic_string_view<value_type> __s, _Type __t, size_t __pos)
201 : path(__s, __t), _M_pos(__pos)
202 { }
203
204 struct path::_List::_Impl
205 {
206 using value_type = _Cmpt;
207
208 _Impl(int cap) : _M_size(0), _M_capacity(cap) { }
209
210 alignas(value_type) int _M_size;
211 int _M_capacity;
212
213 using iterator = value_type*;
214 using const_iterator = const value_type*;
215
216 iterator begin() { return reinterpret_cast<value_type*>(this + 1); }
217 iterator end() { return begin() + size(); }
218
219 const_iterator begin() const
220 { return reinterpret_cast<const value_type*>(this + 1); }
221 const_iterator end() const { return begin() + size(); }
222
223 const value_type& front() const { return *begin(); }
224 const value_type& back() const { return end()[-1]; }
225
226 int size() const { return _M_size; }
227 int capacity() const { return _M_capacity; }
228 bool empty() const { return _M_size == 0; }
229
230 void clear() { std::destroy_n(begin(), _M_size); _M_size = 0; }
231
232 void pop_back()
233 {
234 back().~_Cmpt();
235 --_M_size;
236 }
237
238 void _M_erase_from(const_iterator pos)
239 {
240 iterator first = begin() + (pos - begin());
241 iterator last = end();
242 std::destroy(first, last);
243 _M_size -= last - first;
244 }
245
246 unique_ptr<_Impl, _Impl_deleter> copy() const
247 {
248 const auto n = size();
249 void* p = ::operator new(sizeof(_Impl) + n * sizeof(value_type));
250 unique_ptr<_Impl, _Impl_deleter> newptr(::new (p) _Impl{n});
251 std::uninitialized_copy_n(begin(), n, newptr->begin());
252 newptr->_M_size = n;
253 return newptr;
254 }
255
256 // Clear the lowest two bits from the pointer (i.e. remove the _Type value)
257 static _Impl* notype(_Impl* p)
258 {
259 constexpr uintptr_t mask = ~(uintptr_t)0x3;
260 return reinterpret_cast<_Impl*>(reinterpret_cast<uintptr_t>(p) & mask);
261 }
262 };
263
264 void path::_List::_Impl_deleter::operator()(_Impl* p) const noexcept
265 {
266 p = _Impl::notype(p);
267 if (p)
268 {
269 __glibcxx_assert(p->_M_size <= p->_M_capacity);
270 p->clear();
271 ::operator delete(p, sizeof(*p) + p->_M_capacity * sizeof(value_type));
272 }
273 }
274
275 path::_List::_List() : _M_impl(reinterpret_cast<_Impl*>(_Type::_Filename)) { }
276
277 path::_List::_List(const _List& other)
278 {
279 if (!other.empty())
280 _M_impl = other._M_impl->copy();
281 else
282 type(other.type());
283 }
284
285 path::_List&
286 path::_List::operator=(const _List& other)
287 {
288 if (!other.empty())
289 {
290 // copy in-place if there is capacity
291 const int newsize = other._M_impl->size();
292 auto impl = _Impl::notype(_M_impl.get());
293 if (impl && impl->capacity() >= newsize)
294 {
295 const int oldsize = impl->_M_size;
296 auto to = impl->begin();
297 auto from = other._M_impl->begin();
298 const int minsize = std::min(newsize, oldsize);
299 for (int i = 0; i < minsize; ++i)
300 to[i]._M_pathname.reserve(from[i]._M_pathname.length());
301 if (newsize > oldsize)
302 {
303 std::uninitialized_copy_n(from + oldsize, newsize - oldsize,
304 to + oldsize);
305 impl->_M_size = newsize;
306 }
307 else if (newsize < oldsize)
308 impl->_M_erase_from(impl->begin() + newsize);
309 std::copy_n(from, minsize, to);
310 type(_Type::_Multi);
311 }
312 else
313 _M_impl = other._M_impl->copy();
314 }
315 else
316 {
317 clear();
318 type(other.type());
319 }
320 return *this;
321 }
322
323 inline void
324 path::_List::type(_Type t) noexcept
325 {
326 auto val = reinterpret_cast<uintptr_t>(_Impl::notype(_M_impl.release()));
327 _M_impl.reset(reinterpret_cast<_Impl*>(val | (unsigned char)t));
328 }
329
330 inline int
331 path::_List::size() const noexcept
332 {
333 if (auto* ptr = _Impl::notype(_M_impl.get()))
334 return ptr->size();
335 return 0;
336 }
337
338 inline int
339 path::_List::capacity() const noexcept
340 {
341 if (auto* ptr = _Impl::notype(_M_impl.get()))
342 return ptr->capacity();
343 return 0;
344 }
345
346 inline bool
347 path::_List::empty() const noexcept
348 {
349 return size() == 0;
350 }
351
352 inline auto
353 path::_List::begin() noexcept
354 -> iterator
355 {
356 __glibcxx_assert(!empty());
357 if (auto* ptr = _Impl::notype(_M_impl.get()))
358 return ptr->begin();
359 return nullptr;
360 }
361
362 inline auto
363 path::_List::end() noexcept
364 -> iterator
365 {
366 __glibcxx_assert(!empty());
367 if (auto* ptr = _Impl::notype(_M_impl.get()))
368 return ptr->end();
369 return nullptr;
370 }
371
372 auto
373 path::_List::begin() const noexcept
374 -> const_iterator
375 {
376 __glibcxx_assert(!empty());
377 if (auto* ptr = _Impl::notype(_M_impl.get()))
378 return ptr->begin();
379 return nullptr;
380 }
381
382 auto
383 path::_List::end() const noexcept
384 -> const_iterator
385 {
386 __glibcxx_assert(!empty());
387 if (auto* ptr = _Impl::notype(_M_impl.get()))
388 return ptr->end();
389 return nullptr;
390 }
391
392 inline auto
393 path::_List::front() noexcept
394 -> value_type&
395 {
396 return *_M_impl->begin();
397 }
398
399 inline auto
400 path::_List::back() noexcept
401 -> value_type&
402 {
403 return _M_impl->begin()[_M_impl->size() - 1];
404 }
405
406 inline auto
407 path::_List::front() const noexcept
408 -> const value_type&
409 {
410 return *_M_impl->begin();
411 }
412
413 inline auto
414 path::_List::back() const noexcept
415 -> const value_type&
416 {
417 return _M_impl->begin()[_M_impl->size() - 1];
418 }
419
420 inline void
421 path::_List::pop_back()
422 {
423 __glibcxx_assert(size() > 0);
424 _M_impl->pop_back();
425 }
426
427 inline void
428 path::_List::_M_erase_from(const_iterator pos)
429 {
430 _M_impl->_M_erase_from(pos);
431 }
432
433 inline void
434 path::_List::clear()
435 {
436 if (auto ptr = _Impl::notype(_M_impl.get()))
437 ptr->clear();
438 }
439
440 void
441 path::_List::reserve(int newcap, bool exact = false)
442 {
443 // __glibcxx_assert(type() == _Type::_Multi);
444
445 _Impl* curptr = _Impl::notype(_M_impl.get());
446
447 int curcap = curptr ? curptr->capacity() : 0;
448
449 if (curcap < newcap)
450 {
451 if (!exact)
452 {
453 const int nextcap = curcap + curcap / 2;
454 if (newcap < nextcap)
455 newcap = nextcap;
456 }
457
458 using __gnu_cxx::__int_traits;
459 // Nobody should need paths with this many components.
460 if (newcap >= __int_traits<int>::__max / 4)
461 std::__throw_bad_alloc();
462
463 size_t bytes;
464 if constexpr (__int_traits<int>::__max >= __int_traits<size_t>::__max)
465 {
466 size_t components;
467 if (__builtin_mul_overflow(newcap, sizeof(value_type), &components)
468 || __builtin_add_overflow(sizeof(_Impl), components, &bytes))
469 std::__throw_bad_alloc();
470 }
471 else // This won't overflow, even for 20-bit size_t on msp430.
472 bytes = sizeof(_Impl) + newcap * sizeof(value_type);
473
474 void* p = ::operator new(bytes);
475 std::unique_ptr<_Impl, _Impl_deleter> newptr(::new(p) _Impl{newcap});
476 const int cursize = curptr ? curptr->size() : 0;
477 if (cursize)
478 {
479 std::uninitialized_move_n(curptr->begin(), cursize, newptr->begin());
480 newptr->_M_size = cursize;
481 }
482 std::swap(newptr, _M_impl);
483 }
484 }
485
486 path&
487 path::operator=(const path& p)
488 {
489 if (&p == this) [[__unlikely__]]
490 return *this;
491
492 _M_pathname.reserve(p._M_pathname.length());
493 _M_cmpts = p._M_cmpts; // might throw
494 _M_pathname = p._M_pathname; // won't throw because we reserved enough space
495 return *this;
496 }
497
498 path&
499 path::operator/=(const path& __p)
500 {
501 #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
502 if (__p.is_absolute()
503 || (__p.has_root_name() && __p.root_name() != root_name()))
504 return operator=(__p);
505
506 basic_string_view<value_type> __lhs = _M_pathname;
507 bool __add_sep = false;
508
509 if (__p.has_root_directory())
510 {
511 // Remove any root directory and relative path
512 if (_M_type() != _Type::_Root_name)
513 {
514 if (!_M_cmpts.empty()
515 && _M_cmpts.front()._M_type() == _Type::_Root_name)
516 __lhs = _M_cmpts.front()._M_pathname;
517 else
518 __lhs = {};
519 }
520 }
521 else if (has_filename() || (!has_root_directory() && is_absolute()))
522 __add_sep = true;
523
524 basic_string_view<value_type> __rhs = __p._M_pathname;
525 // Omit any root-name from the generic format pathname:
526 if (__p._M_type() == _Type::_Root_name)
527 __rhs = {};
528 else if (!__p._M_cmpts.empty()
529 && __p._M_cmpts.front()._M_type() == _Type::_Root_name)
530 __rhs.remove_prefix(__p._M_cmpts.front()._M_pathname.size());
531
532 const size_t __len = __lhs.size() + (int)__add_sep + __rhs.size();
533 const int __maxcmpts = _M_cmpts.size() + __p._M_cmpts.size();
534 if (_M_pathname.capacity() < __len || _M_cmpts.capacity() < __maxcmpts)
535 {
536 // Construct new path and swap (strong exception-safety guarantee).
537 string_type __tmp;
538 __tmp.reserve(__len);
539 __tmp = __lhs;
540 if (__add_sep)
541 __tmp += preferred_separator;
542 __tmp += __rhs;
543 path __newp = std::move(__tmp);
544 swap(__newp);
545 }
546 else
547 {
548 _M_pathname = __lhs;
549 if (__add_sep)
550 _M_pathname += preferred_separator;
551 _M_pathname += __rhs;
552 __try
553 {
554 _M_split_cmpts();
555 }
556 __catch (...)
557 {
558 __try
559 {
560 // try to restore original state
561 _M_pathname.resize(__lhs.length());
562 _M_split_cmpts();
563 }
564 __catch (...)
565 {
566 // give up, basic exception safety guarantee only:
567 clear();
568 __throw_exception_again;
569 }
570 }
571 }
572 #else
573 // POSIX version is simpler than the specification in the standard,
574 // as any path with root-name or root-dir is absolute.
575
576 if (__p.is_absolute() || this->empty())
577 {
578 return operator=(__p);
579 }
580
581 using string_view_type = basic_string_view<value_type>;
582
583 string_view_type sep;
584 if (has_filename())
585 sep = { &preferred_separator, 1 }; // need to add a separator
586 #if SLASHSLASH_IS_ROOTNAME
587 else if (_M_type() == _Type::_Root_name) // root-name with no root-dir
588 sep = { &preferred_separator, 1 }; // need to add a separator
589 #endif
590 else if (__p.empty())
591 return *this; // nothing to do
592
593 const auto orig_pathlen = _M_pathname.length();
594 const auto orig_size = _M_cmpts.size();
595 const auto orig_type = _M_type();
596
597 int capacity = 0;
598 if (_M_type() == _Type::_Multi)
599 capacity += _M_cmpts.size();
600 else if (!empty())
601 capacity += 1;
602 if (__p._M_type() == _Type::_Multi)
603 capacity += __p._M_cmpts.size();
604 else if (!__p.empty() || !sep.empty())
605 capacity += 1;
606 #if SLASHSLASH_IS_ROOTNAME
607 if (orig_type == _Type::_Root_name)
608 ++capacity; // Need to insert root-directory after root-name
609 #endif
610
611 _M_pathname.reserve(_M_pathname.length() + sep.length()
612 + __p._M_pathname.length());
613
614 __try
615 {
616 _M_pathname += sep;
617 const auto basepos = _M_pathname.length();
618 _M_pathname += __p.native();
619
620 _M_cmpts.type(_Type::_Multi);
621 _M_cmpts.reserve(capacity);
622 _Cmpt* output = _M_cmpts._M_impl->end();
623
624 if (orig_type == _Type::_Multi)
625 {
626 // Remove empty final component
627 if (_M_cmpts._M_impl->back().empty())
628 {
629 _M_cmpts.pop_back();
630 --output;
631 }
632 }
633 else if (orig_pathlen != 0)
634 {
635 // Create single component from original path
636 string_view_type s(_M_pathname.data(), orig_pathlen);
637 ::new(output++) _Cmpt(s, orig_type, 0);
638 ++_M_cmpts._M_impl->_M_size;
639 #if SLASHSLASH_IS_ROOTNAME
640 if (orig_type == _Type::_Root_name)
641 {
642 ::new(output++) _Cmpt(sep, _Type::_Root_dir,
643 orig_pathlen + sep.length());
644 ++_M_cmpts._M_impl->_M_size;
645 }
646 #endif
647 }
648
649 if (__p._M_type() == _Type::_Multi)
650 {
651 for (auto& c : *__p._M_cmpts._M_impl)
652 {
653 ::new(output++) _Cmpt(c._M_pathname, _Type::_Filename,
654 c._M_pos + basepos);
655 ++_M_cmpts._M_impl->_M_size;
656 }
657 }
658 else if (!__p.empty() || !sep.empty())
659 {
660 __glibcxx_assert(__p._M_type() == _Type::_Filename);
661 ::new(output) _Cmpt(__p._M_pathname, __p._M_type(), basepos);
662 ++_M_cmpts._M_impl->_M_size;
663 }
664 }
665 __catch (...)
666 {
667 _M_pathname.resize(orig_pathlen);
668 if (orig_type == _Type::_Multi)
669 _M_cmpts._M_erase_from(_M_cmpts.begin() + orig_size);
670 else
671 _M_cmpts.clear();
672 _M_cmpts.type(orig_type);
673 __throw_exception_again;
674 }
675 #endif
676 return *this;
677 }
678
679 // [fs.path.append]
680 void
681 path::_M_append(basic_string_view<value_type> s)
682 {
683 _Parser parser(s);
684 auto root_path = parser.root_path();
685
686 #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
687 bool is_absolute = root_path.second.type == _Type::_Root_dir;
688 bool has_root_name = root_path.first.type == _Type::_Root_name;
689 if (is_absolute || (has_root_name && root_path.first.str != root_name()))
690 {
691 operator=(s);
692 return;
693 }
694
695 basic_string_view<value_type> lhs = _M_pathname;
696 bool add_sep = false;
697
698 bool has_root_directory = root_path.first.type == _Type::_Root_dir
699 || root_path.second.type == _Type::_Root_dir;
700
701 if (has_root_directory)
702 {
703 // Remove any root directory and relative path
704 if (_M_type() != _Type::_Root_name)
705 {
706 if (!_M_cmpts.empty()
707 && _M_cmpts.front()._M_type() == _Type::_Root_name)
708 lhs = _M_cmpts.front()._M_pathname;
709 else
710 lhs = {};
711 }
712 }
713 else if (has_filename() || (!has_root_directory && is_absolute))
714 add_sep = true;
715
716 basic_string_view<value_type> rhs = s;
717 // Omit any root-name from the generic format pathname:
718 if (has_root_name)
719 rhs.remove_prefix(root_path.first.str.length());
720
721 // Construct new path and swap (strong exception-safety guarantee).
722 string_type tmp;
723 tmp.reserve(lhs.size() + (int)add_sep + rhs.size());
724 tmp = lhs;
725 if (add_sep)
726 tmp += preferred_separator;
727 tmp += rhs;
728 path newp = std::move(tmp);
729 swap(newp);
730 #else
731
732 bool is_absolute = root_path.first.type == _Type::_Root_dir
733 || root_path.second.type == _Type::_Root_dir;
734 if (is_absolute || this->empty())
735 {
736 operator=(s);
737 return;
738 }
739
740 const auto orig_pathlen = _M_pathname.length();
741 const auto orig_size = _M_cmpts.size();
742 const auto orig_type = _M_type();
743
744 basic_string_view<value_type> sep;
745 if (has_filename())
746 sep = { &preferred_separator, 1 }; // need to add a separator
747 #if SLASHSLASH_IS_ROOTNAME
748 else if (_M_type() == _Type::_Root_name) // root-name with no root-dir
749 sep = { &preferred_separator, 1 }; // need to add a separator
750 #endif
751 else if (s.empty())
752 return; // nothing to do
753
754 // Copy the input into _M_pathname:
755 _M_pathname += s;
756 _M_pathname.insert(orig_pathlen, sep);
757 // Update s to refer to the new copy (this ensures s is not a dangling
758 // reference to deallocated characters, in the case where it was referring
759 // into _M_pathname or a member of _M_cmpts).
760 s = _M_pathname;
761 const auto orig_pathname = s.substr(0, orig_pathlen);
762 s.remove_prefix(orig_pathlen + sep.length());
763
764 parser.input = s; // reset parser to use updated string view
765 const auto basepos = orig_pathname.length() + sep.length();
766 parser.origin = basepos;
767
768 std::array<_Parser::cmpt, 64> buf;
769 auto next = buf.begin();
770
771 int capacity = 0;
772 if (_M_type() == _Type::_Multi)
773 capacity += _M_cmpts.size();
774 else if (!empty())
775 capacity += 1;
776
777 auto cmpt = parser.next();
778 if (cmpt.valid())
779 {
780 do
781 {
782 *next++ = cmpt;
783 cmpt = parser.next();
784 }
785 while (cmpt.valid() && next != buf.end());
786
787 capacity += next - buf.begin();
788 if (cmpt.valid()) // filled buffer before parsing whole input
789 {
790 ++capacity;
791 _Parser parser2(parser);
792 while (parser2.next().valid())
793 ++capacity;
794 }
795 }
796 else if (!sep.empty())
797 ++capacity;
798
799 #if SLASHSLASH_IS_ROOTNAME
800 if (orig_type == _Type::_Root_name)
801 ++capacity; // Need to insert root-directory after root-name
802 #endif
803
804 __try
805 {
806 _M_cmpts.type(_Type::_Multi);
807 _M_cmpts.reserve(capacity);
808 _Cmpt* output = _M_cmpts._M_impl->end();
809
810 if (orig_type == _Type::_Multi)
811 {
812 // Remove empty final component
813 if (_M_cmpts._M_impl->back().empty())
814 {
815 _M_cmpts.pop_back();
816 --output;
817 }
818 }
819 else if (orig_pathlen != 0)
820 {
821 // Create single component from original path
822 ::new(output++) _Cmpt(orig_pathname, orig_type, 0);
823 ++_M_cmpts._M_impl->_M_size;
824
825 #if SLASHSLASH_IS_ROOTNAME
826 if (!sep.empty() && orig_type == _Type::_Root_name)
827 {
828 ::new(output++) _Cmpt(sep, _Type::_Root_dir,
829 orig_pathlen + sep.length());
830 ++_M_cmpts._M_impl->_M_size;
831 }
832 #endif
833 }
834
835 if (next != buf.begin())
836 {
837 for (auto it = buf.begin(); it != next; ++it)
838 {
839 auto c = *it;
840 ::new(output++) _Cmpt(c.str, c.type, parser.offset(c));
841 ++_M_cmpts._M_impl->_M_size;
842 }
843 while (cmpt.valid())
844 {
845 ::new(output++) _Cmpt(cmpt.str, cmpt.type, parser.offset(cmpt));
846 ++_M_cmpts._M_impl->_M_size;
847 cmpt = parser.next();
848 }
849 }
850 else if (!sep.empty())
851 {
852 // Empty filename at the end:
853 ::new(output) _Cmpt({}, _Type::_Filename, basepos);
854 ++_M_cmpts._M_impl->_M_size;
855 }
856 }
857 __catch (...)
858 {
859 _M_pathname.resize(orig_pathlen);
860 if (orig_type == _Type::_Multi)
861 _M_cmpts._M_erase_from(_M_cmpts.begin() + orig_size);
862 else
863 _M_cmpts.clear();
864 _M_cmpts.type(orig_type);
865 __throw_exception_again;
866 }
867 #endif
868 }
869
870 // [fs.path.concat]
871 path&
872 path::operator+=(const path& p)
873 {
874 if (p.empty())
875 return *this;
876
877 if (this->empty())
878 {
879 operator=(p);
880 return *this;
881 }
882
883 // Handle p += p which would otherwise access dangling pointers after
884 // reallocating _M_cmpts and _M_pathname.
885 if (&p == this) [[unlikely]]
886 return *this += p.native();
887 // Handle p += *i where i is in [p.begin(),p.end()), for the same reason.
888 if (_M_type() == _Type::_Multi && p._M_type() != _Type::_Multi)
889 {
890 const auto first = _M_cmpts.begin(), last = first + _M_cmpts.size();
891 if (!std::less<>()(&p, first) && std::less<>()(&p, last)) [[unlikely]]
892 return *this += p.native();
893 }
894
895 #if _GLIBCXX_FILESYSTEM_IS_WINDOWS
896 if (_M_type() == _Type::_Root_name
897 || (_M_type() == _Type::_Filename && _M_pathname.size() == 1))
898 {
899 // Handle path("C") += path(":") and path("C:") += path("/x")
900 // FIXME: do this more efficiently
901 *this = path(_M_pathname + p._M_pathname);
902 return *this;
903 }
904 #endif
905 #if SLASHSLASH_IS_ROOTNAME
906 if (_M_type() == _Type::_Root_dir)
907 {
908 // Handle path("/") += path("/x") and path("//") += path("x")
909 // FIXME: do this more efficiently
910 *this = path(_M_pathname + p._M_pathname);
911 return *this;
912 }
913 #endif
914
915 const auto orig_pathlen = _M_pathname.length();
916 const auto orig_type = _M_type();
917 const auto orig_size = _M_cmpts.size();
918 int orig_filenamelen = -1;
919 basic_string_view<value_type> extra;
920
921 // Ensure that '_M_pathname += p._M_pathname' won't throw:
922 _M_pathname.reserve(orig_pathlen + p._M_pathname.length());
923
924 _Cmpt c;
925 _Cmpt* it = nullptr;
926 _Cmpt* last = nullptr;
927 if (p._M_type() == _Type::_Multi)
928 {
929 it = p._M_cmpts._M_impl->begin();
930 last = p._M_cmpts._M_impl->end();
931 }
932 else
933 {
934 c = _Cmpt(p._M_pathname, p._M_type(), 0);
935 it = &c;
936 last = it + 1;
937 }
938
939 if (it->_M_type() == _Type::_Filename)
940 {
941 // See if there's a filename or root-name at the end of the original path
942 // that we can add to.
943 if (_M_type() == _Type::_Filename
944 #if SLASHSLASH_IS_ROOTNAME
945 || _M_type() == _Type::_Root_name
946 #endif
947 )
948 {
949 if (p._M_type() == _Type::_Filename)
950 {
951 // Simplest case where we just add the whole of p to the
952 // original path.
953 _M_pathname += p._M_pathname;
954 return *this;
955 }
956 // Only the first component of s should be appended, do so below:
957 extra = it->_M_pathname;
958 ++it;
959 }
960 else if (_M_type() == _Type::_Multi
961 && _M_cmpts.back()._M_type() == _Type::_Filename)
962 {
963 auto& back = _M_cmpts.back();
964 if (p._M_type() == _Type::_Filename)
965 {
966 basic_string_view<value_type> s = p._M_pathname;
967 back._M_pathname += s;
968 _M_pathname += s;
969 return *this;
970 }
971
972 orig_filenamelen = back._M_pathname.length();
973 back._M_pathname += it->_M_pathname;
974 extra = it->_M_pathname;
975 ++it;
976 }
977 }
978 else if (is_dir_sep(_M_pathname.back()) && _M_type() == _Type::_Multi
979 && _M_cmpts.back()._M_type() == _Type::_Filename)
980 orig_filenamelen = 0; // current path has empty filename at end
981
982 int capacity = 0;
983 if (_M_type() == _Type::_Multi)
984 capacity += _M_cmpts.size();
985 else
986 capacity += 1;
987 if (p._M_type() == _Type::_Multi)
988 capacity += p._M_cmpts.size();
989 else
990 capacity += 1;
991
992 __try
993 {
994 _M_cmpts.type(_Type::_Multi);
995 _M_cmpts.reserve(capacity);
996 _Cmpt* output = _M_cmpts._M_impl->end();
997
998 if (orig_type != _Type::_Multi)
999 {
1000 // Create single component from original path
1001 auto ptr = ::new(output++) _Cmpt({}, orig_type, 0);
1002 ++_M_cmpts._M_impl->_M_size;
1003 ptr->_M_pathname.reserve(_M_pathname.length() + extra.length());
1004 ptr->_M_pathname = _M_pathname;
1005 ptr->_M_pathname += extra;
1006
1007 #if SLASHSLASH_IS_ROOTNAME
1008 if (orig_type == _Type::_Root_name)
1009 {
1010 basic_string_view<value_type> s(p._M_pathname);
1011 ::new(output++) _Cmpt(s.substr(extra.length(), 1),
1012 _Type::_Root_dir, orig_pathlen + extra.length());
1013 ++_M_cmpts._M_impl->_M_size;
1014 }
1015 #endif
1016 }
1017 else if (orig_filenamelen == 0 && it != last)
1018 {
1019 // Remove empty filename at end of original path.
1020 _M_cmpts.pop_back();
1021 --output;
1022 }
1023
1024 if (it != last && it->_M_type() == _Type::_Root_name)
1025 {
1026 basic_string_view<value_type> s = it->_M_pathname;
1027 auto pos = orig_pathlen;
1028 #if SLASHSLASH_IS_ROOTNAME
1029 s.remove_prefix(2);
1030 pos += 2;
1031 #endif
1032 ::new(output++) _Cmpt(s, _Type::_Filename, pos);
1033 ++_M_cmpts._M_impl->_M_size;
1034 ++it;
1035 }
1036
1037 if (it != last && it->_M_type() == _Type::_Root_dir)
1038 ++it;
1039
1040 while (it != last)
1041 {
1042 auto pos = it->_M_pos + orig_pathlen;
1043 ::new(output++) _Cmpt(it->_M_pathname, _Type::_Filename, pos);
1044 ++_M_cmpts._M_impl->_M_size;
1045 ++it;
1046 }
1047
1048 _M_pathname += p._M_pathname;
1049
1050 if (is_dir_sep(_M_pathname.back()))
1051 {
1052 ::new(output++) _Cmpt({}, _Type::_Filename, _M_pathname.length());
1053 ++_M_cmpts._M_impl->_M_size;
1054 }
1055 }
1056 __catch (...)
1057 {
1058 _M_pathname.resize(orig_pathlen);
1059 if (orig_type == _Type::_Multi)
1060 {
1061 if (_M_cmpts.size() > orig_size)
1062 _M_cmpts._M_erase_from(_M_cmpts.begin() + orig_size);
1063 if (orig_filenamelen != -1)
1064 {
1065 if (_M_cmpts.size() == orig_size)
1066 {
1067 auto& back = _M_cmpts.back();
1068 back._M_pathname.resize(orig_filenamelen);
1069 if (orig_filenamelen == 0)
1070 back._M_pos = orig_pathlen;
1071 }
1072 else
1073 {
1074 auto output = _M_cmpts._M_impl->end();
1075 ::new(output) _Cmpt({}, _Type::_Filename, orig_pathlen);
1076 ++_M_cmpts._M_impl->_M_size;
1077 }
1078 }
1079 }
1080 else
1081 _M_cmpts.clear();
1082 _M_cmpts.type(orig_type);
1083 __throw_exception_again;
1084 }
1085 return *this;
1086 }
1087
1088 // [fs.path.concat]
1089 void
1090 path::_M_concat(basic_string_view<value_type> s)
1091 {
1092 if (s.empty())
1093 return;
1094
1095 if (this->empty())
1096 {
1097 operator=(s);
1098 return;
1099 }
1100
1101 #if _GLIBCXX_FILESYSTEM_IS_WINDOWS
1102 if (_M_type() == _Type::_Root_name
1103 || (_M_type() == _Type::_Filename && _M_pathname.size() == 1))
1104 {
1105 // Handle path("C") += ":" and path("C:") += "/x"
1106 // FIXME: do this more efficiently
1107 *this = path(_M_pathname + string_type(s));
1108 return;
1109 }
1110 #endif
1111 #if SLASHSLASH_IS_ROOTNAME
1112 if (_M_type() == _Type::_Root_dir)
1113 {
1114 // Handle path("/") += "/x" and path("//") += "x"
1115 // FIXME: do this more efficiently
1116 *this = path(_M_pathname + string_type(s));
1117 return;
1118 }
1119 #endif
1120
1121 const auto orig_pathlen = _M_pathname.length();
1122 const auto orig_type = _M_type();
1123 const auto orig_size = _M_cmpts.size();
1124 int orig_filenamelen = -1;
1125 basic_string_view<value_type> extra;
1126
1127 // Copy the input into _M_pathname:
1128 _M_pathname += s;
1129 // Update s to refer to the new copy (this ensures s is not a dangling
1130 // reference to deallocated characters, in the case where it was referring
1131 // into _M_pathname or a member of _M_cmpts).
1132 s = _M_pathname;
1133 const auto orig_pathname = s.substr(0, orig_pathlen);
1134 s.remove_prefix(orig_pathlen);
1135
1136 _Parser parser(s, orig_pathlen);
1137 auto cmpt = parser.next();
1138
1139 if (cmpt.str.data() == s.data())
1140 {
1141 // See if there's a filename or root-name at the end of the original path
1142 // that we can add to.
1143 if (_M_type() == _Type::_Filename
1144 #if SLASHSLASH_IS_ROOTNAME
1145 || _M_type() == _Type::_Root_name
1146 #endif
1147 )
1148 {
1149 if (cmpt.str.length() == s.length())
1150 {
1151 // Simplest case where we just need to add the whole of s
1152 // to the original path, which was already done above.
1153 return;
1154 }
1155 // Only the first component of s should be appended, do so below:
1156 extra = cmpt.str;
1157 cmpt = {}; // so we don't process it again
1158 }
1159 else if (_M_type() == _Type::_Multi
1160 && _M_cmpts.back()._M_type() == _Type::_Filename)
1161 {
1162 auto& back = _M_cmpts.back();
1163 if (cmpt.str.length() == s.length())
1164 {
1165 back._M_pathname += s;
1166 return;
1167 }
1168
1169 orig_filenamelen = back._M_pathname.length();
1170 back._M_pathname += cmpt.str;
1171 extra = cmpt.str;
1172 cmpt = {};
1173 }
1174 }
1175 else if (is_dir_sep(orig_pathname.back()) && _M_type() == _Type::_Multi
1176 && _M_cmpts.back()._M_type() == _Type::_Filename)
1177 orig_filenamelen = 0; // original path had empty filename at end
1178
1179 std::array<_Parser::cmpt, 64> buf;
1180 auto next = buf.begin();
1181
1182 if (cmpt.valid())
1183 *next++ = cmpt;
1184
1185 cmpt = parser.next();
1186 while (cmpt.valid() && next != buf.end())
1187 {
1188 *next++ = cmpt;
1189 cmpt = parser.next();
1190 }
1191
1192 int capacity = 0;
1193 if (_M_type() == _Type::_Multi)
1194 capacity += _M_cmpts.size();
1195 else
1196 capacity += 1;
1197
1198 capacity += next - buf.begin();
1199
1200 if (cmpt.valid()) // filled buffer before parsing whole input
1201 {
1202 ++capacity;
1203 _Parser parser2(parser);
1204 while (parser2.next().valid())
1205 ++capacity;
1206 }
1207
1208 #if SLASHSLASH_IS_ROOTNAME
1209 if (orig_type == _Type::_Root_name)
1210 ++capacity; // Need to insert root-directory after root-name
1211 #endif
1212
1213 __try
1214 {
1215 _M_cmpts.type(_Type::_Multi);
1216 _M_cmpts.reserve(capacity);
1217 _Cmpt* output = _M_cmpts._M_impl->end();
1218 auto it = buf.begin();
1219
1220 if (orig_type != _Type::_Multi)
1221 {
1222 // Create single component from original path
1223 auto p = ::new(output++) _Cmpt({}, orig_type, 0);
1224 ++_M_cmpts._M_impl->_M_size;
1225 p->_M_pathname.reserve(orig_pathname.length() + extra.length());
1226 p->_M_pathname = orig_pathname;
1227 p->_M_pathname += extra;
1228
1229 #if SLASHSLASH_IS_ROOTNAME
1230 if (orig_type == _Type::_Root_name)
1231 {
1232 ::new(output++) _Cmpt(s.substr(extra.length(), 1),
1233 _Type::_Root_dir, orig_pathlen + extra.length());
1234 ++_M_cmpts._M_impl->_M_size;
1235 }
1236 #endif
1237 }
1238 else if (orig_filenamelen == 0 && extra.empty())
1239 {
1240 // Replace empty filename at end of original path.
1241 std::prev(output)->_M_pathname = it->str;
1242 std::prev(output)->_M_pos = parser.offset(*it);
1243 ++it;
1244 }
1245
1246 while (it != next)
1247 {
1248 ::new(output++) _Cmpt(it->str, _Type::_Filename, parser.offset(*it));
1249 ++_M_cmpts._M_impl->_M_size;
1250 ++it;
1251 }
1252
1253 if (next == buf.end())
1254 {
1255 while (cmpt.valid())
1256 {
1257 auto pos = parser.offset(cmpt);
1258 ::new(output++) _Cmpt(cmpt.str, _Type::_Filename, pos);
1259 ++_M_cmpts._M_impl->_M_size;
1260 cmpt = parser.next();
1261 }
1262 }
1263 }
1264 __catch (...)
1265 {
1266 _M_pathname.resize(orig_pathlen);
1267 if (orig_type == _Type::_Multi)
1268 {
1269 _M_cmpts._M_erase_from(_M_cmpts.begin() + orig_size);
1270 if (orig_filenamelen != -1)
1271 {
1272 auto& back = _M_cmpts.back();
1273 back._M_pathname.resize(orig_filenamelen);
1274 if (orig_filenamelen == 0)
1275 back._M_pos = orig_pathlen;
1276 }
1277 }
1278 else
1279 _M_cmpts.clear();
1280 _M_cmpts.type(orig_type);
1281 __throw_exception_again;
1282 }
1283 }
1284
1285 path&
1286 path::remove_filename()
1287 {
1288 if (_M_type() == _Type::_Multi)
1289 {
1290 if (!_M_cmpts.empty())
1291 {
1292 auto cmpt = std::prev(_M_cmpts.end());
1293 if (cmpt->_M_type() == _Type::_Filename && !cmpt->empty())
1294 {
1295 _M_pathname.erase(cmpt->_M_pos);
1296 auto prev = std::prev(cmpt);
1297 if (prev->_M_type() == _Type::_Root_dir
1298 || prev->_M_type() == _Type::_Root_name)
1299 {
1300 _M_cmpts.pop_back();
1301 if (_M_cmpts.size() == 1)
1302 {
1303 _M_cmpts.type(_M_cmpts.front()._M_type());
1304 _M_cmpts.clear();
1305 }
1306 }
1307 else
1308 cmpt->clear();
1309 }
1310 }
1311 }
1312 else if (_M_type() == _Type::_Filename)
1313 clear();
1314 return *this;
1315 }
1316
1317 path&
1318 path::replace_filename(const path& replacement)
1319 {
1320 remove_filename();
1321 operator/=(replacement);
1322 return *this;
1323 }
1324
1325 #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
1326 const fs::path::value_type dot = L'.';
1327 #else
1328 const fs::path::value_type dot = '.';
1329 #endif
1330
1331 path&
1332 path::replace_extension(const path& replacement)
1333 {
1334 auto ext = _M_find_extension();
1335 // Any existing extension() is removed
1336 if (ext.first && ext.second != string_type::npos)
1337 {
1338 if (ext.first == &_M_pathname)
1339 _M_pathname.erase(ext.second);
1340 else
1341 {
1342 auto& back = _M_cmpts.back();
1343 __glibcxx_assert( ext.first == &back._M_pathname );
1344 back._M_pathname.erase(ext.second);
1345 _M_pathname.erase(back._M_pos + ext.second);
1346 }
1347 }
1348 // If replacement is not empty and does not begin with a dot character,
1349 // a dot character is appended
1350 if (!replacement.empty() && replacement.native()[0] != dot)
1351 operator+=(".");
1352 operator+=(replacement);
1353 return *this;
1354 }
1355
1356 int
1357 path::compare(const path& p) const noexcept
1358 {
1359 if (_M_pathname == p._M_pathname)
1360 return 0;
1361
1362 basic_string_view<value_type> lroot, rroot;
1363 if (_M_type() == _Type::_Root_name)
1364 lroot = _M_pathname;
1365 else if (_M_type() == _Type::_Multi
1366 && _M_cmpts.front()._M_type() == _Type::_Root_name)
1367 lroot = _M_cmpts.front()._M_pathname;
1368 if (p._M_type() == _Type::_Root_name)
1369 rroot = p._M_pathname;
1370 else if (p._M_type() == _Type::_Multi
1371 && p._M_cmpts.front()._M_type() == _Type::_Root_name)
1372 rroot = p._M_cmpts.front()._M_pathname;
1373 if (int rootNameComparison = lroot.compare(rroot))
1374 return rootNameComparison;
1375
1376 if (!this->has_root_directory() && p.has_root_directory())
1377 return -1;
1378 else if (this->has_root_directory() && !p.has_root_directory())
1379 return +1;
1380
1381 using Iterator = const _Cmpt*;
1382 Iterator begin1, end1, begin2, end2;
1383 if (_M_type() == _Type::_Multi)
1384 {
1385 begin1 = _M_cmpts.begin();
1386 end1 = _M_cmpts.end();
1387 // Find start of this->relative_path()
1388 while (begin1 != end1 && begin1->_M_type() != _Type::_Filename)
1389 ++begin1;
1390 }
1391 else
1392 begin1 = end1 = nullptr;
1393
1394 if (p._M_type() == _Type::_Multi)
1395 {
1396 begin2 = p._M_cmpts.begin();
1397 end2 = p._M_cmpts.end();
1398 // Find start of p.relative_path()
1399 while (begin2 != end2 && begin2->_M_type() != _Type::_Filename)
1400 ++begin2;
1401 }
1402 else
1403 begin2 = end2 = nullptr;
1404
1405 if (_M_type() == _Type::_Filename)
1406 {
1407 if (p._M_type() == _Type::_Filename)
1408 return native().compare(p.native());
1409 else if (begin2 != end2)
1410 {
1411 if (int ret = native().compare(begin2->native()))
1412 return ret;
1413 else
1414 return ++begin2 == end2 ? 0 : -1;
1415 }
1416 else
1417 return +1;
1418 }
1419 else if (p._M_type() == _Type::_Filename)
1420 {
1421 if (begin1 != end1)
1422 {
1423 if (int ret = begin1->native().compare(p.native()))
1424 return ret;
1425 else
1426 return ++begin1 == end1 ? 0 : +1;
1427 }
1428 else
1429 return -1;
1430 }
1431
1432 int count = 1;
1433 while (begin1 != end1 && begin2 != end2)
1434 {
1435 if (int i = begin1->native().compare(begin2->native()))
1436 return i;
1437 ++begin1;
1438 ++begin2;
1439 ++count;
1440 }
1441 if (begin1 == end1)
1442 {
1443 if (begin2 == end2)
1444 return 0;
1445 return -count;
1446 }
1447 return count;
1448 }
1449
1450 int
1451 path::compare(basic_string_view<value_type> s) const noexcept
1452 {
1453 if (_M_pathname == s)
1454 return 0;
1455
1456 _Parser parser(s);
1457
1458 basic_string_view<value_type> lroot, rroot;
1459 if (_M_type() == _Type::_Root_name)
1460 lroot = _M_pathname;
1461 else if (_M_type() == _Type::_Multi
1462 && _M_cmpts.front()._M_type() == _Type::_Root_name)
1463 lroot = _M_cmpts.front()._M_pathname;
1464 auto root_path = parser.root_path();
1465 if (root_path.first.type == _Type::_Root_name)
1466 rroot = root_path.first.str;
1467 if (int rootNameComparison = lroot.compare(rroot))
1468 return rootNameComparison;
1469
1470 const bool has_root_dir = root_path.first.type == _Type::_Root_dir
1471 || root_path.second.type == _Type::_Root_dir;
1472 if (!this->has_root_directory() && has_root_dir)
1473 return -1;
1474 else if (this->has_root_directory() && !has_root_dir)
1475 return +1;
1476
1477 using Iterator = const _Cmpt*;
1478 Iterator begin1, end1;
1479 if (_M_type() == _Type::_Filename)
1480 {
1481 auto cmpt = parser.next();
1482 if (cmpt.valid())
1483 {
1484 if (int ret = this->native().compare(cmpt.str))
1485 return ret;
1486 return parser.next().valid() ? -1 : 0;
1487 }
1488 else
1489 return +1;
1490 }
1491 else if (_M_type() == _Type::_Multi)
1492 {
1493 begin1 = _M_cmpts.begin();
1494 end1 = _M_cmpts.end();
1495 while (begin1 != end1 && begin1->_M_type() != _Type::_Filename)
1496 ++begin1;
1497 }
1498 else
1499 begin1 = end1 = nullptr;
1500
1501 int count = 1;
1502 auto cmpt = parser.next();
1503 while (begin1 != end1 && cmpt.valid())
1504 {
1505 if (int i = begin1->native().compare(cmpt.str))
1506 return i;
1507 ++begin1;
1508 cmpt = parser.next();
1509 ++count;
1510 }
1511 if (begin1 == end1)
1512 {
1513 if (!cmpt.valid())
1514 return 0;
1515 return -count;
1516 }
1517 return +count;
1518 }
1519
1520 path
1521 path::root_name() const
1522 {
1523 path __ret;
1524 if (_M_type() == _Type::_Root_name)
1525 __ret = *this;
1526 else if (_M_cmpts.size() && _M_cmpts.begin()->_M_type() == _Type::_Root_name)
1527 __ret = *_M_cmpts.begin();
1528 return __ret;
1529 }
1530
1531 path
1532 path::root_directory() const
1533 {
1534 path __ret;
1535 if (_M_type() == _Type::_Root_dir)
1536 {
1537 __ret._M_cmpts.type(_Type::_Root_dir);
1538 __ret._M_pathname.assign(1, preferred_separator);
1539 }
1540 else if (!_M_cmpts.empty())
1541 {
1542 auto __it = _M_cmpts.begin();
1543 if (__it->_M_type() == _Type::_Root_name)
1544 ++__it;
1545 if (__it != _M_cmpts.end() && __it->_M_type() == _Type::_Root_dir)
1546 __ret = *__it;
1547 }
1548 return __ret;
1549 }
1550
1551 path
1552 path::root_path() const
1553 {
1554 path __ret;
1555 if (_M_type() == _Type::_Root_name)
1556 __ret = *this;
1557 else if (_M_type() == _Type::_Root_dir)
1558 {
1559 __ret._M_pathname.assign(1, preferred_separator);
1560 __ret._M_cmpts.type(_Type::_Root_dir);
1561 }
1562 else if (!_M_cmpts.empty())
1563 {
1564 auto __it = _M_cmpts.begin();
1565 if (__it->_M_type() == _Type::_Root_name)
1566 {
1567 __ret = *__it++;
1568 if (__it != _M_cmpts.end() && __it->_M_type() == _Type::_Root_dir)
1569 __ret /= *__it;
1570 }
1571 else if (__it->_M_type() == _Type::_Root_dir)
1572 __ret = *__it;
1573 }
1574 return __ret;
1575 }
1576
1577 path
1578 path::relative_path() const
1579 {
1580 path __ret;
1581 if (_M_type() == _Type::_Filename)
1582 __ret = *this;
1583 else if (!_M_cmpts.empty())
1584 {
1585 auto __it = _M_cmpts.begin();
1586 if (__it->_M_type() == _Type::_Root_name)
1587 ++__it;
1588 if (__it != _M_cmpts.end() && __it->_M_type() == _Type::_Root_dir)
1589 ++__it;
1590 if (__it != _M_cmpts.end())
1591 __ret.assign(_M_pathname.substr(__it->_M_pos));
1592 }
1593 return __ret;
1594 }
1595
1596 path
1597 path::parent_path() const
1598 {
1599 path __ret;
1600 if (!has_relative_path())
1601 __ret = *this;
1602 else if (_M_cmpts.size() >= 2)
1603 {
1604 const auto parent = std::prev(_M_cmpts.end(), 2);
1605 const auto len = parent->_M_pos + parent->_M_pathname.length();
1606 __ret.assign(_M_pathname.substr(0, len));
1607 }
1608 return __ret;
1609 }
1610
1611 bool
1612 path::has_root_name() const noexcept
1613 {
1614 if (_M_type() == _Type::_Root_name)
1615 return true;
1616 if (!_M_cmpts.empty() && _M_cmpts.begin()->_M_type() == _Type::_Root_name)
1617 return true;
1618 return false;
1619 }
1620
1621 bool
1622 path::has_root_directory() const noexcept
1623 {
1624 if (_M_type() == _Type::_Root_dir)
1625 return true;
1626 if (!_M_cmpts.empty())
1627 {
1628 auto __it = _M_cmpts.begin();
1629 if (__it->_M_type() == _Type::_Root_name)
1630 ++__it;
1631 if (__it != _M_cmpts.end() && __it->_M_type() == _Type::_Root_dir)
1632 return true;
1633 }
1634 return false;
1635 }
1636
1637 bool
1638 path::has_root_path() const noexcept
1639 {
1640 if (_M_type() == _Type::_Root_name || _M_type() == _Type::_Root_dir)
1641 return true;
1642 if (!_M_cmpts.empty())
1643 {
1644 auto __type = _M_cmpts.front()._M_type();
1645 if (__type == _Type::_Root_name || __type == _Type::_Root_dir)
1646 return true;
1647 }
1648 return false;
1649 }
1650
1651 bool
1652 path::has_relative_path() const noexcept
1653 {
1654 if (_M_type() == _Type::_Filename && !_M_pathname.empty())
1655 return true;
1656 if (!_M_cmpts.empty())
1657 {
1658 auto __it = _M_cmpts.begin();
1659 if (__it->_M_type() == _Type::_Root_name)
1660 ++__it;
1661 if (__it != _M_cmpts.end() && __it->_M_type() == _Type::_Root_dir)
1662 ++__it;
1663 if (__it != _M_cmpts.end() && !__it->_M_pathname.empty())
1664 return true;
1665 }
1666 return false;
1667 }
1668
1669
1670 bool
1671 path::has_parent_path() const noexcept
1672 {
1673 if (!has_relative_path())
1674 return !empty();
1675 return _M_cmpts.size() >= 2;
1676 }
1677
1678 bool
1679 path::has_filename() const noexcept
1680 {
1681 if (empty())
1682 return false;
1683 if (_M_type() == _Type::_Filename)
1684 return !_M_pathname.empty();
1685 if (_M_type() == _Type::_Multi)
1686 {
1687 if (_M_pathname.back() == preferred_separator)
1688 return false;
1689 return _M_cmpts.back().has_filename();
1690 }
1691 return false;
1692 }
1693
1694 namespace
1695 {
1696 inline bool is_dot(fs::path::value_type c) { return c == dot; }
1697
1698 inline bool is_dot(const fs::path& path)
1699 {
1700 const auto& filename = path.native();
1701 return filename.size() == 1 && is_dot(filename[0]);
1702 }
1703
1704 inline bool is_dotdot(const fs::path& path)
1705 {
1706 const auto& filename = path.native();
1707 return filename.size() == 2 && is_dot(filename[0]) && is_dot(filename[1]);
1708 }
1709 } // namespace
1710
1711 path
1712 path::lexically_normal() const
1713 {
1714 /*
1715 C++17 [fs.path.generic] p6
1716 - If the path is empty, stop.
1717 - Replace each slash character in the root-name with a preferred-separator.
1718 - Replace each directory-separator with a preferred-separator.
1719 - Remove each dot filename and any immediately following directory-separator.
1720 - As long as any appear, remove a non-dot-dot filename immediately followed
1721 by a directory-separator and a dot-dot filename, along with any immediately
1722 following directory-separator.
1723 - If there is a root-directory, remove all dot-dot filenames and any
1724 directory-separators immediately following them.
1725 - If the last filename is dot-dot, remove any trailing directory-separator.
1726 - If the path is empty, add a dot.
1727 */
1728 path ret;
1729 // If the path is empty, stop.
1730 if (empty())
1731 return ret;
1732 for (auto& p : *this)
1733 {
1734 #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
1735 // Replace each slash character in the root-name
1736 if (p._M_type() == _Type::_Root_name || p._M_type() == _Type::_Root_dir)
1737 {
1738 string_type s = p.native();
1739 std::replace(s.begin(), s.end(), L'/', L'\\');
1740 ret /= s;
1741 continue;
1742 }
1743 #endif
1744 if (is_dotdot(p))
1745 {
1746 if (ret.has_filename())
1747 {
1748 // remove a non-dot-dot filename immediately followed by /..
1749 if (!is_dotdot(ret.filename()))
1750 ret.remove_filename();
1751 else
1752 ret /= p;
1753 }
1754 else if (!ret.has_relative_path())
1755 {
1756 // remove a dot-dot filename immediately after root-directory
1757 if (!ret.has_root_directory())
1758 ret /= p;
1759 }
1760 else
1761 {
1762 // Got a path with a relative path (i.e. at least one non-root
1763 // element) and no filename at the end (i.e. empty last element),
1764 // so must have a trailing slash. See what is before it.
1765 auto elem = ret._M_cmpts.end() - 2;
1766 if (elem->has_filename() && !is_dotdot(*elem))
1767 {
1768 // Remove the filename before the trailing slash
1769 // (equiv. to ret = ret.parent_path().remove_filename())
1770
1771 if (elem == ret._M_cmpts.begin())
1772 ret.clear();
1773 else
1774 {
1775 ret._M_pathname.erase(elem->_M_pos);
1776 // Remove empty filename at the end:
1777 ret._M_cmpts.pop_back();
1778 // If we still have a trailing non-root dir separator
1779 // then leave an empty filename at the end:
1780 if (std::prev(elem)->_M_type() == _Type::_Filename)
1781 elem->clear();
1782 else // remove the component completely:
1783 ret._M_cmpts.pop_back();
1784 }
1785 }
1786 else
1787 // Append the ".." to something ending in "../" which happens
1788 // when normalising paths like ".././.." and "../a/../.."
1789 ret /= p;
1790 }
1791 }
1792 else if (is_dot(p))
1793 ret /= path();
1794 #if SLASHSLASH_IS_ROOTNAME
1795 else if (p._M_type() == _Type::_Root_dir)
1796 ret += '/'; // using operator/=('/') would replace whole of ret
1797 #endif
1798 else
1799 ret /= p;
1800 }
1801
1802 if (ret._M_cmpts.size() >= 2)
1803 {
1804 auto back = std::prev(ret.end());
1805 // If the last filename is dot-dot, ...
1806 if (back->empty() && is_dotdot(*std::prev(back)))
1807 // ... remove any trailing directory-separator.
1808 ret = ret.parent_path();
1809 }
1810 // If the path is empty, add a dot.
1811 else if (ret.empty())
1812 ret = ".";
1813
1814 return ret;
1815 }
1816
1817 path
1818 path::lexically_relative(const path& base) const
1819 {
1820 path ret;
1821 if (root_name() != base.root_name())
1822 return ret;
1823 if (is_absolute() != base.is_absolute())
1824 return ret;
1825 if (!has_root_directory() && base.has_root_directory())
1826 return ret;
1827 auto [a, b] = std::mismatch(begin(), end(), base.begin(), base.end());
1828 #ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
1829 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1830 // 3070. path::lexically_relative causes surprising results if a filename
1831 // can also be a root-name
1832 if (!empty())
1833 for (auto& p : _M_cmpts)
1834 if (p._M_type() == _Type::_Filename && is_disk_designator(p.native()))
1835 return ret;
1836 if (!base.empty())
1837 for (auto i = b, end = base.end(); i != end; ++i)
1838 if (i->_M_type() == _Type::_Filename && is_disk_designator(i->native()))
1839 return ret;
1840 #endif
1841 if (a == end() && b == base.end())
1842 ret = ".";
1843 else
1844 {
1845 int n = 0;
1846 for (; b != base.end(); ++b)
1847 {
1848 const path& p = *b;
1849 if (is_dotdot(p))
1850 --n;
1851 else if (!p.empty() && !is_dot(p))
1852 ++n;
1853 }
1854 if (n == 0 && (a == end() || a->empty()))
1855 ret = ".";
1856 else if (n >= 0)
1857 {
1858 const path dotdot("..");
1859 while (n--)
1860 ret /= dotdot;
1861 for (; a != end(); ++a)
1862 ret /= *a;
1863 }
1864 }
1865 return ret;
1866 }
1867
1868 path
1869 path::lexically_proximate(const path& base) const
1870 {
1871 path rel = lexically_relative(base);
1872 if (rel.empty())
1873 rel = *this;
1874 return rel;
1875 }
1876
1877 std::pair<const path::string_type*, std::size_t>
1878 path::_M_find_extension() const noexcept
1879 {
1880 const string_type* s = nullptr;
1881
1882 if (_M_type() == _Type::_Filename)
1883 s = &_M_pathname;
1884 else if (_M_type() == _Type::_Multi && !_M_cmpts.empty())
1885 {
1886 const auto& c = _M_cmpts.back();
1887 if (c._M_type() == _Type::_Filename)
1888 s = &c._M_pathname;
1889 }
1890
1891 if (s)
1892 {
1893 if (auto sz = s->size())
1894 {
1895 if (sz <= 2 && (*s)[0] == dot)
1896 return { s, string_type::npos };
1897 if (const auto pos = s->rfind(dot))
1898 return { s , pos };
1899 return { s, string_type::npos };
1900 }
1901 }
1902 return {};
1903 }
1904
1905 void
1906 path::_M_split_cmpts()
1907 {
1908 _M_cmpts.clear();
1909
1910 if (_M_pathname.empty())
1911 {
1912 _M_cmpts.type(_Type::_Filename);
1913 return;
1914 }
1915
1916 _Parser parser(_M_pathname);
1917
1918 std::array<_Parser::cmpt, 64> buf;
1919 auto next = buf.begin();
1920
1921 // look for root name or root directory
1922 auto root_path = parser.root_path();
1923 if (root_path.first.valid())
1924 {
1925 *next++ = root_path.first;
1926 if (root_path.second.valid())
1927 *next++ = root_path.second;
1928 }
1929
1930 auto cmpt = parser.next();
1931 while (cmpt.valid())
1932 {
1933 do
1934 {
1935 *next++ = cmpt;
1936 cmpt = parser.next();
1937 }
1938 while (cmpt.valid() && next != buf.end());
1939
1940 if (next == buf.end())
1941 {
1942 _M_cmpts.type(_Type::_Multi);
1943 _M_cmpts.reserve(_M_cmpts.size() + buf.size());
1944 auto output = _M_cmpts._M_impl->end();
1945 for (const auto& c : buf)
1946 {
1947 ::new(output++) _Cmpt(c.str, c.type, parser.offset(c));
1948 ++_M_cmpts._M_impl->_M_size;
1949 }
1950 next = buf.begin();
1951 }
1952 }
1953
1954 if (auto n = next - buf.begin())
1955 {
1956 if (n == 1 && _M_cmpts.empty())
1957 {
1958 _M_cmpts.type(buf.front().type);
1959 return;
1960 }
1961
1962 _M_cmpts.type(_Type::_Multi);
1963 _M_cmpts.reserve(_M_cmpts.size() + n, true);
1964 auto output = _M_cmpts._M_impl->end();
1965 for (int i = 0; i < n; ++i)
1966 {
1967 const auto& c = buf[i];
1968 ::new(output++) _Cmpt(c.str, c.type, parser.offset(c));
1969 ++_M_cmpts._M_impl->_M_size;
1970 }
1971 }
1972 }
1973
1974 path::string_type
1975 path::_S_convert_loc(const char* __first, const char* __last,
1976 [[maybe_unused]] const std::locale& __loc)
1977 {
1978 #if _GLIBCXX_USE_WCHAR_T
1979 auto& __cvt = std::use_facet<codecvt<wchar_t, char, mbstate_t>>(__loc);
1980 basic_string<wchar_t> __ws;
1981 if (!__str_codecvt_in_all(__first, __last, __ws, __cvt))
1982 _GLIBCXX_THROW_OR_ABORT(filesystem_error(
1983 "Cannot convert character sequence",
1984 std::make_error_code(errc::illegal_byte_sequence)));
1985 return _S_convert(std::move(__ws));
1986 #else
1987 return {__first, __last};
1988 #endif
1989 }
1990
1991 std::size_t
1992 fs::hash_value(const path& p) noexcept
1993 {
1994 // [path.non-member]
1995 // "If for two paths, p1 == p2 then hash_value(p1) == hash_value(p2)."
1996 // Equality works as if by traversing the range [begin(), end()), meaning
1997 // e.g. path("a//b") == path("a/b"), so we cannot simply hash _M_pathname
1998 // but need to iterate over individual elements. Use the hash_combine from
1999 // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3876.pdf
2000 size_t seed = 0;
2001 for (const auto& x : p)
2002 {
2003 seed ^= std::hash<path::string_type>()(x.native()) + 0x9e3779b9
2004 + (seed<<6) + (seed>>2);
2005 }
2006 return seed;
2007 }
2008
2009 struct fs::filesystem_error::_Impl
2010 {
2011 _Impl(string_view what_arg, const path& p1, const path& p2)
2012 : path1(p1), path2(p2), what(make_what(what_arg, &p1, &p2))
2013 { }
2014
2015 _Impl(string_view what_arg, const path& p1)
2016 : path1(p1), path2(), what(make_what(what_arg, &p1, nullptr))
2017 { }
2018
2019 _Impl(string_view what_arg)
2020 : what(make_what(what_arg, nullptr, nullptr))
2021 { }
2022
2023 static std::string
2024 make_what(string_view s, const path* p1, const path* p2)
2025 {
2026 const std::string pstr1 = p1 ? p1->u8string() : std::string{};
2027 const std::string pstr2 = p2 ? p2->u8string() : std::string{};
2028 const size_t len = 18 + s.length()
2029 + (pstr1.length() ? pstr1.length() + 3 : 0)
2030 + (pstr2.length() ? pstr2.length() + 3 : 0);
2031 std::string w;
2032 w.reserve(len);
2033 w = "filesystem error: ";
2034 w += s;
2035 if (p1)
2036 {
2037 w += " [";
2038 w += pstr1;
2039 w += ']';
2040 if (p2)
2041 {
2042 w += " [";
2043 w += pstr2;
2044 w += ']';
2045 }
2046 }
2047 return w;
2048 }
2049
2050 path path1;
2051 path path2;
2052 std::string what;
2053 };
2054
2055 template class std::__shared_ptr<const fs::filesystem_error::_Impl>;
2056
2057 fs::filesystem_error::
2058 filesystem_error(const string& what_arg, error_code ec)
2059 : system_error(ec, what_arg),
2060 _M_impl(std::__make_shared<_Impl>(system_error::what()))
2061 { }
2062
2063 fs::filesystem_error::
2064 filesystem_error(const string& what_arg, const path& p1, error_code ec)
2065 : system_error(ec, what_arg),
2066 _M_impl(std::__make_shared<_Impl>(system_error::what(), p1))
2067 { }
2068
2069 fs::filesystem_error::
2070 filesystem_error(const string& what_arg, const path& p1, const path& p2,
2071 error_code ec)
2072 : system_error(ec, what_arg),
2073 _M_impl(std::__make_shared<_Impl>(system_error::what(), p1, p2))
2074 { }
2075
2076 fs::filesystem_error::~filesystem_error() = default;
2077
2078 const fs::path&
2079 fs::filesystem_error::path1() const noexcept
2080 { return _M_impl->path1; }
2081
2082 const fs::path&
2083 fs::filesystem_error::path2() const noexcept
2084 { return _M_impl->path2; }
2085
2086 const char*
2087 fs::filesystem_error::what() const noexcept
2088 { return _M_impl->what.c_str(); }