1#![stable(feature = "rust1", since = "1.0.0")]
82#![deny(unsafe_op_in_unsafe_fn)]
83
84use core::clone::CloneToUninit;
85
86use crate::alloc::Allocator;
87use crate::borrow::{Borrow, Cow};
88use crate::collections::TryReserveError;
89use crate::error::Error;
90use crate::ffi::{OsStr, OsString, os_str};
91use crate::hash::{Hash, Hasher};
92use crate::iter::FusedIterator;
93use crate::ops::{self, Deref};
94use crate::rc::Rc;
95use crate::str::FromStr;
96use crate::sync::Arc;
97use crate::sys::path::{HAS_PREFIXES, is_sep_byte, is_verbatim_sep, parse_prefix};
98use crate::{cmp, fmt, fs, io, sys};
99
100#[derive(#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::marker::Copy for Prefix<'a> { }Copy, #[automatically_derived]
#[doc(hidden)]
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<'a> ::core::clone::TrivialClone for Prefix<'a> { }
#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::clone::Clone for Prefix<'a> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<&'a OsStr>;
let _: ::core::clone::AssertParamIsClone<&'a OsStr>;
let _: ::core::clone::AssertParamIsClone<&'a OsStr>;
let _: ::core::clone::AssertParamIsClone<u8>;
let _: ::core::clone::AssertParamIsClone<&'a OsStr>;
let _: ::core::clone::AssertParamIsClone<&'a OsStr>;
let _: ::core::clone::AssertParamIsClone<&'a OsStr>;
*self
}
}Clone, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::fmt::Debug for Prefix<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Verbatim(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Verbatim", &__self_0),
Self::VerbatimUNC(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"VerbatimUNC", __self_0, &__self_1),
Self::VerbatimDisk(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"VerbatimDisk", &__self_0),
Self::DeviceNS(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DeviceNS", &__self_0),
Self::UNC(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f, "UNC",
__self_0, &__self_1),
Self::Disk(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Disk",
&__self_0),
}
}
}Debug, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::hash::Hash for Prefix<'a> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::Verbatim(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::VerbatimUNC(__self_0, __self_1) => {
::core::hash::Hash::hash(__self_0, state);
::core::hash::Hash::hash(__self_1, state)
}
Self::VerbatimDisk(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::DeviceNS(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::UNC(__self_0, __self_1) => {
::core::hash::Hash::hash(__self_0, state);
::core::hash::Hash::hash(__self_1, state)
}
Self::Disk(__self_0) => ::core::hash::Hash::hash(__self_0, state),
}
}
}Hash, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::cmp::PartialOrd for Prefix<'a> {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::cmp::Ord for Prefix<'a> {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
match (self, other) {
(Self::Verbatim(__self_0), Self::Verbatim(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(Self::VerbatimUNC(__self_0, __self_1),
Self::VerbatimUNC(__arg1_0, __arg1_1)) =>
match ::core::cmp::Ord::cmp(__self_0, __arg1_0) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(__self_1, __arg1_1),
cmp => cmp,
},
(Self::VerbatimDisk(__self_0), Self::VerbatimDisk(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(Self::DeviceNS(__self_0), Self::DeviceNS(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(Self::UNC(__self_0, __self_1), Self::UNC(__arg1_0, __arg1_1)) =>
match ::core::cmp::Ord::cmp(__self_0, __arg1_0) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(__self_1, __arg1_1),
cmp => cmp,
},
(Self::Disk(__self_0), Self::Disk(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
_ =>
::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
&::core::intrinsics::discriminant_value(other)),
}
}
}Ord, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::marker::StructuralPartialEq for Prefix<'a> { }
#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::cmp::PartialEq for Prefix<'a> {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Verbatim(__self_0), Self::Verbatim(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::VerbatimUNC(__self_0, __self_1),
Self::VerbatimUNC(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(Self::VerbatimDisk(__self_0), Self::VerbatimDisk(__arg1_0))
=> __self_0 == __arg1_0,
(Self::DeviceNS(__self_0), Self::DeviceNS(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::UNC(__self_0, __self_1), Self::UNC(__arg1_0, __arg1_1))
=> __self_0 == __arg1_0 && __self_1 == __arg1_1,
(Self::Disk(__self_0), Self::Disk(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::cmp::Eq for Prefix<'a> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<&'a OsStr>;
let _: ::core::cmp::AssertParamIsEq<&'a OsStr>;
let _: ::core::cmp::AssertParamIsEq<&'a OsStr>;
let _: ::core::cmp::AssertParamIsEq<u8>;
let _: ::core::cmp::AssertParamIsEq<&'a OsStr>;
let _: ::core::cmp::AssertParamIsEq<&'a OsStr>;
let _: ::core::cmp::AssertParamIsEq<&'a OsStr>;
}
}Eq)]
151#[stable(feature = "rust1", since = "1.0.0")]
152pub enum Prefix<'a> {
153 #[stable(feature = "rust1", since = "1.0.0")]
158 Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
159
160 #[stable(feature = "rust1", since = "1.0.0")]
166 VerbatimUNC(
167 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
168 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
169 ),
170
171 #[stable(feature = "rust1", since = "1.0.0")]
176 VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8),
177
178 #[stable(feature = "rust1", since = "1.0.0")]
183 DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
184
185 #[stable(feature = "rust1", since = "1.0.0")]
190 UNC(
191 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
192 #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr,
193 ),
194
195 #[stable(feature = "rust1", since = "1.0.0")]
197 Disk(#[stable(feature = "rust1", since = "1.0.0")] u8),
198}
199
200impl<'a> Prefix<'a> {
201 #[inline]
202 fn len(&self) -> usize {
203 use self::Prefix::*;
204 fn os_str_len(s: &OsStr) -> usize {
205 s.as_encoded_bytes().len()
206 }
207 match *self {
208 Verbatim(x) => 4 + os_str_len(x),
209 VerbatimUNC(x, y) => {
210 8 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 }
211 }
212 VerbatimDisk(_) => 6,
213 UNC(x, y) => 2 + os_str_len(x) + if os_str_len(y) > 0 { 1 + os_str_len(y) } else { 0 },
214 DeviceNS(x) => 4 + os_str_len(x),
215 Disk(_) => 2,
216 }
217 }
218
219 #[inline]
235 #[must_use]
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn is_verbatim(&self) -> bool {
238 use self::Prefix::*;
239 #[allow(non_exhaustive_omitted_patterns)] match *self {
Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true,
_ => false,
}matches!(*self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
240 }
241
242 #[inline]
243 fn is_drive(&self) -> bool {
244 #[allow(non_exhaustive_omitted_patterns)] match *self {
Prefix::Disk(_) => true,
_ => false,
}matches!(*self, Prefix::Disk(_))
245 }
246
247 #[inline]
248 fn has_implicit_root(&self) -> bool {
249 !self.is_drive()
250 }
251}
252
253#[must_use]
269#[stable(feature = "rust1", since = "1.0.0")]
270#[rustc_const_unstable(feature = "const_path_separators", issue = "153106")]
271pub const fn is_separator(c: char) -> bool {
272 c.is_ascii() && is_sep_byte(c as u8)
273}
274
275#[unstable(feature = "const_path_separators", issue = "153106")]
279pub const SEPARATORS: &[char] = crate::sys::path::SEPARATORS;
280
281#[unstable(feature = "const_path_separators", issue = "153106")]
285pub const SEPARATORS_STR: &[&str] = crate::sys::path::SEPARATORS_STR;
286
287#[stable(feature = "rust1", since = "1.0.0")]
290#[cfg_attr(not(test), rustc_diagnostic_item = "path_main_separator")]
291pub const MAIN_SEPARATOR: char = SEPARATORS[0];
292
293#[stable(feature = "main_separator_str", since = "1.68.0")]
296pub const MAIN_SEPARATOR_STR: &str = SEPARATORS_STR[0];
297
298fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
306where
307 I: Iterator<Item = Component<'a>> + Clone,
308 J: Iterator<Item = Component<'b>>,
309{
310 loop {
311 let mut iter_next = iter.clone();
312 match (iter_next.next(), prefix.next()) {
313 (Some(ref x), Some(ref y)) if x == y => (),
314 (Some(_), Some(_)) => return None,
315 (Some(_), None) => return Some(iter),
316 (None, None) => return Some(iter),
317 (None, Some(_)) => return None,
318 }
319 iter = iter_next;
320 }
321}
322
323fn has_physical_root(s: &[u8], prefix: Option<Prefix<'_>>) -> bool {
329 let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
330 !path.is_empty() && is_sep_byte(path[0])
331}
332
333fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
335 if file.as_encoded_bytes() == b".." {
336 return (Some(file), None);
337 }
338
339 let mut iter = file.as_encoded_bytes().rsplitn(2, |b| *b == b'.');
344 let after = iter.next();
345 let before = iter.next();
346 if before == Some(b"") {
347 (Some(file), None)
348 } else {
349 unsafe {
350 (
351 before.map(|s| OsStr::from_encoded_bytes_unchecked(s)),
352 after.map(|s| OsStr::from_encoded_bytes_unchecked(s)),
353 )
354 }
355 }
356}
357
358fn split_file_at_dot(file: &OsStr) -> (&OsStr, Option<&OsStr>) {
359 let slice = file.as_encoded_bytes();
360 if slice == b".." {
361 return (file, None);
362 }
363
364 let i = match slice[1..].iter().position(|b| *b == b'.') {
369 Some(i) => i + 1,
370 None => return (file, None),
371 };
372 let before = &slice[..i];
373 let after = &slice[i + 1..];
374 unsafe {
375 (
376 OsStr::from_encoded_bytes_unchecked(before),
377 Some(OsStr::from_encoded_bytes_unchecked(after)),
378 )
379 }
380}
381
382fn validate_extension(extension: &OsStr) {
384 for &b in extension.as_encoded_bytes() {
385 if is_sep_byte(b) {
386 {
::core::panicking::panic_fmt(format_args!("extension cannot contain path separators: {0:?}",
extension));
};panic!("extension cannot contain path separators: {extension:?}");
387 }
388 }
389}
390
391#[derive(#[automatically_derived]
impl ::core::marker::Copy for State { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for State { }
#[automatically_derived]
impl ::core::clone::Clone for State {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for State { }
#[automatically_derived]
impl ::core::cmp::PartialEq for State {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::PartialOrd for State {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::cmp::PartialOrd::partial_cmp(&::core::intrinsics::discriminant_value(self),
&::core::intrinsics::discriminant_value(other))
}
}PartialOrd, #[automatically_derived]
impl ::core::fmt::Debug for State {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
State::Prefix => "Prefix",
State::StartDir => "StartDir",
State::Body => "Body",
State::Done => "Done",
})
}
}Debug)]
402enum State {
403 Prefix = 0, StartDir = 1, Body = 2, Done = 3,
407}
408
409#[stable(feature = "rust1", since = "1.0.0")]
443#[derive(#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::marker::Copy for PrefixComponent<'a> { }Copy, #[automatically_derived]
#[doc(hidden)]
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<'a> ::core::clone::TrivialClone for PrefixComponent<'a> { }
#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::clone::Clone for PrefixComponent<'a> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<&'a OsStr>;
let _: ::core::clone::AssertParamIsClone<Prefix<'a>>;
*self
}
}Clone, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::cmp::Eq for PrefixComponent<'a> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<&'a OsStr>;
let _: ::core::cmp::AssertParamIsEq<Prefix<'a>>;
}
}Eq, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::fmt::Debug for PrefixComponent<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"PrefixComponent", "raw", &self.raw, "parsed", &&self.parsed)
}
}Debug)]
444pub struct PrefixComponent<'a> {
445 raw: &'a OsStr,
447
448 parsed: Prefix<'a>,
450}
451
452impl<'a> PrefixComponent<'a> {
453 #[stable(feature = "rust1", since = "1.0.0")]
458 #[must_use]
459 #[inline]
460 pub fn kind(&self) -> Prefix<'a> {
461 self.parsed
462 }
463
464 #[stable(feature = "rust1", since = "1.0.0")]
466 #[must_use]
467 #[inline]
468 pub fn as_os_str(&self) -> &'a OsStr {
469 self.raw
470 }
471}
472
473#[stable(feature = "rust1", since = "1.0.0")]
474impl<'a> PartialEq for PrefixComponent<'a> {
475 #[inline]
476 fn eq(&self, other: &PrefixComponent<'a>) -> bool {
477 self.parsed == other.parsed
478 }
479}
480
481#[stable(feature = "rust1", since = "1.0.0")]
482impl<'a> PartialOrd for PrefixComponent<'a> {
483 #[inline]
484 fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> {
485 PartialOrd::partial_cmp(&self.parsed, &other.parsed)
486 }
487}
488
489#[stable(feature = "rust1", since = "1.0.0")]
490impl Ord for PrefixComponent<'_> {
491 #[inline]
492 fn cmp(&self, other: &Self) -> cmp::Ordering {
493 Ord::cmp(&self.parsed, &other.parsed)
494 }
495}
496
497#[stable(feature = "rust1", since = "1.0.0")]
498impl Hash for PrefixComponent<'_> {
499 fn hash<H: Hasher>(&self, h: &mut H) {
500 self.parsed.hash(h);
501 }
502}
503
504#[derive(#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::marker::Copy for Component<'a> { }Copy, #[automatically_derived]
#[doc(hidden)]
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<'a> ::core::clone::TrivialClone for Component<'a> { }
#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::clone::Clone for Component<'a> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<PrefixComponent<'a>>;
let _: ::core::clone::AssertParamIsClone<&'a OsStr>;
*self
}
}Clone, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::marker::StructuralPartialEq for Component<'a> { }
#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::cmp::PartialEq for Component<'a> {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Prefix(__self_0), Self::Prefix(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Normal(__self_0), Self::Normal(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::cmp::Eq for Component<'a> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<PrefixComponent<'a>>;
let _: ::core::cmp::AssertParamIsEq<&'a OsStr>;
}
}Eq, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::cmp::PartialOrd for Component<'a> {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::cmp::Ord for Component<'a> {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
match (self, other) {
(Self::Prefix(__self_0), Self::Prefix(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(Self::Normal(__self_0), Self::Normal(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
_ =>
::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
&::core::intrinsics::discriminant_value(other)),
}
}
}Ord, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::hash::Hash for Component<'a> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::Prefix(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::Normal(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::fmt::Debug for Component<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Prefix(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Prefix",
&__self_0),
Self::RootDir => ::core::fmt::Formatter::write_str(f, "RootDir"),
Self::CurDir => ::core::fmt::Formatter::write_str(f, "CurDir"),
Self::ParentDir =>
::core::fmt::Formatter::write_str(f, "ParentDir"),
Self::Normal(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Normal",
&__self_0),
}
}
}Debug)]
527#[stable(feature = "rust1", since = "1.0.0")]
528pub enum Component<'a> {
529 #[stable(feature = "rust1", since = "1.0.0")]
536 Prefix(#[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a>),
537
538 #[stable(feature = "rust1", since = "1.0.0")]
542 RootDir,
543
544 #[stable(feature = "rust1", since = "1.0.0")]
546 CurDir,
547
548 #[stable(feature = "rust1", since = "1.0.0")]
550 ParentDir,
551
552 #[stable(feature = "rust1", since = "1.0.0")]
557 Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr),
558}
559
560impl<'a> Component<'a> {
561 #[must_use = "`self` will be dropped if the result is not used"]
573 #[stable(feature = "rust1", since = "1.0.0")]
574 pub fn as_os_str(self) -> &'a OsStr {
575 match self {
576 Component::Prefix(p) => p.as_os_str(),
577 Component::RootDir => OsStr::new(MAIN_SEPARATOR_STR),
578 Component::CurDir => OsStr::new("."),
579 Component::ParentDir => OsStr::new(".."),
580 Component::Normal(path) => path,
581 }
582 }
583}
584
585#[stable(feature = "rust1", since = "1.0.0")]
586impl AsRef<OsStr> for Component<'_> {
587 #[inline]
588 fn as_ref(&self) -> &OsStr {
589 self.as_os_str()
590 }
591}
592
593#[stable(feature = "path_component_asref", since = "1.25.0")]
594impl AsRef<Path> for Component<'_> {
595 #[inline]
596 fn as_ref(&self) -> &Path {
597 self.as_os_str().as_ref()
598 }
599}
600
601#[derive(#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::clone::Clone for Components<'a> {
#[inline]
fn clone(&self) -> Self {
Components {
path: ::core::clone::Clone::clone(&self.path),
prefix: ::core::clone::Clone::clone(&self.prefix),
has_physical_root: ::core::clone::Clone::clone(&self.has_physical_root),
front: ::core::clone::Clone::clone(&self.front),
back: ::core::clone::Clone::clone(&self.back),
}
}
}Clone)]
620#[must_use = "iterators are lazy and do nothing unless consumed"]
621#[stable(feature = "rust1", since = "1.0.0")]
622pub struct Components<'a> {
623 path: &'a [u8],
625
626 prefix: Option<Prefix<'a>>,
628
629 has_physical_root: bool,
633
634 front: State,
637 back: State,
638}
639
640#[derive(#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> ::core::clone::Clone for Iter<'a> {
#[inline]
fn clone(&self) -> Self {
Iter { inner: ::core::clone::Clone::clone(&self.inner) }
}
}Clone)]
647#[must_use = "iterators are lazy and do nothing unless consumed"]
648#[stable(feature = "rust1", since = "1.0.0")]
649pub struct Iter<'a> {
650 inner: Components<'a>,
651}
652
653#[stable(feature = "path_components_debug", since = "1.13.0")]
654impl fmt::Debug for Components<'_> {
655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656 struct DebugHelper<'a>(&'a Path);
657
658 impl fmt::Debug for DebugHelper<'_> {
659 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
660 f.debug_list().entries(self.0.components()).finish()
661 }
662 }
663
664 f.debug_tuple("Components").field(&DebugHelper(self.as_path())).finish()
665 }
666}
667
668impl<'a> Components<'a> {
669 #[inline]
671 fn prefix_len(&self) -> usize {
672 if !HAS_PREFIXES {
673 return 0;
674 }
675 self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
676 }
677
678 #[inline]
679 fn prefix_verbatim(&self) -> bool {
680 if !HAS_PREFIXES {
681 return false;
682 }
683 self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false)
684 }
685
686 #[inline]
688 fn prefix_remaining(&self) -> usize {
689 if !HAS_PREFIXES {
690 return 0;
691 }
692 if self.front == State::Prefix { self.prefix_len() } else { 0 }
693 }
694
695 #[inline]
697 fn len_before_body(&self) -> usize {
698 let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 };
699 let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 };
700 self.prefix_remaining() + root + cur_dir
701 }
702
703 #[inline]
705 fn finished(&self) -> bool {
706 self.front == State::Done || self.back == State::Done || self.front > self.back
707 }
708
709 #[inline]
710 fn is_sep_byte(&self, b: u8) -> bool {
711 if self.prefix_verbatim() { is_verbatim_sep(b) } else { is_sep_byte(b) }
712 }
713
714 #[must_use]
728 #[stable(feature = "rust1", since = "1.0.0")]
729 pub fn as_path(&self) -> &'a Path {
730 let mut comps = self.clone();
731 if comps.front == State::Body {
732 comps.trim_left();
733 }
734 if comps.back == State::Body {
735 comps.trim_right();
736 }
737 unsafe { Path::from_u8_slice(comps.path) }
738 }
739
740 fn has_root(&self) -> bool {
742 if self.has_physical_root {
743 return true;
744 }
745 if HAS_PREFIXES && let Some(p) = self.prefix {
746 if p.has_implicit_root() {
747 return true;
748 }
749 }
750 false
751 }
752
753 fn include_cur_dir(&self) -> bool {
755 if self.has_root() {
756 return false;
757 }
758 let slice = &self.path[self.prefix_remaining()..];
759 match slice {
760 [b'.'] => true,
761 [b'.', b, ..] => self.is_sep_byte(*b),
762 _ => false,
763 }
764 }
765
766 unsafe fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
769 match comp {
770 b"." if HAS_PREFIXES && self.prefix_verbatim() => Some(Component::CurDir),
771 b"." => None, b".." => Some(Component::ParentDir),
775 b"" => None,
776 _ => Some(Component::Normal(unsafe { OsStr::from_encoded_bytes_unchecked(comp) })),
777 }
778 }
779
780 fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
783 if true {
if !(self.front == State::Body) {
::core::panicking::panic("assertion failed: self.front == State::Body")
};
};debug_assert!(self.front == State::Body);
784 let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
785 None => (0, self.path),
786 Some(i) => (1, &self.path[..i]),
787 };
788 (comp.len() + extra, unsafe { self.parse_single_component(comp) })
790 }
791
792 fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
795 if true {
if !(self.back == State::Body) {
::core::panicking::panic("assertion failed: self.back == State::Body")
};
};debug_assert!(self.back == State::Body);
796 let start = self.len_before_body();
797 let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
798 None => (0, &self.path[start..]),
799 Some(i) => (1, &self.path[start + i + 1..]),
800 };
801 (comp.len() + extra, unsafe { self.parse_single_component(comp) })
803 }
804
805 fn trim_left(&mut self) {
807 while !self.path.is_empty() {
808 let (size, comp) = self.parse_next_component();
809 if comp.is_some() {
810 return;
811 } else {
812 self.path = &self.path[size..];
813 }
814 }
815 }
816
817 fn trim_right(&mut self) {
819 while self.path.len() > self.len_before_body() {
820 let (size, comp) = self.parse_next_component_back();
821 if comp.is_some() {
822 return;
823 } else {
824 self.path = &self.path[..self.path.len() - size];
825 }
826 }
827 }
828}
829
830#[stable(feature = "rust1", since = "1.0.0")]
831impl AsRef<Path> for Components<'_> {
832 #[inline]
833 fn as_ref(&self) -> &Path {
834 self.as_path()
835 }
836}
837
838#[stable(feature = "rust1", since = "1.0.0")]
839impl AsRef<OsStr> for Components<'_> {
840 #[inline]
841 fn as_ref(&self) -> &OsStr {
842 self.as_path().as_os_str()
843 }
844}
845
846#[stable(feature = "path_iter_debug", since = "1.13.0")]
847impl fmt::Debug for Iter<'_> {
848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849 struct DebugHelper<'a>(&'a Path);
850
851 impl fmt::Debug for DebugHelper<'_> {
852 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
853 f.debug_list().entries(self.0.iter()).finish()
854 }
855 }
856
857 f.debug_tuple("Iter").field(&DebugHelper(self.as_path())).finish()
858 }
859}
860
861impl<'a> Iter<'a> {
862 #[stable(feature = "rust1", since = "1.0.0")]
876 #[must_use]
877 #[inline]
878 pub fn as_path(&self) -> &'a Path {
879 self.inner.as_path()
880 }
881}
882
883#[stable(feature = "rust1", since = "1.0.0")]
884impl AsRef<Path> for Iter<'_> {
885 #[inline]
886 fn as_ref(&self) -> &Path {
887 self.as_path()
888 }
889}
890
891#[stable(feature = "rust1", since = "1.0.0")]
892impl AsRef<OsStr> for Iter<'_> {
893 #[inline]
894 fn as_ref(&self) -> &OsStr {
895 self.as_path().as_os_str()
896 }
897}
898
899#[stable(feature = "rust1", since = "1.0.0")]
900impl<'a> Iterator for Iter<'a> {
901 type Item = &'a OsStr;
902
903 #[inline]
904 fn next(&mut self) -> Option<&'a OsStr> {
905 self.inner.next().map(Component::as_os_str)
906 }
907}
908
909#[stable(feature = "rust1", since = "1.0.0")]
910impl<'a> DoubleEndedIterator for Iter<'a> {
911 #[inline]
912 fn next_back(&mut self) -> Option<&'a OsStr> {
913 self.inner.next_back().map(Component::as_os_str)
914 }
915}
916
917#[stable(feature = "fused", since = "1.26.0")]
918impl FusedIterator for Iter<'_> {}
919
920#[stable(feature = "rust1", since = "1.0.0")]
921impl<'a> Iterator for Components<'a> {
922 type Item = Component<'a>;
923
924 fn next(&mut self) -> Option<Component<'a>> {
925 while !self.finished() {
926 match self.front {
927 State::Body if !self.path.is_empty() => {
929 let (size, comp) = self.parse_next_component();
930 self.path = &self.path[size..];
931 if comp.is_some() {
932 return comp;
933 }
934 }
935 State::Body => {
936 self.front = State::Done;
937 }
938 State::StartDir => {
939 self.front = State::Body;
940 if self.has_physical_root {
941 if true {
if !!self.path.is_empty() {
::core::panicking::panic("assertion failed: !self.path.is_empty()")
};
};debug_assert!(!self.path.is_empty());
942 self.path = &self.path[1..];
943 return Some(Component::RootDir);
944 } else if HAS_PREFIXES && let Some(p) = self.prefix {
945 if p.has_implicit_root() && !p.is_verbatim() {
946 return Some(Component::RootDir);
947 }
948 } else if self.include_cur_dir() {
949 if true {
if !!self.path.is_empty() {
::core::panicking::panic("assertion failed: !self.path.is_empty()")
};
};debug_assert!(!self.path.is_empty());
950 self.path = &self.path[1..];
951 return Some(Component::CurDir);
952 }
953 }
954 _ if const { !HAS_PREFIXES } => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
955 State::Prefix if self.prefix_len() == 0 => {
956 self.front = State::StartDir;
957 }
958 State::Prefix => {
959 self.front = State::StartDir;
960 if true {
if !(self.prefix_len() <= self.path.len()) {
::core::panicking::panic("assertion failed: self.prefix_len() <= self.path.len()")
};
};debug_assert!(self.prefix_len() <= self.path.len());
961 let raw = &self.path[..self.prefix_len()];
962 self.path = &self.path[self.prefix_len()..];
963 return Some(Component::Prefix(PrefixComponent {
964 raw: unsafe { OsStr::from_encoded_bytes_unchecked(raw) },
965 parsed: self.prefix.unwrap(),
966 }));
967 }
968 State::Done => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
969 }
970 }
971 None
972 }
973}
974
975#[stable(feature = "rust1", since = "1.0.0")]
976impl<'a> DoubleEndedIterator for Components<'a> {
977 fn next_back(&mut self) -> Option<Component<'a>> {
978 while !self.finished() {
979 match self.back {
980 State::Body if self.path.len() > self.len_before_body() => {
981 let (size, comp) = self.parse_next_component_back();
982 self.path = &self.path[..self.path.len() - size];
983 if comp.is_some() {
984 return comp;
985 }
986 }
987 State::Body => {
988 self.back = State::StartDir;
989 }
990 State::StartDir => {
991 self.back = if HAS_PREFIXES { State::Prefix } else { State::Done };
992 if self.has_physical_root {
993 self.path = &self.path[..self.path.len() - 1];
994 return Some(Component::RootDir);
995 } else if HAS_PREFIXES && let Some(p) = self.prefix {
996 if p.has_implicit_root() && !p.is_verbatim() {
997 return Some(Component::RootDir);
998 }
999 } else if self.include_cur_dir() {
1000 self.path = &self.path[..self.path.len() - 1];
1001 return Some(Component::CurDir);
1002 }
1003 }
1004 _ if !HAS_PREFIXES => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1005 State::Prefix if self.prefix_len() > 0 => {
1006 self.back = State::Done;
1007 return Some(Component::Prefix(PrefixComponent {
1008 raw: unsafe { OsStr::from_encoded_bytes_unchecked(self.path) },
1009 parsed: self.prefix.unwrap(),
1010 }));
1011 }
1012 State::Prefix => {
1013 self.back = State::Done;
1014 return None;
1015 }
1016 State::Done => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1017 }
1018 }
1019 None
1020 }
1021}
1022
1023#[stable(feature = "fused", since = "1.26.0")]
1024impl FusedIterator for Components<'_> {}
1025
1026#[stable(feature = "rust1", since = "1.0.0")]
1027impl<'a> PartialEq for Components<'a> {
1028 #[inline]
1029 fn eq(&self, other: &Components<'a>) -> bool {
1030 let Components { path: _, front: _, back: _, has_physical_root: _, prefix: _ } = self;
1031
1032 if self.path.len() == other.path.len()
1036 && self.front == other.front
1037 && self.back == State::Body
1038 && other.back == State::Body
1039 && self.prefix_verbatim() == other.prefix_verbatim()
1040 {
1041 if self.path == other.path {
1044 return true;
1045 }
1046 }
1047
1048 Iterator::eq(self.clone().rev(), other.clone().rev())
1050 }
1051}
1052
1053#[stable(feature = "rust1", since = "1.0.0")]
1054impl Eq for Components<'_> {}
1055
1056#[stable(feature = "rust1", since = "1.0.0")]
1057impl<'a> PartialOrd for Components<'a> {
1058 #[inline]
1059 fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> {
1060 Some(compare_components(self.clone(), other.clone()))
1061 }
1062}
1063
1064#[stable(feature = "rust1", since = "1.0.0")]
1065impl Ord for Components<'_> {
1066 #[inline]
1067 fn cmp(&self, other: &Self) -> cmp::Ordering {
1068 compare_components(self.clone(), other.clone())
1069 }
1070}
1071
1072fn compare_components(mut left: Components<'_>, mut right: Components<'_>) -> cmp::Ordering {
1073 if left.prefix.is_none() && right.prefix.is_none() && left.front == right.front {
1083 let first_difference = match left.path.iter().zip(right.path).position(|(&a, &b)| a != b) {
1085 None if left.path.len() == right.path.len() => return cmp::Ordering::Equal,
1086 None => left.path.len().min(right.path.len()),
1087 Some(diff) => diff,
1088 };
1089
1090 if let Some(previous_sep) =
1091 left.path[..first_difference].iter().rposition(|&b| left.is_sep_byte(b))
1092 {
1093 let mismatched_component_start = previous_sep + 1;
1094 left.path = &left.path[mismatched_component_start..];
1095 left.front = State::Body;
1096 right.path = &right.path[mismatched_component_start..];
1097 right.front = State::Body;
1098 }
1099 }
1100
1101 Iterator::cmp(left, right)
1102}
1103
1104#[derive(#[automatically_derived]
#[stable(feature = "path_ancestors", since = "1.28.0")]
impl<'a> ::core::marker::Copy for Ancestors<'a> { }Copy, #[automatically_derived]
#[doc(hidden)]
#[stable(feature = "path_ancestors", since = "1.28.0")]
unsafe impl<'a> ::core::clone::TrivialClone for Ancestors<'a> { }
#[automatically_derived]
#[stable(feature = "path_ancestors", since = "1.28.0")]
impl<'a> ::core::clone::Clone for Ancestors<'a> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Option<&'a Path>>;
*self
}
}Clone, #[automatically_derived]
#[stable(feature = "path_ancestors", since = "1.28.0")]
impl<'a> ::core::fmt::Debug for Ancestors<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "Ancestors",
"next", &&self.next)
}
}Debug)]
1123#[must_use = "iterators are lazy and do nothing unless consumed"]
1124#[stable(feature = "path_ancestors", since = "1.28.0")]
1125pub struct Ancestors<'a> {
1126 next: Option<&'a Path>,
1127}
1128
1129#[stable(feature = "path_ancestors", since = "1.28.0")]
1130impl<'a> Iterator for Ancestors<'a> {
1131 type Item = &'a Path;
1132
1133 #[inline]
1134 fn next(&mut self) -> Option<Self::Item> {
1135 let next = self.next;
1136 self.next = next.and_then(Path::parent);
1137 next
1138 }
1139}
1140
1141#[stable(feature = "path_ancestors", since = "1.28.0")]
1142impl FusedIterator for Ancestors<'_> {}
1143
1144#[cfg_attr(not(test), rustc_diagnostic_item = "PathBuf")]
1214#[stable(feature = "rust1", since = "1.0.0")]
1215pub struct PathBuf {
1216 inner: OsString,
1217}
1218
1219impl PathBuf {
1220 #[stable(feature = "rust1", since = "1.0.0")]
1230 #[must_use]
1231 #[inline]
1232 #[rustc_const_stable(feature = "const_pathbuf_osstring_new", since = "1.91.0")]
1233 pub const fn new() -> PathBuf {
1234 PathBuf { inner: OsString::new() }
1235 }
1236
1237 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1256 #[must_use]
1257 #[inline]
1258 pub fn with_capacity(capacity: usize) -> PathBuf {
1259 PathBuf { inner: OsString::with_capacity(capacity) }
1260 }
1261
1262 #[cfg_attr(not(test), rustc_diagnostic_item = "pathbuf_as_path")]
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 #[must_use]
1275 #[inline]
1276 pub fn as_path(&self) -> &Path {
1277 self
1278 }
1279
1280 #[stable(feature = "os_string_pathbuf_leak", since = "1.89.0")]
1294 #[inline]
1295 pub fn leak<'a>(self) -> &'a mut Path {
1296 Path::from_inner_mut(self.inner.leak())
1297 }
1298
1299 #[stable(feature = "rust1", since = "1.0.0")]
1337 #[rustc_confusables("append", "put")]
1338 pub fn push<P: AsRef<Path>>(&mut self, path: P) {
1339 self._push(path.as_ref())
1340 }
1341
1342 fn _push(&mut self, path: &Path) {
1343 let buf = self.inner.as_encoded_bytes();
1345 let mut need_sep = buf.last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
1346
1347 let comps = self.components();
1349
1350 if comps.prefix_len() > 0
1351 && comps.prefix_len() == comps.path.len()
1352 && comps.prefix.unwrap().is_drive()
1353 {
1354 need_sep = false
1355 }
1356
1357 let need_clear = if falsecfg!(target_os = "cygwin") {
1358 path.prefix().is_some()
1361 } else {
1362 path.is_absolute() || path.prefix().is_some()
1364 };
1365
1366 if need_clear {
1368 self.inner.clear();
1369
1370 } else if comps.prefix_verbatim() && !path.inner.is_empty() {
1372 let mut buf: Vec<_> = comps.collect();
1373 for c in path.components() {
1374 match c {
1375 Component::RootDir => {
1376 buf.truncate(1);
1377 buf.push(c);
1378 }
1379 Component::CurDir => (),
1380 Component::ParentDir => {
1381 if let Some(Component::Normal(_)) = buf.last() {
1382 buf.pop();
1383 }
1384 }
1385 _ => buf.push(c),
1386 }
1387 }
1388
1389 let mut res = OsString::new();
1390 let mut need_sep = false;
1391
1392 for c in buf {
1393 if need_sep && c != Component::RootDir {
1394 res.push(MAIN_SEPARATOR_STR);
1395 }
1396 res.push(c.as_os_str());
1397
1398 need_sep = match c {
1399 Component::RootDir => false,
1400 Component::Prefix(prefix) => {
1401 !prefix.parsed.is_drive() && prefix.parsed.len() > 0
1402 }
1403 _ => true,
1404 }
1405 }
1406
1407 self.inner = res;
1408 return;
1409
1410 } else if path.has_root() {
1412 let prefix_len = self.components().prefix_remaining();
1413 self.inner.truncate(prefix_len);
1414
1415 } else if need_sep {
1417 self.inner.push(MAIN_SEPARATOR_STR);
1418 }
1419
1420 self.inner.push(path);
1421 }
1422
1423 #[stable(feature = "rust1", since = "1.0.0")]
1443 pub fn pop(&mut self) -> bool {
1444 match self.parent().map(|p| p.as_u8_slice().len()) {
1445 Some(len) => {
1446 self.inner.truncate(len);
1447 true
1448 }
1449 None => false,
1450 }
1451 }
1452
1453 #[unstable(feature = "path_trailing_sep", issue = "142503")]
1480 pub fn set_trailing_sep(&mut self, trailing_sep: bool) {
1481 if trailing_sep { self.push_trailing_sep() } else { self.pop_trailing_sep() }
1482 }
1483
1484 #[unstable(feature = "path_trailing_sep", issue = "142503")]
1508 pub fn push_trailing_sep(&mut self) {
1509 if !self.has_trailing_sep() {
1510 self.push("");
1511 }
1512 }
1513
1514 #[unstable(feature = "path_trailing_sep", issue = "142503")]
1542 pub fn pop_trailing_sep(&mut self) {
1543 self.inner.truncate(self.trim_trailing_sep().as_os_str().len());
1544 }
1545
1546 #[stable(feature = "rust1", since = "1.0.0")]
1586 pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) {
1587 self._set_file_name(file_name.as_ref())
1588 }
1589
1590 fn _set_file_name(&mut self, file_name: &OsStr) {
1591 if self.file_name().is_some() {
1592 let popped = self.pop();
1593 if true {
if !popped { ::core::panicking::panic("assertion failed: popped") };
};debug_assert!(popped);
1594 }
1595 self.push(file_name);
1596 }
1597
1598 #[stable(feature = "rust1", since = "1.0.0")]
1655 pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1656 self._set_extension(extension.as_ref())
1657 }
1658
1659 fn _set_extension(&mut self, extension: &OsStr) -> bool {
1660 validate_extension(extension);
1661
1662 let file_stem = match self.file_stem() {
1663 None => return false,
1664 Some(f) => f.as_encoded_bytes(),
1665 };
1666
1667 let end_file_stem = file_stem[file_stem.len()..].as_ptr().addr();
1669 let start = self.inner.as_encoded_bytes().as_ptr().addr();
1670 self.inner.truncate(end_file_stem.wrapping_sub(start));
1671
1672 let new = extension.as_encoded_bytes();
1674 if !new.is_empty() {
1675 self.inner.reserve_exact(new.len() + 1);
1676 self.inner.push(".");
1677 unsafe { self.inner.extend_from_slice_unchecked(new) };
1680 }
1681
1682 true
1683 }
1684
1685 #[stable(feature = "path_add_extension", since = "1.91.0")]
1729 pub fn add_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool {
1730 self._add_extension(extension.as_ref())
1731 }
1732
1733 fn _add_extension(&mut self, extension: &OsStr) -> bool {
1734 validate_extension(extension);
1735
1736 let file_name = match self.file_name() {
1737 None => return false,
1738 Some(f) => f.as_encoded_bytes(),
1739 };
1740
1741 let new = extension.as_encoded_bytes();
1742 if !new.is_empty() {
1743 let end_file_name = file_name[file_name.len()..].as_ptr().addr();
1746 let start = self.inner.as_encoded_bytes().as_ptr().addr();
1747 self.inner.truncate(end_file_name.wrapping_sub(start));
1748
1749 self.inner.reserve_exact(new.len() + 1);
1751 self.inner.push(".");
1752 unsafe { self.inner.extend_from_slice_unchecked(new) };
1755 }
1756
1757 true
1758 }
1759
1760 #[stable(feature = "path_as_mut_os_str", since = "1.70.0")]
1777 #[must_use]
1778 #[inline]
1779 pub fn as_mut_os_string(&mut self) -> &mut OsString {
1780 &mut self.inner
1781 }
1782
1783 #[stable(feature = "rust1", since = "1.0.0")]
1794 #[must_use = "`self` will be dropped if the result is not used"]
1795 #[inline]
1796 pub fn into_os_string(self) -> OsString {
1797 self.inner
1798 }
1799
1800 #[stable(feature = "pathbuf_into_string", since = "1.98.0")]
1814 pub fn into_string(self) -> Result<String, PathBuf> {
1815 self.into_os_string().into_string().map_err(PathBuf::from)
1816 }
1817
1818 #[stable(feature = "into_boxed_path", since = "1.20.0")]
1820 #[must_use = "`self` will be dropped if the result is not used"]
1821 #[inline]
1822 pub fn into_boxed_path(self) -> Box<Path> {
1823 let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut Path;
1824 unsafe { Box::from_raw(rw) }
1825 }
1826
1827 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1831 #[must_use]
1832 #[inline]
1833 pub fn capacity(&self) -> usize {
1834 self.inner.capacity()
1835 }
1836
1837 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1841 #[inline]
1842 pub fn clear(&mut self) {
1843 self.inner.clear()
1844 }
1845
1846 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1850 #[inline]
1851 pub fn reserve(&mut self, additional: usize) {
1852 self.inner.reserve(additional)
1853 }
1854
1855 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1859 #[inline]
1860 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1861 self.inner.try_reserve(additional)
1862 }
1863
1864 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1868 #[inline]
1869 pub fn reserve_exact(&mut self, additional: usize) {
1870 self.inner.reserve_exact(additional)
1871 }
1872
1873 #[stable(feature = "try_reserve_2", since = "1.63.0")]
1877 #[inline]
1878 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1879 self.inner.try_reserve_exact(additional)
1880 }
1881
1882 #[stable(feature = "path_buf_capacity", since = "1.44.0")]
1886 #[inline]
1887 pub fn shrink_to_fit(&mut self) {
1888 self.inner.shrink_to_fit()
1889 }
1890
1891 #[stable(feature = "shrink_to", since = "1.56.0")]
1895 #[inline]
1896 pub fn shrink_to(&mut self, min_capacity: usize) {
1897 self.inner.shrink_to(min_capacity)
1898 }
1899}
1900
1901#[stable(feature = "rust1", since = "1.0.0")]
1902impl Clone for PathBuf {
1903 #[inline]
1904 fn clone(&self) -> Self {
1905 PathBuf { inner: self.inner.clone() }
1906 }
1907
1908 #[inline]
1913 fn clone_from(&mut self, source: &Self) {
1914 self.inner.clone_from(&source.inner)
1915 }
1916}
1917
1918#[stable(feature = "box_from_path", since = "1.17.0")]
1919impl From<&Path> for Box<Path> {
1920 fn from(path: &Path) -> Box<Path> {
1924 Box::clone_from_ref(path)
1925 }
1926}
1927
1928#[stable(feature = "box_from_mut_slice", since = "1.84.0")]
1929impl From<&mut Path> for Box<Path> {
1930 fn from(path: &mut Path) -> Box<Path> {
1934 Self::from(&*path)
1935 }
1936}
1937
1938#[stable(feature = "box_from_cow", since = "1.45.0")]
1939impl From<Cow<'_, Path>> for Box<Path> {
1940 #[inline]
1944 fn from(cow: Cow<'_, Path>) -> Box<Path> {
1945 match cow {
1946 Cow::Borrowed(path) => Box::from(path),
1947 Cow::Owned(path) => Box::from(path),
1948 }
1949 }
1950}
1951
1952#[stable(feature = "path_buf_from_box", since = "1.18.0")]
1953impl From<Box<Path>> for PathBuf {
1954 #[inline]
1958 fn from(boxed: Box<Path>) -> PathBuf {
1959 boxed.into_path_buf()
1960 }
1961}
1962
1963#[stable(feature = "box_from_path_buf", since = "1.20.0")]
1964impl From<PathBuf> for Box<Path> {
1965 #[inline]
1970 fn from(p: PathBuf) -> Box<Path> {
1971 p.into_boxed_path()
1972 }
1973}
1974
1975#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
1976impl<A: Allocator + Clone> Clone for Box<Path, A> {
1977 #[inline]
1978 fn clone(&self) -> Self {
1979 Box::clone_from_ref_in(&**self, Self::allocator(self).clone())
1980 }
1981}
1982
1983#[stable(feature = "rust1", since = "1.0.0")]
1984impl<T: ?Sized + AsRef<OsStr>> From<&T> for PathBuf {
1985 #[inline]
1989 fn from(s: &T) -> PathBuf {
1990 PathBuf::from(s.as_ref().to_os_string())
1991 }
1992}
1993
1994#[stable(feature = "rust1", since = "1.0.0")]
1995impl From<OsString> for PathBuf {
1996 #[inline]
2000 fn from(s: OsString) -> PathBuf {
2001 PathBuf { inner: s }
2002 }
2003}
2004
2005#[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")]
2006impl From<PathBuf> for OsString {
2007 #[inline]
2011 fn from(path_buf: PathBuf) -> OsString {
2012 path_buf.inner
2013 }
2014}
2015
2016#[stable(feature = "rust1", since = "1.0.0")]
2017impl From<String> for PathBuf {
2018 #[inline]
2022 fn from(s: String) -> PathBuf {
2023 PathBuf::from(OsString::from(s))
2024 }
2025}
2026
2027#[stable(feature = "path_from_str", since = "1.32.0")]
2028impl FromStr for PathBuf {
2029 type Err = !;
2030
2031 #[inline]
2032 fn from_str(s: &str) -> Result<Self, !> {
2033 Ok(PathBuf::from(s))
2034 }
2035}
2036
2037#[stable(feature = "rust1", since = "1.0.0")]
2038impl<P: AsRef<Path>> FromIterator<P> for PathBuf {
2039 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf {
2053 let mut buf = PathBuf::new();
2054 buf.extend(iter);
2055 buf
2056 }
2057}
2058
2059#[stable(feature = "rust1", since = "1.0.0")]
2060impl<P: AsRef<Path>> Extend<P> for PathBuf {
2061 fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
2076 iter.into_iter().for_each(move |p| self.push(p.as_ref()));
2077 }
2078
2079 #[inline]
2080 fn extend_one(&mut self, p: P) {
2081 self.push(p.as_ref());
2082 }
2083}
2084
2085#[stable(feature = "rust1", since = "1.0.0")]
2086impl fmt::Debug for PathBuf {
2087 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2088 fmt::Debug::fmt(&**self, formatter)
2089 }
2090}
2091
2092#[stable(feature = "rust1", since = "1.0.0")]
2093impl ops::Deref for PathBuf {
2094 type Target = Path;
2095 #[inline]
2096 fn deref(&self) -> &Path {
2097 Path::new(&self.inner)
2098 }
2099}
2100
2101#[stable(feature = "path_buf_deref_mut", since = "1.68.0")]
2102impl ops::DerefMut for PathBuf {
2103 #[inline]
2104 fn deref_mut(&mut self) -> &mut Path {
2105 Path::from_inner_mut(&mut self.inner)
2106 }
2107}
2108
2109#[stable(feature = "rust1", since = "1.0.0")]
2110impl Borrow<Path> for PathBuf {
2111 #[inline]
2112 fn borrow(&self) -> &Path {
2113 self.deref()
2114 }
2115}
2116
2117#[stable(feature = "default_for_pathbuf", since = "1.17.0")]
2118impl Default for PathBuf {
2119 #[inline]
2120 fn default() -> Self {
2121 PathBuf::new()
2122 }
2123}
2124
2125#[stable(feature = "cow_from_path", since = "1.6.0")]
2126impl<'a> From<&'a Path> for Cow<'a, Path> {
2127 #[inline]
2132 fn from(s: &'a Path) -> Cow<'a, Path> {
2133 Cow::Borrowed(s)
2134 }
2135}
2136
2137#[stable(feature = "cow_from_path", since = "1.6.0")]
2138impl<'a> From<PathBuf> for Cow<'a, Path> {
2139 #[inline]
2144 fn from(s: PathBuf) -> Cow<'a, Path> {
2145 Cow::Owned(s)
2146 }
2147}
2148
2149#[stable(feature = "cow_from_pathbuf_ref", since = "1.28.0")]
2150impl<'a> From<&'a PathBuf> for Cow<'a, Path> {
2151 #[inline]
2156 fn from(p: &'a PathBuf) -> Cow<'a, Path> {
2157 Cow::Borrowed(p.as_path())
2158 }
2159}
2160
2161#[stable(feature = "pathbuf_from_cow_path", since = "1.28.0")]
2162impl<'a> From<Cow<'a, Path>> for PathBuf {
2163 #[inline]
2167 fn from(p: Cow<'a, Path>) -> Self {
2168 p.into_owned()
2169 }
2170}
2171
2172#[stable(feature = "shared_from_slice2", since = "1.24.0")]
2173impl From<PathBuf> for Arc<Path> {
2174 #[inline]
2177 fn from(s: PathBuf) -> Arc<Path> {
2178 let arc: Arc<OsStr> = Arc::from(s.into_os_string());
2179 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
2180 }
2181}
2182
2183#[stable(feature = "shared_from_slice2", since = "1.24.0")]
2184impl From<&Path> for Arc<Path> {
2185 #[inline]
2187 fn from(s: &Path) -> Arc<Path> {
2188 let arc: Arc<OsStr> = Arc::from(s.as_os_str());
2189 unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Path) }
2190 }
2191}
2192
2193#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
2194impl From<&mut Path> for Arc<Path> {
2195 #[inline]
2197 fn from(s: &mut Path) -> Arc<Path> {
2198 Arc::from(&*s)
2199 }
2200}
2201
2202#[stable(feature = "shared_from_slice2", since = "1.24.0")]
2203impl From<PathBuf> for Rc<Path> {
2204 #[inline]
2207 fn from(s: PathBuf) -> Rc<Path> {
2208 let rc: Rc<OsStr> = Rc::from(s.into_os_string());
2209 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
2210 }
2211}
2212
2213#[stable(feature = "shared_from_slice2", since = "1.24.0")]
2214impl From<&Path> for Rc<Path> {
2215 #[inline]
2217 fn from(s: &Path) -> Rc<Path> {
2218 let rc: Rc<OsStr> = Rc::from(s.as_os_str());
2219 unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Path) }
2220 }
2221}
2222
2223#[stable(feature = "shared_from_mut_slice", since = "1.84.0")]
2224impl From<&mut Path> for Rc<Path> {
2225 #[inline]
2227 fn from(s: &mut Path) -> Rc<Path> {
2228 Rc::from(&*s)
2229 }
2230}
2231
2232#[stable(feature = "rust1", since = "1.0.0")]
2233impl ToOwned for Path {
2234 type Owned = PathBuf;
2235 #[inline]
2236 fn to_owned(&self) -> PathBuf {
2237 self.to_path_buf()
2238 }
2239 #[inline]
2240 fn clone_into(&self, target: &mut PathBuf) {
2241 self.inner.clone_into(&mut target.inner);
2242 }
2243}
2244
2245#[stable(feature = "rust1", since = "1.0.0")]
2246impl PartialEq for PathBuf {
2247 #[inline]
2248 fn eq(&self, other: &PathBuf) -> bool {
2249 self.components() == other.components()
2250 }
2251}
2252
2253#[stable(feature = "eq_str_for_path", since = "1.91.0")]
2254impl cmp::PartialEq<str> for PathBuf {
2255 #[inline]
2256 fn eq(&self, other: &str) -> bool {
2257 self.as_path() == other
2258 }
2259}
2260
2261#[stable(feature = "eq_str_for_path", since = "1.91.0")]
2262impl cmp::PartialEq<PathBuf> for str {
2263 #[inline]
2264 fn eq(&self, other: &PathBuf) -> bool {
2265 self == other.as_path()
2266 }
2267}
2268
2269#[stable(feature = "eq_str_for_path", since = "1.91.0")]
2270impl cmp::PartialEq<String> for PathBuf {
2271 #[inline]
2272 fn eq(&self, other: &String) -> bool {
2273 self.as_path() == other.as_str()
2274 }
2275}
2276
2277#[stable(feature = "eq_str_for_path", since = "1.91.0")]
2278impl cmp::PartialEq<PathBuf> for String {
2279 #[inline]
2280 fn eq(&self, other: &PathBuf) -> bool {
2281 self.as_str() == other.as_path()
2282 }
2283}
2284
2285#[stable(feature = "rust1", since = "1.0.0")]
2286impl Hash for PathBuf {
2287 fn hash<H: Hasher>(&self, h: &mut H) {
2288 self.as_path().hash(h)
2289 }
2290}
2291
2292#[stable(feature = "rust1", since = "1.0.0")]
2293impl Eq for PathBuf {}
2294
2295#[stable(feature = "rust1", since = "1.0.0")]
2296impl PartialOrd for PathBuf {
2297 #[inline]
2298 fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
2299 Some(compare_components(self.components(), other.components()))
2300 }
2301}
2302
2303#[stable(feature = "rust1", since = "1.0.0")]
2304impl Ord for PathBuf {
2305 #[inline]
2306 fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
2307 compare_components(self.components(), other.components())
2308 }
2309}
2310
2311#[stable(feature = "rust1", since = "1.0.0")]
2312impl AsRef<OsStr> for PathBuf {
2313 #[inline]
2314 fn as_ref(&self) -> &OsStr {
2315 &self.inner[..]
2316 }
2317}
2318
2319#[cfg_attr(not(test), rustc_diagnostic_item = "Path")]
2352#[stable(feature = "rust1", since = "1.0.0")]
2353#[repr(transparent)]
2357pub struct Path {
2358 inner: OsStr,
2359}
2360
2361#[derive(#[automatically_derived]
#[stable(since = "1.7.0", feature = "strip_prefix")]
impl ::core::fmt::Debug for StripPrefixError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"StripPrefixError", &&self.0)
}
}Debug, #[automatically_derived]
#[stable(since = "1.7.0", feature = "strip_prefix")]
impl ::core::clone::Clone for StripPrefixError {
#[inline]
fn clone(&self) -> Self {
StripPrefixError(::core::clone::Clone::clone(&self.0))
}
}Clone, #[automatically_derived]
#[stable(since = "1.7.0", feature = "strip_prefix")]
impl ::core::marker::StructuralPartialEq for StripPrefixError { }
#[automatically_derived]
#[stable(since = "1.7.0", feature = "strip_prefix")]
impl ::core::cmp::PartialEq for StripPrefixError {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
#[stable(since = "1.7.0", feature = "strip_prefix")]
impl ::core::cmp::Eq for StripPrefixError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<()>;
}
}Eq)]
2368#[stable(since = "1.7.0", feature = "strip_prefix")]
2369pub struct StripPrefixError(());
2370
2371#[unstable(feature = "normalize_lexically", issue = "134694")]
2374#[derive(#[automatically_derived]
#[unstable(feature = "normalize_lexically", issue = "134694")]
impl ::core::fmt::Debug for NormalizeError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "NormalizeError")
}
}Debug, #[automatically_derived]
#[unstable(feature = "normalize_lexically", issue = "134694")]
impl ::core::marker::StructuralPartialEq for NormalizeError { }
#[automatically_derived]
#[unstable(feature = "normalize_lexically", issue = "134694")]
impl ::core::cmp::PartialEq for NormalizeError {
#[inline]
fn eq(&self, other: &Self) -> bool { true }
}PartialEq)]
2375#[non_exhaustive]
2376pub struct NormalizeError;
2377
2378impl Path {
2379 pub(crate) unsafe fn from_u8_slice(s: &[u8]) -> &Path {
2382 unsafe { Path::new(OsStr::from_encoded_bytes_unchecked(s)) }
2383 }
2384 pub(crate) fn as_u8_slice(&self) -> &[u8] {
2386 self.inner.as_encoded_bytes()
2387 }
2388
2389 #[stable(feature = "rust1", since = "1.0.0")]
2412 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2413 pub const fn new<S: [const] AsRef<OsStr> + ?Sized>(s: &S) -> &Path {
2414 unsafe { &*(s.as_ref() as *const OsStr as *const Path) }
2415 }
2416
2417 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2418 const fn from_inner_mut(inner: &mut OsStr) -> &mut Path {
2419 unsafe { &mut *(inner as *mut OsStr as *mut Path) }
2422 }
2423
2424 #[stable(feature = "rust1", since = "1.0.0")]
2435 #[must_use]
2436 #[inline]
2437 pub fn as_os_str(&self) -> &OsStr {
2438 &self.inner
2439 }
2440
2441 #[stable(feature = "path_as_mut_os_str", since = "1.70.0")]
2456 #[must_use]
2457 #[inline]
2458 pub fn as_mut_os_str(&mut self) -> &mut OsStr {
2459 &mut self.inner
2460 }
2461
2462 #[stable(feature = "rust1", since = "1.0.0")]
2479 #[must_use = "this returns the result of the operation, \
2480 without modifying the original"]
2481 #[inline]
2482 pub fn to_str(&self) -> Option<&str> {
2483 self.inner.to_str()
2484 }
2485
2486 #[stable(feature = "rust1", since = "1.0.0")]
2507 #[must_use = "this returns the result of the operation, \
2508 without modifying the original"]
2509 #[inline]
2510 pub fn to_string_lossy(&self) -> Cow<'_, str> {
2511 self.inner.to_string_lossy()
2512 }
2513
2514 #[rustc_conversion_suggestion]
2525 #[must_use = "this returns the result of the operation, \
2526 without modifying the original"]
2527 #[stable(feature = "rust1", since = "1.0.0")]
2528 #[cfg_attr(not(test), rustc_diagnostic_item = "path_to_pathbuf")]
2529 pub fn to_path_buf(&self) -> PathBuf {
2530 PathBuf::from(self.inner.to_os_string())
2531 }
2532
2533 #[stable(feature = "rust1", since = "1.0.0")]
2552 #[must_use]
2553 #[allow(deprecated)]
2554 pub fn is_absolute(&self) -> bool {
2555 sys::path::is_absolute(self)
2556 }
2557
2558 #[stable(feature = "rust1", since = "1.0.0")]
2572 #[must_use]
2573 #[inline]
2574 pub fn is_relative(&self) -> bool {
2575 !self.is_absolute()
2576 }
2577
2578 pub(crate) fn prefix(&self) -> Option<Prefix<'_>> {
2579 self.components().prefix
2580 }
2581
2582 #[stable(feature = "rust1", since = "1.0.0")]
2599 #[must_use]
2600 #[inline]
2601 pub fn has_root(&self) -> bool {
2602 self.components().has_root()
2603 }
2604
2605 #[stable(feature = "rust1", since = "1.0.0")]
2634 #[doc(alias = "dirname")]
2635 #[must_use]
2636 pub fn parent(&self) -> Option<&Path> {
2637 let mut comps = self.components();
2638 let comp = comps.next_back();
2639 comp.and_then(|p| match p {
2640 Component::Normal(_) | Component::CurDir | Component::ParentDir => {
2641 Some(comps.as_path())
2642 }
2643 _ => None,
2644 })
2645 }
2646
2647 #[stable(feature = "path_ancestors", since = "1.28.0")]
2675 #[inline]
2676 pub fn ancestors(&self) -> Ancestors<'_> {
2677 Ancestors { next: Some(self) }
2678 }
2679
2680 #[stable(feature = "rust1", since = "1.0.0")]
2701 #[doc(alias = "basename")]
2702 #[must_use]
2703 pub fn file_name(&self) -> Option<&OsStr> {
2704 self.components().next_back().and_then(|p| match p {
2705 Component::Normal(p) => Some(p),
2706 _ => None,
2707 })
2708 }
2709
2710 #[stable(since = "1.7.0", feature = "path_strip_prefix")]
2740 pub fn strip_prefix<P>(&self, base: P) -> Result<&Path, StripPrefixError>
2741 where
2742 P: AsRef<Path>,
2743 {
2744 self._strip_prefix(base.as_ref())
2745 }
2746
2747 #[must_use = "this returns the remaining path as a new path, without modifying the original"]
2773 #[stable(feature = "trim_prefix_suffix", since = "1.100.0")]
2774 pub fn trim_prefix<P>(&self, base: P) -> &Path
2775 where
2776 P: AsRef<Path>,
2777 {
2778 self._strip_prefix(base.as_ref()).unwrap_or(self)
2779 }
2780
2781 fn _strip_prefix(&self, base: &Path) -> Result<&Path, StripPrefixError> {
2782 iter_after(self.components(), base.components())
2783 .map(|c| c.as_path())
2784 .ok_or(StripPrefixError(()))
2785 }
2786
2787 #[stable(feature = "rust1", since = "1.0.0")]
2810 #[must_use]
2811 pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool {
2812 self._starts_with(base.as_ref())
2813 }
2814
2815 fn _starts_with(&self, base: &Path) -> bool {
2816 iter_after(self.components(), base.components()).is_some()
2817 }
2818
2819 #[stable(feature = "rust1", since = "1.0.0")]
2838 #[must_use]
2839 pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool {
2840 self._ends_with(child.as_ref())
2841 }
2842
2843 fn _ends_with(&self, child: &Path) -> bool {
2844 iter_after(self.components().rev(), child.components().rev()).is_some()
2845 }
2846
2847 #[stable(feature = "path_is_empty", since = "1.98.0")]
2868 pub fn is_empty(&self) -> bool {
2869 self.as_os_str().is_empty()
2870 }
2871
2872 #[stable(feature = "rust1", since = "1.0.0")]
2899 #[must_use]
2900 pub fn file_stem(&self) -> Option<&OsStr> {
2901 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after))
2902 }
2903
2904 #[stable(feature = "path_file_prefix", since = "1.91.0")]
2934 #[must_use]
2935 pub fn file_prefix(&self) -> Option<&OsStr> {
2936 self.file_name().map(split_file_at_dot).map(|(before, _after)| before)
2937 }
2938
2939 #[stable(feature = "rust1", since = "1.0.0")]
2959 #[must_use]
2960 pub fn extension(&self) -> Option<&OsStr> {
2961 self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.and(after))
2962 }
2963
2964 #[unstable(feature = "path_trailing_sep", issue = "142503")]
2983 #[must_use]
2984 #[inline]
2985 pub fn has_trailing_sep(&self) -> bool {
2986 let comps = self.components();
2987 self.as_os_str().as_encoded_bytes().last().copied().is_some_and(|b| comps.is_sep_byte(b))
2988 }
2989
2990 #[unstable(feature = "path_trailing_sep", issue = "142503")]
3008 #[must_use]
3009 #[inline]
3010 pub fn with_trailing_sep(&self) -> Cow<'_, Path> {
3011 if self.has_trailing_sep() { Cow::Borrowed(self) } else { Cow::Owned(self.join("")) }
3012 }
3013
3014 #[unstable(feature = "path_trailing_sep", issue = "142503")]
3035 #[must_use]
3036 #[inline]
3037 pub fn trim_trailing_sep(&self) -> &Path {
3038 let comps = self.components();
3039 if self.has_trailing_sep() && (!self.has_root() || self.parent().is_some()) {
3040 let mut bytes = self.inner.as_encoded_bytes();
3041 while let Some((last, init)) = bytes.split_last()
3042 && comps.is_sep_byte(*last)
3043 {
3044 bytes = init;
3045 }
3046
3047 Path::new(unsafe { OsStr::from_encoded_bytes_unchecked(bytes) })
3049 } else {
3050 self
3051 }
3052 }
3053
3054 #[stable(feature = "rust1", since = "1.0.0")]
3078 #[must_use]
3079 pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf {
3080 self._join(path.as_ref())
3081 }
3082
3083 fn _join(&self, path: &Path) -> PathBuf {
3084 let mut buf = self.to_path_buf();
3085 buf.push(path);
3086 buf
3087 }
3088
3089 #[stable(feature = "rust1", since = "1.0.0")]
3106 #[must_use]
3107 pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf {
3108 self._with_file_name(file_name.as_ref())
3109 }
3110
3111 fn _with_file_name(&self, file_name: &OsStr) -> PathBuf {
3112 let mut buf = self.to_path_buf();
3113 buf.set_file_name(file_name);
3114 buf
3115 }
3116
3117 #[stable(feature = "rust1", since = "1.0.0")]
3150 pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
3151 self._with_extension(extension.as_ref())
3152 }
3153
3154 fn _with_extension(&self, extension: &OsStr) -> PathBuf {
3155 let self_len = self.as_os_str().len();
3156 let self_bytes = self.as_os_str().as_encoded_bytes();
3157
3158 let (new_capacity, slice_to_copy) = match self.extension() {
3159 None => {
3160 let capacity = self_len + extension.len() + 1;
3162 let whole_path = self_bytes;
3163 (capacity, whole_path)
3164 }
3165 Some(previous_extension) => {
3166 let capacity = self_len + extension.len() - previous_extension.len();
3167 let path_till_dot = &self_bytes[..self_len - previous_extension.len()];
3168 (capacity, path_till_dot)
3169 }
3170 };
3171
3172 let mut new_path = PathBuf::with_capacity(new_capacity);
3173 unsafe { new_path.inner.extend_from_slice_unchecked(slice_to_copy) };
3175 new_path.set_extension(extension);
3176 new_path
3177 }
3178
3179 #[stable(feature = "path_add_extension", since = "1.91.0")]
3206 pub fn with_added_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf {
3207 let mut new_path = self.to_path_buf();
3208 new_path.add_extension(extension);
3209 new_path
3210 }
3211
3212 #[stable(feature = "rust1", since = "1.0.0")]
3246 pub fn components(&self) -> Components<'_> {
3247 let prefix = parse_prefix(self.as_os_str());
3248 Components {
3249 path: self.as_u8_slice(),
3250 prefix,
3251 has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
3252 front: const { if HAS_PREFIXES { State::Prefix } else { State::StartDir } },
3255 back: State::Body,
3256 }
3257 }
3258
3259 #[stable(feature = "rust1", since = "1.0.0")]
3280 #[inline]
3281 pub fn iter(&self) -> Iter<'_> {
3282 Iter { inner: self.components() }
3283 }
3284
3285 #[stable(feature = "rust1", since = "1.0.0")]
3303 #[must_use = "this does not display the path, \
3304 it returns an object that can be displayed"]
3305 #[inline]
3306 pub fn display(&self) -> Display<'_> {
3307 Display { inner: self.inner.display() }
3308 }
3309
3310 #[inline]
3316 #[unstable(feature = "str_as_str", issue = "130366")]
3317 pub const fn as_path(&self) -> &Path {
3318 self
3319 }
3320
3321 #[stable(feature = "path_ext", since = "1.5.0")]
3338 #[inline]
3339 pub fn metadata(&self) -> io::Result<fs::Metadata> {
3340 fs::metadata(self)
3341 }
3342
3343 #[stable(feature = "path_ext", since = "1.5.0")]
3357 #[inline]
3358 pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
3359 fs::symlink_metadata(self)
3360 }
3361
3362 #[stable(feature = "path_ext", since = "1.5.0")]
3384 #[inline]
3385 pub fn canonicalize(&self) -> io::Result<PathBuf> {
3386 fs::canonicalize(self)
3387 }
3388
3389 #[unstable(feature = "path_absolute_method", issue = "153328")]
3412 #[inline]
3413 pub fn absolute(&self) -> io::Result<PathBuf> {
3414 absolute(self)
3415 }
3416
3417 #[unstable(feature = "normalize_lexically", issue = "134694")]
3434 pub fn normalize_lexically(&self) -> Result<PathBuf, NormalizeError> {
3435 let mut lexical = PathBuf::new();
3436 let mut iter = self.components().peekable();
3437
3438 let root = match iter.peek() {
3442 Some(Component::ParentDir) => return Err(NormalizeError),
3443 Some(p @ Component::RootDir) | Some(p @ Component::CurDir) => {
3444 lexical.push(p);
3445 iter.next();
3446 lexical.as_os_str().len()
3447 }
3448 Some(Component::Prefix(prefix)) => {
3449 lexical.push(prefix.as_os_str());
3450 iter.next();
3451 if let Some(p @ Component::RootDir) = iter.peek() {
3452 lexical.push(p);
3453 iter.next();
3454 }
3455 lexical.as_os_str().len()
3456 }
3457 None => return Ok(PathBuf::new()),
3458 Some(Component::Normal(_)) => 0,
3459 };
3460
3461 for component in iter {
3462 match component {
3463 Component::RootDir => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
3464 Component::Prefix(_) => return Err(NormalizeError),
3465 Component::CurDir => continue,
3466 Component::ParentDir => {
3467 if lexical.as_os_str().len() == root {
3469 return Err(NormalizeError);
3470 } else {
3471 lexical.pop();
3472 }
3473 }
3474 Component::Normal(path) => lexical.push(path),
3475 }
3476 }
3477 Ok(lexical)
3478 }
3479
3480 #[stable(feature = "path_ext", since = "1.5.0")]
3493 #[inline]
3494 pub fn read_link(&self) -> io::Result<PathBuf> {
3495 fs::read_link(self)
3496 }
3497
3498 #[stable(feature = "path_ext", since = "1.5.0")]
3518 #[inline]
3519 pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
3520 fs::read_dir(self)
3521 }
3522
3523 #[stable(feature = "path_ext", since = "1.5.0")]
3549 #[must_use]
3550 #[inline]
3551 pub fn exists(&self) -> bool {
3552 fs::metadata(self).is_ok()
3553 }
3554
3555 #[stable(feature = "path_try_exists", since = "1.63.0")]
3583 #[inline]
3584 pub fn try_exists(&self) -> io::Result<bool> {
3585 fs::exists(self)
3586 }
3587
3588 #[stable(feature = "path_ext", since = "1.5.0")]
3616 #[must_use]
3617 pub fn is_file(&self) -> bool {
3618 fs::metadata(self).map(|m| m.is_file()).unwrap_or(false)
3619 }
3620
3621 #[stable(feature = "path_ext", since = "1.5.0")]
3643 #[must_use]
3644 pub fn is_dir(&self) -> bool {
3645 fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false)
3646 }
3647
3648 #[must_use]
3676 #[stable(feature = "is_symlink", since = "1.58.0")]
3677 pub fn is_symlink(&self) -> bool {
3678 fs::symlink_metadata(self).map(|m| m.is_symlink()).unwrap_or(false)
3679 }
3680
3681 #[stable(feature = "into_boxed_path", since = "1.20.0")]
3684 #[must_use = "`self` will be dropped if the result is not used"]
3685 pub fn into_path_buf(self: Box<Self>) -> PathBuf {
3686 let rw = Box::into_raw(self) as *mut OsStr;
3687 let inner = unsafe { Box::from_raw(rw) };
3688 PathBuf { inner: OsString::from(inner) }
3689 }
3690}
3691
3692#[unstable(feature = "clone_to_uninit", issue = "126799")]
3693unsafe impl CloneToUninit for Path {
3694 #[inline]
3695 #[cfg_attr(debug_assertions, track_caller)]
3696 unsafe fn clone_to_uninit(&self, dst: *mut u8) {
3697 unsafe { self.inner.clone_to_uninit(dst) }
3699 }
3700}
3701
3702#[stable(feature = "rust1", since = "1.0.0")]
3703#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3704const impl AsRef<OsStr> for Path {
3705 #[inline]
3706 fn as_ref(&self) -> &OsStr {
3707 &self.inner
3708 }
3709}
3710
3711#[stable(feature = "rust1", since = "1.0.0")]
3712impl fmt::Debug for Path {
3713 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3714 fmt::Debug::fmt(&self.inner, formatter)
3715 }
3716}
3717
3718#[stable(feature = "rust1", since = "1.0.0")]
3739pub struct Display<'a> {
3740 inner: os_str::Display<'a>,
3741}
3742
3743#[stable(feature = "rust1", since = "1.0.0")]
3744impl fmt::Debug for Display<'_> {
3745 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3746 fmt::Debug::fmt(&self.inner, f)
3747 }
3748}
3749
3750#[stable(feature = "rust1", since = "1.0.0")]
3751impl fmt::Display for Display<'_> {
3752 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3753 fmt::Display::fmt(&self.inner, f)
3754 }
3755}
3756
3757#[stable(feature = "rust1", since = "1.0.0")]
3758impl PartialEq for Path {
3759 #[inline]
3760 fn eq(&self, other: &Path) -> bool {
3761 self.components() == other.components()
3762 }
3763}
3764
3765#[stable(feature = "eq_str_for_path", since = "1.91.0")]
3766impl cmp::PartialEq<str> for Path {
3767 #[inline]
3768 fn eq(&self, other: &str) -> bool {
3769 let other: &OsStr = other.as_ref();
3770 self == other
3771 }
3772}
3773
3774#[stable(feature = "eq_str_for_path", since = "1.91.0")]
3775impl cmp::PartialEq<Path> for str {
3776 #[inline]
3777 fn eq(&self, other: &Path) -> bool {
3778 other == self
3779 }
3780}
3781
3782#[stable(feature = "eq_str_for_path", since = "1.91.0")]
3783impl cmp::PartialEq<String> for Path {
3784 #[inline]
3785 fn eq(&self, other: &String) -> bool {
3786 self == other.as_str()
3787 }
3788}
3789
3790#[stable(feature = "eq_str_for_path", since = "1.91.0")]
3791impl cmp::PartialEq<Path> for String {
3792 #[inline]
3793 fn eq(&self, other: &Path) -> bool {
3794 self.as_str() == other
3795 }
3796}
3797
3798#[stable(feature = "rust1", since = "1.0.0")]
3799impl Hash for Path {
3800 fn hash<H: Hasher>(&self, h: &mut H) {
3801 let bytes = self.as_u8_slice();
3802 let (prefix_len, verbatim) = match parse_prefix(&self.inner) {
3803 Some(prefix) => {
3804 prefix.hash(h);
3805 (prefix.len(), prefix.is_verbatim())
3806 }
3807 None => (0, false),
3808 };
3809 let bytes = &bytes[prefix_len..];
3810
3811 let mut component_start = 0;
3812 let mut chunk_bits: usize = 0;
3816
3817 for i in 0..bytes.len() {
3818 let is_sep = if verbatim { is_verbatim_sep(bytes[i]) } else { is_sep_byte(bytes[i]) };
3819 if is_sep {
3820 if i > component_start {
3821 let to_hash = &bytes[component_start..i];
3822 chunk_bits = chunk_bits.wrapping_add(to_hash.len());
3823 chunk_bits = chunk_bits.rotate_right(2);
3824 h.write(to_hash);
3825 }
3826
3827 component_start = i + 1;
3830
3831 let tail = &bytes[component_start..];
3832
3833 if !verbatim {
3834 component_start += match tail {
3835 [b'.'] => 1,
3836 [b'.', sep, ..] if is_sep_byte(*sep) => 1,
3837 _ => 0,
3838 };
3839 }
3840 }
3841 }
3842
3843 if component_start < bytes.len() {
3844 let to_hash = &bytes[component_start..];
3845 chunk_bits = chunk_bits.wrapping_add(to_hash.len());
3846 chunk_bits = chunk_bits.rotate_right(2);
3847 h.write(to_hash);
3848 }
3849
3850 h.write_usize(chunk_bits);
3851 }
3852}
3853
3854#[stable(feature = "rust1", since = "1.0.0")]
3855impl Eq for Path {}
3856
3857#[stable(feature = "rust1", since = "1.0.0")]
3858impl PartialOrd for Path {
3859 #[inline]
3860 fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
3861 Some(compare_components(self.components(), other.components()))
3862 }
3863}
3864
3865#[stable(feature = "rust1", since = "1.0.0")]
3866impl Ord for Path {
3867 #[inline]
3868 fn cmp(&self, other: &Path) -> cmp::Ordering {
3869 compare_components(self.components(), other.components())
3870 }
3871}
3872
3873#[stable(feature = "rust1", since = "1.0.0")]
3874#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3875const impl AsRef<Path> for Path {
3876 #[inline]
3877 fn as_ref(&self) -> &Path {
3878 self
3879 }
3880}
3881
3882#[stable(feature = "rust1", since = "1.0.0")]
3883#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3884const impl AsRef<Path> for OsStr {
3885 #[inline]
3886 fn as_ref(&self) -> &Path {
3887 Path::new(self)
3888 }
3889}
3890
3891#[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")]
3892impl AsRef<Path> for Cow<'_, OsStr> {
3893 #[inline]
3894 fn as_ref(&self) -> &Path {
3895 Path::new(self)
3896 }
3897}
3898
3899#[stable(feature = "rust1", since = "1.0.0")]
3900impl AsRef<Path> for OsString {
3901 #[inline]
3902 fn as_ref(&self) -> &Path {
3903 Path::new(self)
3904 }
3905}
3906
3907#[stable(feature = "rust1", since = "1.0.0")]
3908impl AsRef<Path> for str {
3909 #[inline]
3910 fn as_ref(&self) -> &Path {
3911 Path::new(self)
3912 }
3913}
3914
3915#[stable(feature = "rust1", since = "1.0.0")]
3916impl AsRef<Path> for String {
3917 #[inline]
3918 fn as_ref(&self) -> &Path {
3919 Path::new(self)
3920 }
3921}
3922
3923#[stable(feature = "rust1", since = "1.0.0")]
3924impl AsRef<Path> for PathBuf {
3925 #[inline]
3926 fn as_ref(&self) -> &Path {
3927 self
3928 }
3929}
3930
3931#[stable(feature = "path_into_iter", since = "1.6.0")]
3932impl<'a> IntoIterator for &'a PathBuf {
3933 type Item = &'a OsStr;
3934 type IntoIter = Iter<'a>;
3935 #[inline]
3936 fn into_iter(self) -> Iter<'a> {
3937 self.iter()
3938 }
3939}
3940
3941#[stable(feature = "path_into_iter", since = "1.6.0")]
3942impl<'a> IntoIterator for &'a Path {
3943 type Item = &'a OsStr;
3944 type IntoIter = Iter<'a>;
3945 #[inline]
3946 fn into_iter(self) -> Iter<'a> {
3947 self.iter()
3948 }
3949}
3950
3951macro_rules! impl_cmp {
3952 ($lhs:ty, $rhs: ty) => {
3953 #[stable(feature = "partialeq_path", since = "1.6.0")]
3954 impl PartialEq<$rhs> for $lhs {
3955 #[inline]
3956 fn eq(&self, other: &$rhs) -> bool {
3957 <Path as PartialEq>::eq(self, other)
3958 }
3959 }
3960
3961 #[stable(feature = "partialeq_path", since = "1.6.0")]
3962 impl PartialEq<$lhs> for $rhs {
3963 #[inline]
3964 fn eq(&self, other: &$lhs) -> bool {
3965 <Path as PartialEq>::eq(self, other)
3966 }
3967 }
3968
3969 #[stable(feature = "cmp_path", since = "1.8.0")]
3970 impl PartialOrd<$rhs> for $lhs {
3971 #[inline]
3972 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
3973 <Path as PartialOrd>::partial_cmp(self, other)
3974 }
3975 }
3976
3977 #[stable(feature = "cmp_path", since = "1.8.0")]
3978 impl PartialOrd<$lhs> for $rhs {
3979 #[inline]
3980 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
3981 <Path as PartialOrd>::partial_cmp(self, other)
3982 }
3983 }
3984 };
3985}
3986
3987#[stable(feature = "partialeq_path", since = "1.6.0")]
impl PartialEq<Path> for PathBuf {
#[inline]
fn eq(&self, other: &Path) -> bool {
<Path as PartialEq>::eq(self, other)
}
}
#[stable(feature = "partialeq_path", since = "1.6.0")]
impl PartialEq<PathBuf> for Path {
#[inline]
fn eq(&self, other: &PathBuf) -> bool {
<Path as PartialEq>::eq(self, other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Path> for PathBuf {
#[inline]
fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<PathBuf> for Path {
#[inline]
fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other)
}
}impl_cmp!(PathBuf, Path);
3988#[stable(feature = "partialeq_path", since = "1.6.0")]
impl PartialEq<&Path> for PathBuf {
#[inline]
fn eq(&self, other: &&Path) -> bool {
<Path as PartialEq>::eq(self, other)
}
}
#[stable(feature = "partialeq_path", since = "1.6.0")]
impl PartialEq<PathBuf> for &Path {
#[inline]
fn eq(&self, other: &PathBuf) -> bool {
<Path as PartialEq>::eq(self, other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<&Path> for PathBuf {
#[inline]
fn partial_cmp(&self, other: &&Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<PathBuf> for &Path {
#[inline]
fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other)
}
}impl_cmp!(PathBuf, &Path);
3989#[stable(feature = "partialeq_path", since = "1.6.0")]
impl PartialEq<Path> for Cow<'_, Path> {
#[inline]
fn eq(&self, other: &Path) -> bool {
<Path as PartialEq>::eq(self, other)
}
}
#[stable(feature = "partialeq_path", since = "1.6.0")]
impl PartialEq<Cow<'_, Path>> for Path {
#[inline]
fn eq(&self, other: &Cow<'_, Path>) -> bool {
<Path as PartialEq>::eq(self, other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Path> for Cow<'_, Path> {
#[inline]
fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Cow<'_, Path>> for Path {
#[inline]
fn partial_cmp(&self, other: &Cow<'_, Path>) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other)
}
}impl_cmp!(Cow<'_, Path>, Path);
3990#[stable(feature = "partialeq_path", since = "1.6.0")]
impl PartialEq<&Path> for Cow<'_, Path> {
#[inline]
fn eq(&self, other: &&Path) -> bool {
<Path as PartialEq>::eq(self, other)
}
}
#[stable(feature = "partialeq_path", since = "1.6.0")]
impl PartialEq<Cow<'_, Path>> for &Path {
#[inline]
fn eq(&self, other: &Cow<'_, Path>) -> bool {
<Path as PartialEq>::eq(self, other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<&Path> for Cow<'_, Path> {
#[inline]
fn partial_cmp(&self, other: &&Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Cow<'_, Path>> for &Path {
#[inline]
fn partial_cmp(&self, other: &Cow<'_, Path>) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other)
}
}impl_cmp!(Cow<'_, Path>, &Path);
3991#[stable(feature = "partialeq_path", since = "1.6.0")]
impl PartialEq<PathBuf> for Cow<'_, Path> {
#[inline]
fn eq(&self, other: &PathBuf) -> bool {
<Path as PartialEq>::eq(self, other)
}
}
#[stable(feature = "partialeq_path", since = "1.6.0")]
impl PartialEq<Cow<'_, Path>> for PathBuf {
#[inline]
fn eq(&self, other: &Cow<'_, Path>) -> bool {
<Path as PartialEq>::eq(self, other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<PathBuf> for Cow<'_, Path> {
#[inline]
fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Cow<'_, Path>> for PathBuf {
#[inline]
fn partial_cmp(&self, other: &Cow<'_, Path>) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other)
}
}impl_cmp!(Cow<'_, Path>, PathBuf);
3992
3993macro_rules! impl_cmp_os_str {
3994 ($lhs:ty, $rhs: ty) => {
3995 #[stable(feature = "cmp_path", since = "1.8.0")]
3996 impl PartialEq<$rhs> for $lhs {
3997 #[inline]
3998 fn eq(&self, other: &$rhs) -> bool {
3999 <Path as PartialEq>::eq(self, other.as_ref())
4000 }
4001 }
4002
4003 #[stable(feature = "cmp_path", since = "1.8.0")]
4004 impl PartialEq<$lhs> for $rhs {
4005 #[inline]
4006 fn eq(&self, other: &$lhs) -> bool {
4007 <Path as PartialEq>::eq(self.as_ref(), other)
4008 }
4009 }
4010
4011 #[stable(feature = "cmp_path", since = "1.8.0")]
4012 impl PartialOrd<$rhs> for $lhs {
4013 #[inline]
4014 fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> {
4015 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
4016 }
4017 }
4018
4019 #[stable(feature = "cmp_path", since = "1.8.0")]
4020 impl PartialOrd<$lhs> for $rhs {
4021 #[inline]
4022 fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> {
4023 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
4024 }
4025 }
4026 };
4027}
4028
4029#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<OsStr> for PathBuf {
#[inline]
fn eq(&self, other: &OsStr) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<PathBuf> for OsStr {
#[inline]
fn eq(&self, other: &PathBuf) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<OsStr> for PathBuf {
#[inline]
fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<PathBuf> for OsStr {
#[inline]
fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(PathBuf, OsStr);
4030#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<&OsStr> for PathBuf {
#[inline]
fn eq(&self, other: &&OsStr) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<PathBuf> for &OsStr {
#[inline]
fn eq(&self, other: &PathBuf) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<&OsStr> for PathBuf {
#[inline]
fn partial_cmp(&self, other: &&OsStr) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<PathBuf> for &OsStr {
#[inline]
fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(PathBuf, &OsStr);
4031#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<Cow<'_, OsStr>> for PathBuf {
#[inline]
fn eq(&self, other: &Cow<'_, OsStr>) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<PathBuf> for Cow<'_, OsStr> {
#[inline]
fn eq(&self, other: &PathBuf) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Cow<'_, OsStr>> for PathBuf {
#[inline]
fn partial_cmp(&self, other: &Cow<'_, OsStr>) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<PathBuf> for Cow<'_, OsStr> {
#[inline]
fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(PathBuf, Cow<'_, OsStr>);
4032#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<OsString> for PathBuf {
#[inline]
fn eq(&self, other: &OsString) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<PathBuf> for OsString {
#[inline]
fn eq(&self, other: &PathBuf) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<OsString> for PathBuf {
#[inline]
fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<PathBuf> for OsString {
#[inline]
fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(PathBuf, OsString);
4033#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<OsStr> for Path {
#[inline]
fn eq(&self, other: &OsStr) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<Path> for OsStr {
#[inline]
fn eq(&self, other: &Path) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<OsStr> for Path {
#[inline]
fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Path> for OsStr {
#[inline]
fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(Path, OsStr);
4034#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<&OsStr> for Path {
#[inline]
fn eq(&self, other: &&OsStr) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<Path> for &OsStr {
#[inline]
fn eq(&self, other: &Path) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<&OsStr> for Path {
#[inline]
fn partial_cmp(&self, other: &&OsStr) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Path> for &OsStr {
#[inline]
fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(Path, &OsStr);
4035#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<Cow<'_, OsStr>> for Path {
#[inline]
fn eq(&self, other: &Cow<'_, OsStr>) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<Path> for Cow<'_, OsStr> {
#[inline]
fn eq(&self, other: &Path) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Cow<'_, OsStr>> for Path {
#[inline]
fn partial_cmp(&self, other: &Cow<'_, OsStr>) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Path> for Cow<'_, OsStr> {
#[inline]
fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(Path, Cow<'_, OsStr>);
4036#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<OsString> for Path {
#[inline]
fn eq(&self, other: &OsString) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<Path> for OsString {
#[inline]
fn eq(&self, other: &Path) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<OsString> for Path {
#[inline]
fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Path> for OsString {
#[inline]
fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(Path, OsString);
4037#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<OsStr> for &Path {
#[inline]
fn eq(&self, other: &OsStr) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<&Path> for OsStr {
#[inline]
fn eq(&self, other: &&Path) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<OsStr> for &Path {
#[inline]
fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<&Path> for OsStr {
#[inline]
fn partial_cmp(&self, other: &&Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(&Path, OsStr);
4038#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<Cow<'_, OsStr>> for &Path {
#[inline]
fn eq(&self, other: &Cow<'_, OsStr>) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<&Path> for Cow<'_, OsStr> {
#[inline]
fn eq(&self, other: &&Path) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Cow<'_, OsStr>> for &Path {
#[inline]
fn partial_cmp(&self, other: &Cow<'_, OsStr>) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<&Path> for Cow<'_, OsStr> {
#[inline]
fn partial_cmp(&self, other: &&Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(&Path, Cow<'_, OsStr>);
4039#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<OsString> for &Path {
#[inline]
fn eq(&self, other: &OsString) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<&Path> for OsString {
#[inline]
fn eq(&self, other: &&Path) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<OsString> for &Path {
#[inline]
fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<&Path> for OsString {
#[inline]
fn partial_cmp(&self, other: &&Path) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(&Path, OsString);
4040#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<OsStr> for Cow<'_, Path> {
#[inline]
fn eq(&self, other: &OsStr) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<Cow<'_, Path>> for OsStr {
#[inline]
fn eq(&self, other: &Cow<'_, Path>) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<OsStr> for Cow<'_, Path> {
#[inline]
fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Cow<'_, Path>> for OsStr {
#[inline]
fn partial_cmp(&self, other: &Cow<'_, Path>) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(Cow<'_, Path>, OsStr);
4041#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<&OsStr> for Cow<'_, Path> {
#[inline]
fn eq(&self, other: &&OsStr) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<Cow<'_, Path>> for &OsStr {
#[inline]
fn eq(&self, other: &Cow<'_, Path>) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<&OsStr> for Cow<'_, Path> {
#[inline]
fn partial_cmp(&self, other: &&OsStr) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Cow<'_, Path>> for &OsStr {
#[inline]
fn partial_cmp(&self, other: &Cow<'_, Path>) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(Cow<'_, Path>, &OsStr);
4042#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<OsString> for Cow<'_, Path> {
#[inline]
fn eq(&self, other: &OsString) -> bool {
<Path as PartialEq>::eq(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialEq<Cow<'_, Path>> for OsString {
#[inline]
fn eq(&self, other: &Cow<'_, Path>) -> bool {
<Path as PartialEq>::eq(self.as_ref(), other)
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<OsString> for Cow<'_, Path> {
#[inline]
fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self, other.as_ref())
}
}
#[stable(feature = "cmp_path", since = "1.8.0")]
impl PartialOrd<Cow<'_, Path>> for OsString {
#[inline]
fn partial_cmp(&self, other: &Cow<'_, Path>) -> Option<cmp::Ordering> {
<Path as PartialOrd>::partial_cmp(self.as_ref(), other)
}
}impl_cmp_os_str!(Cow<'_, Path>, OsString);
4043
4044#[stable(since = "1.7.0", feature = "strip_prefix")]
4045impl fmt::Display for StripPrefixError {
4046 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4047 "prefix not found".fmt(f)
4048 }
4049}
4050
4051#[stable(since = "1.7.0", feature = "strip_prefix")]
4052impl Error for StripPrefixError {}
4053
4054#[unstable(feature = "normalize_lexically", issue = "134694")]
4055impl fmt::Display for NormalizeError {
4056 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4057 f.write_str("parent reference `..` points outside of base directory")
4058 }
4059}
4060#[unstable(feature = "normalize_lexically", issue = "134694")]
4061impl Error for NormalizeError {}
4062
4063#[stable(feature = "absolute_path", since = "1.79.0")]
4148pub fn absolute<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
4149 let path = path.as_ref();
4150 if path.as_os_str().is_empty() {
4151 Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
&::core::io::SimpleMessage {
kind: io::ErrorKind::InvalidInput,
message: "cannot make an empty path absolute",
}
}))io::const_error!(io::ErrorKind::InvalidInput, "cannot make an empty path absolute"))
4152 } else {
4153 sys::path::absolute(path)
4154 }
4155}