Skip to main content

camino/
lib.rs

1// Copyright (c) The camino Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4#![warn(missing_docs)]
5#![cfg_attr(doc_cfg, feature(doc_cfg))]
6
7//! UTF-8 encoded paths.
8//!
9//! `camino` is an extension of the [`std::path`] module that adds new [`Utf8PathBuf`] and [`Utf8Path`]
10//! types. These are like the standard library's [`PathBuf`] and [`Path`] types, except they are
11//! guaranteed to only contain UTF-8 encoded data. Therefore, they expose the ability to get their
12//! contents as strings, they implement [`Display`], etc.
13//!
14//! The [`std::path`] types are not guaranteed to be valid UTF-8. This is the right decision for the standard library,
15//! since it must be as general as possible. However, on all platforms, non-Unicode paths are vanishingly uncommon for a
16//! number of reasons:
17//! * Unicode won. There are still some legacy codebases that store paths in encodings like Shift-JIS, but most
18//!   have been converted to Unicode at this point.
19//! * Unicode is the common subset of supported paths across Windows and Unix platforms. (On Windows, Rust stores paths
20//!   as [an extension to UTF-8](https://simonsapin.github.io/wtf-8/), and converts them to UTF-16 at Win32
21//!   API boundaries.)
22//! * There are already many systems, such as Cargo, that only support UTF-8 paths. If your own tool interacts with any such
23//!   system, you can assume that paths are valid UTF-8 without creating any additional burdens on consumers.
24//! * The ["makefile problem"](https://www.mercurial-scm.org/wiki/EncodingStrategy#The_.22makefile_problem.22)
25//!   (which also applies to `Cargo.toml`, and any other metadata file that lists the names of other files) has *no general,
26//!   cross-platform solution* in systems that support non-UTF-8 paths. However, restricting paths to UTF-8 eliminates
27//!   this problem.
28//!
29//! Therefore, many programs that want to manipulate paths *do* assume they contain UTF-8 data, and convert them to [`str`]s
30//! as  necessary. However, because this invariant is not encoded in the [`Path`] type, conversions such as
31//! `path.to_str().unwrap()` need to be repeated again and again, creating a frustrating experience.
32//!
33//! Instead, `camino` allows you to check that your paths are UTF-8 *once*, and then manipulate them
34//! as valid UTF-8 from there on, avoiding repeated lossy and confusing conversions.
35
36// General note: we use #[allow(clippy::incompatible_msrv)] for code that's already guarded by a
37// version-specific cfg conditional.
38
39use std::{
40    borrow::{Borrow, Cow},
41    cmp::Ordering,
42    convert::{Infallible, TryFrom, TryInto},
43    error,
44    ffi::{OsStr, OsString},
45    fmt,
46    fs::{self, Metadata},
47    hash::{Hash, Hasher},
48    io,
49    iter::FusedIterator,
50    ops::Deref,
51    path::*,
52    rc::Rc,
53    str::FromStr,
54    sync::Arc,
55};
56
57#[cfg(feature = "proptest1")]
58mod proptest_impls;
59#[cfg(feature = "serde1")]
60mod serde_impls;
61#[cfg(test)]
62mod tests;
63
64/// An owned, mutable UTF-8 path (akin to [`String`]).
65///
66/// This type provides methods like [`push`] and [`set_extension`] that mutate
67/// the path in place. It also implements [`Deref`] to [`Utf8Path`], meaning that
68/// all methods on [`Utf8Path`] slices are available on [`Utf8PathBuf`] values as well.
69///
70/// [`push`]: Utf8PathBuf::push
71/// [`set_extension`]: Utf8PathBuf::set_extension
72///
73/// # Examples
74///
75/// You can use [`push`] to build up a [`Utf8PathBuf`] from
76/// components:
77///
78/// ```
79/// use camino::Utf8PathBuf;
80///
81/// let mut path = Utf8PathBuf::new();
82///
83/// path.push(r"C:\");
84/// path.push("windows");
85/// path.push("system32");
86///
87/// path.set_extension("dll");
88/// ```
89///
90/// However, [`push`] is best used for dynamic situations. This is a better way
91/// to do this when you know all of the components ahead of time:
92///
93/// ```
94/// use camino::Utf8PathBuf;
95///
96/// let path: Utf8PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
97/// ```
98///
99/// We can still do better than this! Since these are all strings, we can use
100/// [`From::from`]:
101///
102/// ```
103/// use camino::Utf8PathBuf;
104///
105/// let path = Utf8PathBuf::from(r"C:\windows\system32.dll");
106/// ```
107///
108/// Which method works best depends on what kind of situation you're in.
109// NB: Internal PathBuf must only contain utf8 data
110#[derive(Clone, Default)]
111#[repr(transparent)]
112pub struct Utf8PathBuf(PathBuf);
113
114impl Utf8PathBuf {
115    /// Allocates an empty [`Utf8PathBuf`].
116    ///
117    /// *On Rust 1.91 or newer, this is a `const fn`.*
118    ///
119    /// # Examples
120    ///
121    /// ```
122    /// use camino::Utf8PathBuf;
123    ///
124    /// let path = Utf8PathBuf::new();
125    /// ```
126    #[must_use]
127    #[cfg(pathbuf_const_new)]
128    #[expect(clippy::incompatible_msrv)]
129    pub const fn new() -> Utf8PathBuf {
130        Utf8PathBuf(PathBuf::new())
131    }
132
133    /// Allocates an empty [`Utf8PathBuf`].
134    ///
135    /// # Examples
136    ///
137    /// ```
138    /// use camino::Utf8PathBuf;
139    ///
140    /// let path = Utf8PathBuf::new();
141    /// ```
142    #[must_use]
143    #[cfg(not(pathbuf_const_new))]
144    pub fn new() -> Utf8PathBuf {
145        Utf8PathBuf(PathBuf::new())
146    }
147
148    /// Creates a new [`Utf8PathBuf`] from a [`PathBuf`] containing valid UTF-8 characters.
149    ///
150    /// Errors with the original [`PathBuf`] if it is not valid UTF-8.
151    ///
152    /// For a version that returns a type that implements [`std::error::Error`],
153    /// see [`TryFrom<&PathBuf>`][tryfrom].
154    ///
155    /// [tryfrom]: #impl-TryFrom<PathBuf>-for-Utf8PathBuf
156    ///
157    /// # Examples
158    ///
159    /// ```
160    /// use camino::Utf8PathBuf;
161    /// use std::ffi::OsStr;
162    /// # #[cfg(unix)]
163    /// use std::os::unix::ffi::OsStrExt;
164    /// use std::path::PathBuf;
165    ///
166    /// let unicode_path = PathBuf::from("/valid/unicode");
167    /// Utf8PathBuf::from_path_buf(unicode_path).expect("valid Unicode path succeeded");
168    ///
169    /// // Paths on Unix can be non-UTF-8.
170    /// # #[cfg(unix)]
171    /// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
172    /// # #[cfg(unix)]
173    /// let non_unicode_path = PathBuf::from(non_unicode_str);
174    /// # #[cfg(unix)]
175    /// Utf8PathBuf::from_path_buf(non_unicode_path).expect_err("non-Unicode path failed");
176    /// ```
177    pub fn from_path_buf(path: PathBuf) -> Result<Utf8PathBuf, PathBuf> {
178        match path.into_os_string().into_string() {
179            Ok(string) => Ok(Utf8PathBuf::from(string)),
180            Err(os_string) => Err(PathBuf::from(os_string)),
181        }
182    }
183
184    /// Creates a new [`Utf8PathBuf`] from an [`OsString`] containing valid UTF-8 characters.
185    ///
186    /// Errors with the original [`OsString`] if it is not valid UTF-8.
187    ///
188    /// For a version that returns a type that implements [`std::error::Error`], use the
189    /// [`TryFrom<OsString>`] impl.
190    ///
191    /// [`TryFrom<OsString>`]: #impl-TryFrom<OsString>-for-Utf8PathBuf
192    ///
193    /// # Examples
194    ///
195    /// ```
196    /// # #[cfg(osstring_from_str)] {
197    /// use camino::Utf8PathBuf;
198    /// use std::ffi::OsStr;
199    /// use std::ffi::OsString;
200    /// use std::convert::TryFrom;
201    /// use std::str::FromStr;
202    /// # #[cfg(unix)]
203    /// use std::os::unix::ffi::OsStrExt;
204    ///
205    /// let unicode_string = OsString::from_str("/valid/unicode").unwrap();
206    /// Utf8PathBuf::from_os_string(unicode_string).expect("valid Unicode path succeeded");
207    ///
208    /// // Paths on Unix can be non-UTF-8.
209    /// # #[cfg(unix)]
210    /// let non_unicode_string = OsStr::from_bytes(b"\xFF\xFF\xFF").into();
211    /// # #[cfg(unix)]
212    /// Utf8PathBuf::from_os_string(non_unicode_string).expect_err("non-Unicode path failed");
213    /// # }
214    /// ```
215    pub fn from_os_string(os_string: OsString) -> Result<Utf8PathBuf, OsString> {
216        match os_string.into_string() {
217            Ok(string) => Ok(Utf8PathBuf::from(string)),
218            Err(os_string) => Err(os_string),
219        }
220    }
221
222    /// Converts a [`Utf8PathBuf`] to a [`PathBuf`].
223    ///
224    /// This is equivalent to the [`From<Utf8PathBuf> for PathBuf`][from] implementation,
225    /// but may aid in type inference.
226    ///
227    /// [from]: #impl-From<Utf8PathBuf>-for-PathBuf
228    ///
229    /// # Examples
230    ///
231    /// ```
232    /// use camino::Utf8PathBuf;
233    /// use std::path::PathBuf;
234    ///
235    /// let utf8_path_buf = Utf8PathBuf::from("foo.txt");
236    /// let std_path_buf = utf8_path_buf.into_std_path_buf();
237    /// assert_eq!(std_path_buf.to_str(), Some("foo.txt"));
238    ///
239    /// // Convert back to a Utf8PathBuf.
240    /// let new_utf8_path_buf = Utf8PathBuf::from_path_buf(std_path_buf).unwrap();
241    /// assert_eq!(new_utf8_path_buf, "foo.txt");
242    /// ```
243    #[must_use = "`self` will be dropped if the result is not used"]
244    pub fn into_std_path_buf(self) -> PathBuf {
245        self.into()
246    }
247
248    /// Creates a new [`Utf8PathBuf`] with a given capacity used to create the internal [`PathBuf`].
249    /// See [`with_capacity`] defined on [`PathBuf`].
250    ///
251    /// # Examples
252    ///
253    /// ```
254    /// use camino::Utf8PathBuf;
255    ///
256    /// let mut path = Utf8PathBuf::with_capacity(10);
257    /// let capacity = path.capacity();
258    ///
259    /// // This push is done without reallocating
260    /// path.push(r"C:\");
261    ///
262    /// assert_eq!(capacity, path.capacity());
263    /// ```
264    ///
265    /// [`with_capacity`]: PathBuf::with_capacity
266    #[allow(clippy::incompatible_msrv)]
267    #[must_use]
268    pub fn with_capacity(capacity: usize) -> Utf8PathBuf {
269        Utf8PathBuf(PathBuf::with_capacity(capacity))
270    }
271
272    /// Coerces to a [`Utf8Path`] slice.
273    ///
274    /// # Examples
275    ///
276    /// ```
277    /// use camino::{Utf8Path, Utf8PathBuf};
278    ///
279    /// let p = Utf8PathBuf::from("/test");
280    /// assert_eq!(Utf8Path::new("/test"), p.as_path());
281    /// ```
282    #[must_use]
283    pub fn as_path(&self) -> &Utf8Path {
284        // SAFETY: every Utf8PathBuf constructor ensures that self is valid UTF-8
285        unsafe { Utf8Path::assume_utf8(&self.0) }
286    }
287
288    /// Consumes and leaks the [`Utf8PathBuf`], returning a mutable reference to the contents,
289    /// `&'a mut Utf8Path`.
290    ///
291    /// The caller has free choice over the returned lifetime, including 'static.
292    /// Indeed, this function is ideally used for data that lives for the remainder of
293    /// the program’s life, as dropping the returned reference will cause a memory leak.
294    ///
295    /// It does not reallocate or shrink the [`Utf8PathBuf`], so the leaked allocation may include
296    /// unused capacity that is not part of the returned slice. If you want to discard excess
297    /// capacity, call [`into_boxed_path`], and then [`Box::leak`] instead.
298    /// However, keep in mind that trimming the capacity may result in a reallocation and copy.
299    ///
300    /// *Requires Rust 1.89 or newer.*
301    ///
302    /// [`into_boxed_path`]: Self::into_boxed_path
303    #[cfg(os_string_pathbuf_leak)]
304    #[allow(clippy::incompatible_msrv)]
305    #[inline]
306    pub fn leak<'a>(self) -> &'a mut Utf8Path {
307        // SAFETY: every Utf8PathBuf constructor ensures that self is valid UTF-8
308        unsafe { Utf8Path::assume_utf8_mut(self.0.leak()) }
309    }
310
311    /// Extends `self` with `path`.
312    ///
313    /// If `path` is absolute, it replaces the current path.
314    ///
315    /// On Windows:
316    ///
317    /// * if `path` has a root but no prefix (e.g., `\windows`), it
318    ///   replaces everything except for the prefix (if any) of `self`.
319    /// * if `path` has a prefix but no root, it replaces `self`.
320    ///
321    /// # Examples
322    ///
323    /// Pushing a relative path extends the existing path:
324    ///
325    /// ```
326    /// use camino::Utf8PathBuf;
327    ///
328    /// let mut path = Utf8PathBuf::from("/tmp");
329    /// path.push("file.bk");
330    /// assert_eq!(path, Utf8PathBuf::from("/tmp/file.bk"));
331    /// ```
332    ///
333    /// Pushing an absolute path replaces the existing path:
334    ///
335    /// ```
336    /// use camino::Utf8PathBuf;
337    ///
338    /// let mut path = Utf8PathBuf::from("/tmp");
339    /// path.push("/etc");
340    /// assert_eq!(path, Utf8PathBuf::from("/etc"));
341    /// ```
342    pub fn push(&mut self, path: impl AsRef<Utf8Path>) {
343        self.0.push(&path.as_ref().0)
344    }
345
346    /// Truncates `self` to [`self.parent`].
347    ///
348    /// Returns `false` and does nothing if [`self.parent`] is [`None`].
349    /// Otherwise, returns `true`.
350    ///
351    /// [`self.parent`]: Utf8Path::parent
352    ///
353    /// # Examples
354    ///
355    /// ```
356    /// use camino::{Utf8Path, Utf8PathBuf};
357    ///
358    /// let mut p = Utf8PathBuf::from("/spirited/away.rs");
359    ///
360    /// p.pop();
361    /// assert_eq!(Utf8Path::new("/spirited"), p);
362    /// p.pop();
363    /// assert_eq!(Utf8Path::new("/"), p);
364    /// ```
365    pub fn pop(&mut self) -> bool {
366        self.0.pop()
367    }
368
369    /// Updates [`self.file_name`] to `file_name`.
370    ///
371    /// If [`self.file_name`] was [`None`], this is equivalent to pushing
372    /// `file_name`.
373    ///
374    /// Otherwise it is equivalent to calling [`pop`] and then pushing
375    /// `file_name`. The new path will be a sibling of the original path.
376    /// (That is, it will have the same parent.)
377    ///
378    /// [`self.file_name`]: Utf8Path::file_name
379    /// [`pop`]: Utf8PathBuf::pop
380    ///
381    /// # Examples
382    ///
383    /// ```
384    /// use camino::Utf8PathBuf;
385    ///
386    /// let mut buf = Utf8PathBuf::from("/");
387    /// assert_eq!(buf.file_name(), None);
388    /// buf.set_file_name("bar");
389    /// assert_eq!(buf, Utf8PathBuf::from("/bar"));
390    /// assert!(buf.file_name().is_some());
391    /// buf.set_file_name("baz.txt");
392    /// assert_eq!(buf, Utf8PathBuf::from("/baz.txt"));
393    /// ```
394    pub fn set_file_name(&mut self, file_name: impl AsRef<str>) {
395        self.0.set_file_name(file_name.as_ref())
396    }
397
398    /// Updates [`self.extension`] to `extension`.
399    ///
400    /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
401    /// returns `true` and updates the extension otherwise.
402    ///
403    /// If [`self.extension`] is [`None`], the extension is added; otherwise
404    /// it is replaced.
405    ///
406    /// [`self.file_name`]: Utf8Path::file_name
407    /// [`self.extension`]: Utf8Path::extension
408    ///
409    /// # Examples
410    ///
411    /// ```
412    /// use camino::{Utf8Path, Utf8PathBuf};
413    ///
414    /// let mut p = Utf8PathBuf::from("/feel/the");
415    ///
416    /// p.set_extension("force");
417    /// assert_eq!(Utf8Path::new("/feel/the.force"), p.as_path());
418    ///
419    /// p.set_extension("dark_side");
420    /// assert_eq!(Utf8Path::new("/feel/the.dark_side"), p.as_path());
421    /// ```
422    pub fn set_extension(&mut self, extension: impl AsRef<str>) -> bool {
423        self.0.set_extension(extension.as_ref())
424    }
425
426    /// Appends to [`self.extension`] with `extension`.
427    ///
428    /// Returns `false` and does nothing if [`self.file_name`] is [`None`],
429    /// returns `true` and updates the extension otherwise.
430    ///
431    /// *Requires Rust 1.91 or newer.*
432    ///
433    /// # Panics
434    ///
435    /// Panics if the passed extension contains a path separator (see
436    /// [`is_separator`]).
437    ///
438    /// # Caveats
439    ///
440    /// The appended `extension` may contain dots and will be used in its entirety,
441    /// but only the part after the final dot will be reflected in [`self.extension`].
442    ///
443    /// [`self.file_name`]: Utf8Path::file_name
444    /// [`self.extension`]: Utf8Path::extension
445    ///
446    /// # Examples
447    ///
448    /// ```
449    /// use camino::{Utf8Path, Utf8PathBuf};
450    ///
451    /// let mut p = Utf8PathBuf::from("/feel/the");
452    ///
453    /// p.add_extension("formatted");
454    /// assert_eq!(Utf8Path::new("/feel/the.formatted"), p.as_path());
455    ///
456    /// p.add_extension("dark.side");
457    /// assert_eq!(Utf8Path::new("/feel/the.formatted.dark.side"), p.as_path());
458    /// ```
459    #[cfg(path_add_extension)]
460    #[expect(clippy::incompatible_msrv)]
461    pub fn add_extension<S: AsRef<str>>(&mut self, extension: S) -> bool {
462        self.0.add_extension(extension.as_ref())
463    }
464
465    /// Consumes the [`Utf8PathBuf`], yielding its internal [`String`] storage.
466    ///
467    /// # Examples
468    ///
469    /// ```
470    /// use camino::Utf8PathBuf;
471    ///
472    /// let p = Utf8PathBuf::from("/the/head");
473    /// let s = p.into_string();
474    /// assert_eq!(s, "/the/head");
475    /// ```
476    #[must_use = "`self` will be dropped if the result is not used"]
477    pub fn into_string(self) -> String {
478        self.into_os_string().into_string().unwrap()
479    }
480
481    /// Consumes the [`Utf8PathBuf`], yielding its internal [`OsString`] storage.
482    ///
483    /// # Examples
484    ///
485    /// ```
486    /// use camino::Utf8PathBuf;
487    /// use std::ffi::OsStr;
488    ///
489    /// let p = Utf8PathBuf::from("/the/head");
490    /// let s = p.into_os_string();
491    /// assert_eq!(s, OsStr::new("/the/head"));
492    /// ```
493    #[must_use = "`self` will be dropped if the result is not used"]
494    pub fn into_os_string(self) -> OsString {
495        self.0.into_os_string()
496    }
497
498    /// Converts this [`Utf8PathBuf`] into a [boxed](Box) [`Utf8Path`].
499    #[must_use = "`self` will be dropped if the result is not used"]
500    pub fn into_boxed_path(self) -> Box<Utf8Path> {
501        let ptr = Box::into_raw(self.0.into_boxed_path()) as *mut Utf8Path;
502        // SAFETY:
503        // * self is valid UTF-8
504        // * ptr was constructed by consuming self so it represents an owned path
505        // * Utf8Path is marked as #[repr(transparent)] so the conversion from *mut Path to
506        //   *mut Utf8Path is valid
507        unsafe { Box::from_raw(ptr) }
508    }
509
510    /// Invokes [`capacity`] on the underlying instance of [`PathBuf`].
511    ///
512    /// [`capacity`]: PathBuf::capacity
513    #[allow(clippy::incompatible_msrv)]
514    #[must_use]
515    pub fn capacity(&self) -> usize {
516        self.0.capacity()
517    }
518
519    /// Invokes [`clear`] on the underlying instance of [`PathBuf`].
520    ///
521    /// [`clear`]: PathBuf::clear
522    #[allow(clippy::incompatible_msrv)]
523    pub fn clear(&mut self) {
524        self.0.clear()
525    }
526
527    /// Invokes [`reserve`] on the underlying instance of [`PathBuf`].
528    ///
529    /// [`reserve`]: PathBuf::reserve
530    #[allow(clippy::incompatible_msrv)]
531    pub fn reserve(&mut self, additional: usize) {
532        self.0.reserve(additional)
533    }
534
535    /// Invokes [`try_reserve`] on the underlying instance of [`PathBuf`].
536    ///
537    /// *Requires Rust 1.63 or newer.*
538    ///
539    /// [`try_reserve`]: PathBuf::try_reserve
540    #[cfg(try_reserve_2)]
541    #[allow(clippy::incompatible_msrv)]
542    #[inline]
543    pub fn try_reserve(
544        &mut self,
545        additional: usize,
546    ) -> Result<(), std::collections::TryReserveError> {
547        self.0.try_reserve(additional)
548    }
549
550    /// Invokes [`reserve_exact`] on the underlying instance of [`PathBuf`].
551    ///
552    /// [`reserve_exact`]: PathBuf::reserve_exact
553    #[allow(clippy::incompatible_msrv)]
554    pub fn reserve_exact(&mut self, additional: usize) {
555        self.0.reserve_exact(additional)
556    }
557
558    /// Invokes [`try_reserve_exact`] on the underlying instance of [`PathBuf`].
559    ///
560    /// *Requires Rust 1.63 or newer.*
561    ///
562    /// [`try_reserve_exact`]: PathBuf::try_reserve_exact
563    #[cfg(try_reserve_2)]
564    #[allow(clippy::incompatible_msrv)]
565    #[inline]
566    pub fn try_reserve_exact(
567        &mut self,
568        additional: usize,
569    ) -> Result<(), std::collections::TryReserveError> {
570        self.0.try_reserve_exact(additional)
571    }
572
573    /// Invokes [`shrink_to_fit`] on the underlying instance of [`PathBuf`].
574    ///
575    /// [`shrink_to_fit`]: PathBuf::shrink_to_fit
576    #[allow(clippy::incompatible_msrv)]
577    pub fn shrink_to_fit(&mut self) {
578        self.0.shrink_to_fit()
579    }
580
581    /// Invokes [`shrink_to`] on the underlying instance of [`PathBuf`].
582    ///
583    /// [`shrink_to`]: PathBuf::shrink_to
584    #[allow(clippy::incompatible_msrv)]
585    #[inline]
586    pub fn shrink_to(&mut self, min_capacity: usize) {
587        self.0.shrink_to(min_capacity)
588    }
589}
590
591impl Deref for Utf8PathBuf {
592    type Target = Utf8Path;
593
594    fn deref(&self) -> &Utf8Path {
595        self.as_path()
596    }
597}
598
599/// *Requires Rust 1.68 or newer.*
600#[cfg(path_buf_deref_mut)]
601#[allow(clippy::incompatible_msrv)]
602impl std::ops::DerefMut for Utf8PathBuf {
603    fn deref_mut(&mut self) -> &mut Self::Target {
604        unsafe { Utf8Path::assume_utf8_mut(&mut self.0) }
605    }
606}
607
608impl fmt::Debug for Utf8PathBuf {
609    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
610        fmt::Debug::fmt(&**self, f)
611    }
612}
613
614impl fmt::Display for Utf8PathBuf {
615    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
616        fmt::Display::fmt(self.as_str(), f)
617    }
618}
619
620impl<P: AsRef<Utf8Path>> Extend<P> for Utf8PathBuf {
621    fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
622        for path in iter {
623            self.push(path);
624        }
625    }
626}
627
628/// A slice of a UTF-8 path (akin to [`str`]).
629///
630/// This type supports a number of operations for inspecting a path, including
631/// breaking the path into its components (separated by `/` on Unix and by either
632/// `/` or `\` on Windows), extracting the file name, determining whether the path
633/// is absolute, and so on.
634///
635/// This is an *unsized* type, meaning that it must always be used behind a
636/// pointer like `&` or [`Box`]. For an owned version of this type,
637/// see [`Utf8PathBuf`].
638///
639/// # Examples
640///
641/// ```
642/// use camino::Utf8Path;
643///
644/// // Note: this example does work on Windows
645/// let path = Utf8Path::new("./foo/bar.txt");
646///
647/// let parent = path.parent();
648/// assert_eq!(parent, Some(Utf8Path::new("./foo")));
649///
650/// let file_stem = path.file_stem();
651/// assert_eq!(file_stem, Some("bar"));
652///
653/// let extension = path.extension();
654/// assert_eq!(extension, Some("txt"));
655/// ```
656// NB: Internal Path must only contain utf8 data
657#[repr(transparent)]
658pub struct Utf8Path(Path);
659
660impl Utf8Path {
661    /// Directly wraps a string slice as a [`Utf8Path`] slice.
662    ///
663    /// This is a cost-free conversion.
664    ///
665    /// # Examples
666    ///
667    /// ```
668    /// use camino::Utf8Path;
669    ///
670    /// Utf8Path::new("foo.txt");
671    /// ```
672    ///
673    /// You can create [`Utf8Path`]s from [`String`]s, or even other [`Utf8Path`]s:
674    ///
675    /// ```
676    /// use camino::Utf8Path;
677    ///
678    /// let string = String::from("foo.txt");
679    /// let from_string = Utf8Path::new(&string);
680    /// let from_path = Utf8Path::new(&from_string);
681    /// assert_eq!(from_string, from_path);
682    /// ```
683    pub fn new(s: &(impl AsRef<str> + ?Sized)) -> &Utf8Path {
684        let path = Path::new(s.as_ref());
685        // SAFETY: s is a str which means it is always valid UTF-8
686        unsafe { Utf8Path::assume_utf8(path) }
687    }
688
689    /// Converts a [`Path`] to a [`Utf8Path`].
690    ///
691    /// Returns [`None`] if the path is not valid UTF-8.
692    ///
693    /// For a version that returns a type that implements [`std::error::Error`],
694    /// see [`TryFrom<&Path>`][tryfrom].
695    ///
696    /// [tryfrom]: #impl-TryFrom<%26Path>-for-%26Utf8Path
697    ///
698    /// # Examples
699    ///
700    /// ```
701    /// use camino::Utf8Path;
702    /// use std::ffi::OsStr;
703    /// # #[cfg(unix)]
704    /// use std::os::unix::ffi::OsStrExt;
705    /// use std::path::Path;
706    ///
707    /// let unicode_path = Path::new("/valid/unicode");
708    /// Utf8Path::from_path(unicode_path).expect("valid Unicode path succeeded");
709    ///
710    /// // Paths on Unix can be non-UTF-8.
711    /// # #[cfg(unix)]
712    /// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
713    /// # #[cfg(unix)]
714    /// let non_unicode_path = Path::new(non_unicode_str);
715    /// # #[cfg(unix)]
716    /// assert!(Utf8Path::from_path(non_unicode_path).is_none(), "non-Unicode path failed");
717    /// ```
718    pub fn from_path(path: &Path) -> Option<&Utf8Path> {
719        path.as_os_str().to_str().map(Utf8Path::new)
720    }
721
722    /// Converts an [`OsStr`] to a [`Utf8Path`].
723    ///
724    /// Returns [`None`] if the path is not valid UTF-8.
725    ///
726    /// For a version that returns a type that implements [`std::error::Error`], use the
727    /// [`TryFrom<&OsStr>`][tryfrom] impl.
728    ///
729    /// [tryfrom]: #impl-TryFrom<%26OsStr>-for-%26Utf8Path
730    ///
731    /// # Examples
732    ///
733    /// ```
734    /// use camino::Utf8Path;
735    /// use std::ffi::OsStr;
736    /// # #[cfg(unix)]
737    /// use std::os::unix::ffi::OsStrExt;
738    /// use std::path::Path;
739    ///
740    /// let unicode_string = OsStr::new("/valid/unicode");
741    /// Utf8Path::from_os_str(unicode_string).expect("valid Unicode string succeeded");
742    ///
743    /// // Paths on Unix can be non-UTF-8.
744    /// # #[cfg(unix)]
745    /// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
746    /// # #[cfg(unix)]
747    /// assert!(Utf8Path::from_os_str(non_unicode_str).is_none(), "non-Unicode string failed");
748    /// ```
749    pub fn from_os_str(path: &OsStr) -> Option<&Utf8Path> {
750        path.to_str().map(Utf8Path::new)
751    }
752
753    /// Converts a [`Utf8Path`] to a [`Path`].
754    ///
755    /// This is equivalent to the [`AsRef<Path> for Utf8PathBuf`][asref] implementation,
756    /// but may aid in type inference.
757    ///
758    /// [asref]: Utf8PathBuf#impl-AsRef<Path>-for-Utf8PathBuf
759    ///
760    /// # Examples
761    ///
762    /// ```
763    /// use camino::Utf8Path;
764    /// use std::path::Path;
765    ///
766    /// let utf8_path = Utf8Path::new("foo.txt");
767    /// let std_path: &Path = utf8_path.as_std_path();
768    /// assert_eq!(std_path.to_str(), Some("foo.txt"));
769    ///
770    /// // Convert back to a Utf8Path.
771    /// let new_utf8_path = Utf8Path::from_path(std_path).unwrap();
772    /// assert_eq!(new_utf8_path, "foo.txt");
773    /// ```
774    #[inline]
775    pub fn as_std_path(&self) -> &Path {
776        self.as_ref()
777    }
778
779    /// Yields the underlying [`str`] slice.
780    ///
781    /// Unlike [`Path::to_str`], this always returns a slice because the contents
782    /// of a [`Utf8Path`] are guaranteed to be valid UTF-8.
783    ///
784    /// # Examples
785    ///
786    /// ```
787    /// use camino::Utf8Path;
788    ///
789    /// let s = Utf8Path::new("foo.txt").as_str();
790    /// assert_eq!(s, "foo.txt");
791    /// ```
792    ///
793    /// [`str`]: str
794    #[inline]
795    #[must_use]
796    pub fn as_str(&self) -> &str {
797        // SAFETY: every Utf8Path constructor ensures that self is valid UTF-8
798        unsafe { str_assume_utf8(self.as_os_str()) }
799    }
800
801    /// Yields the underlying [`OsStr`] slice.
802    ///
803    /// # Examples
804    ///
805    /// ```
806    /// use camino::Utf8Path;
807    ///
808    /// let os_str = Utf8Path::new("foo.txt").as_os_str();
809    /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt"));
810    /// ```
811    #[inline]
812    #[must_use]
813    pub fn as_os_str(&self) -> &OsStr {
814        self.0.as_os_str()
815    }
816
817    /// Converts a [`Utf8Path`] to an owned [`Utf8PathBuf`].
818    ///
819    /// # Examples
820    ///
821    /// ```
822    /// use camino::{Utf8Path, Utf8PathBuf};
823    ///
824    /// let path_buf = Utf8Path::new("foo.txt").to_path_buf();
825    /// assert_eq!(path_buf, Utf8PathBuf::from("foo.txt"));
826    /// ```
827    #[inline]
828    #[must_use = "this returns the result of the operation, \
829                  without modifying the original"]
830    pub fn to_path_buf(&self) -> Utf8PathBuf {
831        Utf8PathBuf(self.0.to_path_buf())
832    }
833
834    /// Returns `true` if the [`Utf8Path`] is absolute, i.e., if it is independent of
835    /// the current directory.
836    ///
837    /// * On Unix, a path is absolute if it starts with the root, so
838    ///   `is_absolute` and [`has_root`] are equivalent.
839    ///
840    /// * On Windows, a path is absolute if it has a prefix and starts with the
841    ///   root: `C:\windows` is absolute, while `C:temp` and `\temp` are not.
842    ///
843    /// # Examples
844    ///
845    /// ```
846    /// use camino::Utf8Path;
847    ///
848    /// assert!(!Utf8Path::new("foo.txt").is_absolute());
849    /// ```
850    ///
851    /// [`has_root`]: Utf8Path::has_root
852    #[inline]
853    #[must_use]
854    pub fn is_absolute(&self) -> bool {
855        self.0.is_absolute()
856    }
857
858    /// Returns `true` if the [`Utf8Path`] is relative, i.e., not absolute.
859    ///
860    /// See [`is_absolute`]'s documentation for more details.
861    ///
862    /// # Examples
863    ///
864    /// ```
865    /// use camino::Utf8Path;
866    ///
867    /// assert!(Utf8Path::new("foo.txt").is_relative());
868    /// ```
869    ///
870    /// [`is_absolute`]: Utf8Path::is_absolute
871    #[inline]
872    #[must_use]
873    pub fn is_relative(&self) -> bool {
874        self.0.is_relative()
875    }
876
877    /// Returns `true` if the [`Utf8Path`] has a root.
878    ///
879    /// * On Unix, a path has a root if it begins with `/`.
880    ///
881    /// * On Windows, a path has a root if it:
882    ///     * has no prefix and begins with a separator, e.g., `\windows`
883    ///     * has a prefix followed by a separator, e.g., `C:\windows` but not `C:windows`
884    ///     * has any non-disk prefix, e.g., `\\server\share`
885    ///
886    /// # Examples
887    ///
888    /// ```
889    /// use camino::Utf8Path;
890    ///
891    /// assert!(Utf8Path::new("/etc/passwd").has_root());
892    /// ```
893    #[inline]
894    #[must_use]
895    pub fn has_root(&self) -> bool {
896        self.0.has_root()
897    }
898
899    /// Returns the [`Path`] without its final component, if there is one.
900    ///
901    /// Returns [`None`] if the path terminates in a root or prefix.
902    ///
903    /// # Examples
904    ///
905    /// ```
906    /// use camino::Utf8Path;
907    ///
908    /// let path = Utf8Path::new("/foo/bar");
909    /// let parent = path.parent().unwrap();
910    /// assert_eq!(parent, Utf8Path::new("/foo"));
911    ///
912    /// let grand_parent = parent.parent().unwrap();
913    /// assert_eq!(grand_parent, Utf8Path::new("/"));
914    /// assert_eq!(grand_parent.parent(), None);
915    /// ```
916    #[inline]
917    #[must_use]
918    pub fn parent(&self) -> Option<&Utf8Path> {
919        self.0.parent().map(|path| {
920            // SAFETY: self is valid UTF-8, so parent is valid UTF-8 as well
921            unsafe { Utf8Path::assume_utf8(path) }
922        })
923    }
924
925    /// Produces an iterator over [`Utf8Path`] and its ancestors.
926    ///
927    /// The iterator will yield the [`Utf8Path`] that is returned if the [`parent`] method is used zero
928    /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`,
929    /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns
930    /// [`None`], the iterator will do likewise. The iterator will always yield at least one value,
931    /// namely `&self`.
932    ///
933    /// # Examples
934    ///
935    /// ```
936    /// use camino::Utf8Path;
937    ///
938    /// let mut ancestors = Utf8Path::new("/foo/bar").ancestors();
939    /// assert_eq!(ancestors.next(), Some(Utf8Path::new("/foo/bar")));
940    /// assert_eq!(ancestors.next(), Some(Utf8Path::new("/foo")));
941    /// assert_eq!(ancestors.next(), Some(Utf8Path::new("/")));
942    /// assert_eq!(ancestors.next(), None);
943    ///
944    /// let mut ancestors = Utf8Path::new("../foo/bar").ancestors();
945    /// assert_eq!(ancestors.next(), Some(Utf8Path::new("../foo/bar")));
946    /// assert_eq!(ancestors.next(), Some(Utf8Path::new("../foo")));
947    /// assert_eq!(ancestors.next(), Some(Utf8Path::new("..")));
948    /// assert_eq!(ancestors.next(), Some(Utf8Path::new("")));
949    /// assert_eq!(ancestors.next(), None);
950    /// ```
951    ///
952    /// [`parent`]: Utf8Path::parent
953    #[inline]
954    pub fn ancestors(&self) -> Utf8Ancestors<'_> {
955        Utf8Ancestors(self.0.ancestors())
956    }
957
958    /// Returns the final component of the [`Utf8Path`], if there is one.
959    ///
960    /// If the path is a normal file, this is the file name. If it's the path of a directory, this
961    /// is the directory name.
962    ///
963    /// Returns [`None`] if the path terminates in `..`.
964    ///
965    /// # Examples
966    ///
967    /// ```
968    /// use camino::Utf8Path;
969    ///
970    /// assert_eq!(Some("bin"), Utf8Path::new("/usr/bin/").file_name());
971    /// assert_eq!(Some("foo.txt"), Utf8Path::new("tmp/foo.txt").file_name());
972    /// assert_eq!(Some("foo.txt"), Utf8Path::new("foo.txt/.").file_name());
973    /// assert_eq!(Some("foo.txt"), Utf8Path::new("foo.txt/.//").file_name());
974    /// assert_eq!(None, Utf8Path::new("foo.txt/..").file_name());
975    /// assert_eq!(None, Utf8Path::new("/").file_name());
976    /// ```
977    #[inline]
978    #[must_use]
979    pub fn file_name(&self) -> Option<&str> {
980        self.0.file_name().map(|s| {
981            // SAFETY: self is valid UTF-8, so file_name is valid UTF-8 as well
982            unsafe { str_assume_utf8(s) }
983        })
984    }
985
986    /// Returns a path that, when joined onto `base`, yields `self`.
987    ///
988    /// # Errors
989    ///
990    /// If `base` is not a prefix of `self` (i.e., [`starts_with`]
991    /// returns `false`), returns [`Err`].
992    ///
993    /// [`starts_with`]: Utf8Path::starts_with
994    ///
995    /// # Examples
996    ///
997    /// ```
998    /// use camino::{Utf8Path, Utf8PathBuf};
999    ///
1000    /// let path = Utf8Path::new("/test/haha/foo.txt");
1001    ///
1002    /// assert_eq!(path.strip_prefix("/"), Ok(Utf8Path::new("test/haha/foo.txt")));
1003    /// assert_eq!(path.strip_prefix("/test"), Ok(Utf8Path::new("haha/foo.txt")));
1004    /// assert_eq!(path.strip_prefix("/test/"), Ok(Utf8Path::new("haha/foo.txt")));
1005    /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Utf8Path::new("")));
1006    /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Utf8Path::new("")));
1007    ///
1008    /// assert!(path.strip_prefix("test").is_err());
1009    /// assert!(path.strip_prefix("/haha").is_err());
1010    ///
1011    /// let prefix = Utf8PathBuf::from("/test/");
1012    /// assert_eq!(path.strip_prefix(prefix), Ok(Utf8Path::new("haha/foo.txt")));
1013    /// ```
1014    #[inline]
1015    pub fn strip_prefix(&self, base: impl AsRef<Path>) -> Result<&Utf8Path, StripPrefixError> {
1016        self.0.strip_prefix(base).map(|path| {
1017            // SAFETY: self is valid UTF-8, and strip_prefix returns a part of self (or an empty
1018            // string), so it is valid UTF-8 as well.
1019            unsafe { Utf8Path::assume_utf8(path) }
1020        })
1021    }
1022
1023    /// Determines whether `base` is a prefix of `self`.
1024    ///
1025    /// Only considers whole path components to match.
1026    ///
1027    /// # Examples
1028    ///
1029    /// ```
1030    /// use camino::Utf8Path;
1031    ///
1032    /// let path = Utf8Path::new("/etc/passwd");
1033    ///
1034    /// assert!(path.starts_with("/etc"));
1035    /// assert!(path.starts_with("/etc/"));
1036    /// assert!(path.starts_with("/etc/passwd"));
1037    /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay
1038    /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay
1039    ///
1040    /// assert!(!path.starts_with("/e"));
1041    /// assert!(!path.starts_with("/etc/passwd.txt"));
1042    ///
1043    /// assert!(!Utf8Path::new("/etc/foo.rs").starts_with("/etc/foo"));
1044    /// ```
1045    #[inline]
1046    #[must_use]
1047    pub fn starts_with(&self, base: impl AsRef<Path>) -> bool {
1048        self.0.starts_with(base)
1049    }
1050
1051    /// Determines whether `child` is a suffix of `self`.
1052    ///
1053    /// Only considers whole path components to match.
1054    ///
1055    /// # Examples
1056    ///
1057    /// ```
1058    /// use camino::Utf8Path;
1059    ///
1060    /// let path = Utf8Path::new("/etc/resolv.conf");
1061    ///
1062    /// assert!(path.ends_with("resolv.conf"));
1063    /// assert!(path.ends_with("etc/resolv.conf"));
1064    /// assert!(path.ends_with("/etc/resolv.conf"));
1065    ///
1066    /// assert!(!path.ends_with("/resolv.conf"));
1067    /// assert!(!path.ends_with("conf")); // use .extension() instead
1068    /// ```
1069    #[inline]
1070    #[must_use]
1071    pub fn ends_with(&self, base: impl AsRef<Path>) -> bool {
1072        self.0.ends_with(base)
1073    }
1074
1075    /// Extracts the stem (non-extension) portion of [`self.file_name`].
1076    ///
1077    /// [`self.file_name`]: Utf8Path::file_name
1078    ///
1079    /// The stem is:
1080    ///
1081    /// * [`None`], if there is no file name;
1082    /// * The entire file name if there is no embedded `.`;
1083    /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1084    /// * Otherwise, the portion of the file name before the final `.`
1085    ///
1086    /// # Examples
1087    ///
1088    /// ```
1089    /// use camino::Utf8Path;
1090    ///
1091    /// assert_eq!("foo", Utf8Path::new("foo.rs").file_stem().unwrap());
1092    /// assert_eq!("foo.tar", Utf8Path::new("foo.tar.gz").file_stem().unwrap());
1093    /// ```
1094    #[inline]
1095    #[must_use]
1096    pub fn file_stem(&self) -> Option<&str> {
1097        self.0.file_stem().map(|s| {
1098            // SAFETY: self is valid UTF-8, so file_stem is valid UTF-8 as well
1099            unsafe { str_assume_utf8(s) }
1100        })
1101    }
1102
1103    /// Extracts the prefix of [`self.file_name`].
1104    ///
1105    /// The prefix is:
1106    ///
1107    /// * [`None`], if there is no file name;
1108    /// * The entire file name if there is no embedded `.`;
1109    /// * The portion of the file name before the first non-beginning `.`;
1110    /// * The entire file name if the file name begins with `.` and has no other `.`s within;
1111    /// * The portion of the file name before the second `.` if the file name begins with `.`
1112    ///
1113    /// *Requires Rust 1.91 or newer.*
1114    ///
1115    /// [`self.file_name`]: Utf8Path::file_name
1116    ///
1117    /// # Examples
1118    ///
1119    /// ```
1120    /// use camino::Utf8Path;
1121    ///
1122    /// assert_eq!("foo", Utf8Path::new("foo.rs").file_prefix().unwrap());
1123    /// assert_eq!("foo", Utf8Path::new("foo.tar.gz").file_prefix().unwrap());
1124    /// ```
1125    #[cfg(path_add_extension)]
1126    #[expect(clippy::incompatible_msrv)]
1127    #[inline]
1128    #[must_use]
1129    pub fn file_prefix(&self) -> Option<&str> {
1130        self.0.file_prefix().map(|s| {
1131            // SAFETY: self is valid UTF-8, so file_prefix is valid UTF-8 as well
1132            unsafe { str_assume_utf8(s) }
1133        })
1134    }
1135
1136    /// Extracts the extension of [`self.file_name`], if possible.
1137    ///
1138    /// The extension is:
1139    ///
1140    /// * [`None`], if there is no file name;
1141    /// * [`None`], if there is no embedded `.`;
1142    /// * [`None`], if the file name begins with `.` and has no other `.`s within;
1143    /// * Otherwise, the portion of the file name after the final `.`
1144    ///
1145    /// [`self.file_name`]: Utf8Path::file_name
1146    ///
1147    /// # Examples
1148    ///
1149    /// ```
1150    /// use camino::Utf8Path;
1151    ///
1152    /// assert_eq!("rs", Utf8Path::new("foo.rs").extension().unwrap());
1153    /// assert_eq!("gz", Utf8Path::new("foo.tar.gz").extension().unwrap());
1154    /// ```
1155    #[inline]
1156    #[must_use]
1157    pub fn extension(&self) -> Option<&str> {
1158        self.0.extension().map(|s| {
1159            // SAFETY: self is valid UTF-8, so extension is valid UTF-8 as well
1160            unsafe { str_assume_utf8(s) }
1161        })
1162    }
1163
1164    /// Creates an owned [`Utf8PathBuf`] with `path` adjoined to `self`.
1165    ///
1166    /// See [`Utf8PathBuf::push`] for more details on what it means to adjoin a path.
1167    ///
1168    /// # Examples
1169    ///
1170    /// ```
1171    /// use camino::{Utf8Path, Utf8PathBuf};
1172    ///
1173    /// assert_eq!(Utf8Path::new("/etc").join("passwd"), Utf8PathBuf::from("/etc/passwd"));
1174    /// ```
1175    #[inline]
1176    #[must_use]
1177    pub fn join(&self, path: impl AsRef<Utf8Path>) -> Utf8PathBuf {
1178        Utf8PathBuf(self.0.join(&path.as_ref().0))
1179    }
1180
1181    /// Creates an owned [`PathBuf`] with `path` adjoined to `self`.
1182    ///
1183    /// See [`PathBuf::push`] for more details on what it means to adjoin a path.
1184    ///
1185    /// # Examples
1186    ///
1187    /// ```
1188    /// use camino::Utf8Path;
1189    /// use std::path::PathBuf;
1190    ///
1191    /// assert_eq!(Utf8Path::new("/etc").join_os("passwd"), PathBuf::from("/etc/passwd"));
1192    /// ```
1193    #[inline]
1194    #[must_use]
1195    pub fn join_os(&self, path: impl AsRef<Path>) -> PathBuf {
1196        self.0.join(path)
1197    }
1198
1199    /// Creates an owned [`Utf8PathBuf`] like `self` but with the given file name.
1200    ///
1201    /// See [`Utf8PathBuf::set_file_name`] for more details.
1202    ///
1203    /// # Examples
1204    ///
1205    /// ```
1206    /// use camino::{Utf8Path, Utf8PathBuf};
1207    ///
1208    /// let path = Utf8Path::new("/tmp/foo.txt");
1209    /// assert_eq!(path.with_file_name("bar.txt"), Utf8PathBuf::from("/tmp/bar.txt"));
1210    ///
1211    /// let path = Utf8Path::new("/tmp");
1212    /// assert_eq!(path.with_file_name("var"), Utf8PathBuf::from("/var"));
1213    /// ```
1214    #[inline]
1215    #[must_use]
1216    pub fn with_file_name(&self, file_name: impl AsRef<str>) -> Utf8PathBuf {
1217        Utf8PathBuf(self.0.with_file_name(file_name.as_ref()))
1218    }
1219
1220    /// Creates an owned [`Utf8PathBuf`] like `self` but with the given extension.
1221    ///
1222    /// See [`Utf8PathBuf::set_extension`] for more details.
1223    ///
1224    /// # Examples
1225    ///
1226    /// ```
1227    /// use camino::{Utf8Path, Utf8PathBuf};
1228    ///
1229    /// let path = Utf8Path::new("foo.rs");
1230    /// assert_eq!(path.with_extension("txt"), Utf8PathBuf::from("foo.txt"));
1231    ///
1232    /// let path = Utf8Path::new("foo.tar.gz");
1233    /// assert_eq!(path.with_extension(""), Utf8PathBuf::from("foo.tar"));
1234    /// assert_eq!(path.with_extension("xz"), Utf8PathBuf::from("foo.tar.xz"));
1235    /// assert_eq!(path.with_extension("").with_extension("txt"), Utf8PathBuf::from("foo.txt"));
1236    /// ```
1237    #[inline]
1238    pub fn with_extension(&self, extension: impl AsRef<str>) -> Utf8PathBuf {
1239        Utf8PathBuf(self.0.with_extension(extension.as_ref()))
1240    }
1241
1242    /// Creates an owned [`Utf8PathBuf`] like `self` but with the extension added.
1243    ///
1244    /// See [`Utf8PathBuf::add_extension`] for more details.
1245    ///
1246    /// *Requires Rust 1.91 or newer.*
1247    ///
1248    /// # Examples
1249    ///
1250    /// ```
1251    /// use camino::{Utf8Path, Utf8PathBuf};
1252    ///
1253    /// let path = Utf8Path::new("foo.rs");
1254    /// assert_eq!(path.with_added_extension("txt"), Utf8PathBuf::from("foo.rs.txt"));
1255    ///
1256    /// let path = Utf8Path::new("foo.tar.gz");
1257    /// assert_eq!(path.with_added_extension(""), Utf8PathBuf::from("foo.tar.gz"));
1258    /// assert_eq!(path.with_added_extension("xz"), Utf8PathBuf::from("foo.tar.gz.xz"));
1259    /// ```
1260    #[cfg(path_add_extension)]
1261    #[expect(clippy::incompatible_msrv)]
1262    #[inline]
1263    pub fn with_added_extension<S: AsRef<str>>(&self, extension: S) -> Utf8PathBuf {
1264        Utf8PathBuf(self.0.with_added_extension(extension.as_ref()))
1265    }
1266
1267    /// Produces an iterator over the [`Utf8Component`]s of the path.
1268    ///
1269    /// When parsing the path, there is a small amount of normalization:
1270    ///
1271    /// * Repeated separators are ignored, so `a/b` and `a//b` both have
1272    ///   `a` and `b` as components.
1273    ///
1274    /// * Occurrences of `.` are normalized away, except if they are at the
1275    ///   beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and
1276    ///   `a/b` all have `a` and `b` as components, but `./a/b` starts with
1277    ///   an additional [`CurDir`] component.
1278    ///
1279    /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent.
1280    ///
1281    /// Note that no other normalization takes place; in particular, `a/c`
1282    /// and `a/b/../c` are distinct, to account for the possibility that `b`
1283    /// is a symbolic link (so its parent isn't `a`).
1284    ///
1285    /// # Examples
1286    ///
1287    /// ```
1288    /// use camino::{Utf8Component, Utf8Path};
1289    ///
1290    /// let mut components = Utf8Path::new("/tmp/foo.txt").components();
1291    ///
1292    /// assert_eq!(components.next(), Some(Utf8Component::RootDir));
1293    /// assert_eq!(components.next(), Some(Utf8Component::Normal("tmp")));
1294    /// assert_eq!(components.next(), Some(Utf8Component::Normal("foo.txt")));
1295    /// assert_eq!(components.next(), None)
1296    /// ```
1297    ///
1298    /// [`CurDir`]: Utf8Component::CurDir
1299    #[inline]
1300    pub fn components(&self) -> Utf8Components<'_> {
1301        Utf8Components(self.0.components())
1302    }
1303
1304    /// Produces an iterator over the path's components viewed as [`str`]
1305    /// slices.
1306    ///
1307    /// For more information about the particulars of how the path is separated
1308    /// into components, see [`components`].
1309    ///
1310    /// [`components`]: Utf8Path::components
1311    ///
1312    /// # Examples
1313    ///
1314    /// ```
1315    /// use camino::Utf8Path;
1316    ///
1317    /// let mut it = Utf8Path::new("/tmp/foo.txt").iter();
1318    /// assert_eq!(it.next(), Some(std::path::MAIN_SEPARATOR.to_string().as_str()));
1319    /// assert_eq!(it.next(), Some("tmp"));
1320    /// assert_eq!(it.next(), Some("foo.txt"));
1321    /// assert_eq!(it.next(), None)
1322    /// ```
1323    #[inline]
1324    pub fn iter(&self) -> Iter<'_> {
1325        Iter {
1326            inner: self.components(),
1327        }
1328    }
1329
1330    /// Queries the file system to get information about a file, directory, etc.
1331    ///
1332    /// This function will traverse symbolic links to query information about the
1333    /// destination file.
1334    ///
1335    /// This is an alias to [`fs::metadata`].
1336    ///
1337    /// # Examples
1338    ///
1339    /// ```no_run
1340    /// use camino::Utf8Path;
1341    ///
1342    /// let path = Utf8Path::new("/Minas/tirith");
1343    /// let metadata = path.metadata().expect("metadata call failed");
1344    /// println!("{:?}", metadata.file_type());
1345    /// ```
1346    #[inline]
1347    pub fn metadata(&self) -> io::Result<fs::Metadata> {
1348        self.0.metadata()
1349    }
1350
1351    /// Queries the metadata about a file without following symlinks.
1352    ///
1353    /// This is an alias to [`fs::symlink_metadata`].
1354    ///
1355    /// # Examples
1356    ///
1357    /// ```no_run
1358    /// use camino::Utf8Path;
1359    ///
1360    /// let path = Utf8Path::new("/Minas/tirith");
1361    /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed");
1362    /// println!("{:?}", metadata.file_type());
1363    /// ```
1364    #[inline]
1365    pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
1366        self.0.symlink_metadata()
1367    }
1368
1369    /// Returns the canonical, absolute form of the path with all intermediate
1370    /// components normalized and symbolic links resolved.
1371    ///
1372    /// This returns a [`PathBuf`] because even if a symlink is valid Unicode, its target may not
1373    /// be. For a version that returns a [`Utf8PathBuf`], see
1374    /// [`canonicalize_utf8`](Self::canonicalize_utf8).
1375    ///
1376    /// This is an alias to [`fs::canonicalize`].
1377    ///
1378    /// # Examples
1379    ///
1380    /// ```no_run
1381    /// use camino::Utf8Path;
1382    /// use std::path::PathBuf;
1383    ///
1384    /// let path = Utf8Path::new("/foo/test/../test/bar.rs");
1385    /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs"));
1386    /// ```
1387    #[inline]
1388    pub fn canonicalize(&self) -> io::Result<PathBuf> {
1389        self.0.canonicalize()
1390    }
1391
1392    /// Returns the canonical, absolute form of the path with all intermediate
1393    /// components normalized and symbolic links resolved.
1394    ///
1395    /// This method attempts to convert the resulting [`PathBuf`] into a [`Utf8PathBuf`]. For a
1396    /// version that does not attempt to do this conversion, see
1397    /// [`canonicalize`](Self::canonicalize).
1398    ///
1399    /// # Errors
1400    ///
1401    /// The I/O operation may return an error: see the [`fs::canonicalize`]
1402    /// documentation for more.
1403    ///
1404    /// If the resulting path is not UTF-8, an [`io::Error`] is returned with the
1405    /// [`ErrorKind`](io::ErrorKind) set to [`InvalidData`](io::ErrorKind::InvalidData)
1406    /// and the payload set to a [`FromPathBufError`].
1407    ///
1408    /// # Examples
1409    ///
1410    /// ```no_run
1411    /// use camino::{Utf8Path, Utf8PathBuf};
1412    ///
1413    /// let path = Utf8Path::new("/foo/test/../test/bar.rs");
1414    /// assert_eq!(path.canonicalize_utf8().unwrap(), Utf8PathBuf::from("/foo/test/bar.rs"));
1415    /// ```
1416    pub fn canonicalize_utf8(&self) -> io::Result<Utf8PathBuf> {
1417        self.canonicalize()
1418            .and_then(|path| path.try_into().map_err(FromPathBufError::into_io_error))
1419    }
1420
1421    /// Reads a symbolic link, returning the file that the link points to.
1422    ///
1423    /// This returns a [`PathBuf`] because even if a symlink is valid Unicode, its target may not
1424    /// be. For a version that returns a [`Utf8PathBuf`], see
1425    /// [`read_link_utf8`](Self::read_link_utf8).
1426    ///
1427    /// This is an alias to [`fs::read_link`].
1428    ///
1429    /// # Examples
1430    ///
1431    /// ```no_run
1432    /// use camino::Utf8Path;
1433    ///
1434    /// let path = Utf8Path::new("/laputa/sky_castle.rs");
1435    /// let path_link = path.read_link().expect("read_link call failed");
1436    /// ```
1437    #[inline]
1438    pub fn read_link(&self) -> io::Result<PathBuf> {
1439        self.0.read_link()
1440    }
1441
1442    /// Reads a symbolic link, returning the file that the link points to.
1443    ///
1444    /// This method attempts to convert the resulting [`PathBuf`] into a [`Utf8PathBuf`]. For a
1445    /// version that does not attempt to do this conversion, see [`read_link`](Self::read_link).
1446    ///
1447    /// # Errors
1448    ///
1449    /// The I/O operation may return an error: see the [`fs::read_link`]
1450    /// documentation for more.
1451    ///
1452    /// If the resulting path is not UTF-8, an [`io::Error`] is returned with the
1453    /// [`ErrorKind`](io::ErrorKind) set to [`InvalidData`](io::ErrorKind::InvalidData)
1454    /// and the payload set to a [`FromPathBufError`].
1455    ///
1456    /// # Examples
1457    ///
1458    /// ```no_run
1459    /// use camino::Utf8Path;
1460    ///
1461    /// let path = Utf8Path::new("/laputa/sky_castle.rs");
1462    /// let path_link = path.read_link_utf8().expect("read_link call failed");
1463    /// ```
1464    pub fn read_link_utf8(&self) -> io::Result<Utf8PathBuf> {
1465        self.read_link()
1466            .and_then(|path| path.try_into().map_err(FromPathBufError::into_io_error))
1467    }
1468
1469    /// Returns an iterator over the entries within a directory.
1470    ///
1471    /// The iterator will yield instances of [`io::Result`]`<`[`fs::DirEntry`]`>`. New
1472    /// errors may be encountered after an iterator is initially constructed.
1473    ///
1474    /// This is an alias to [`fs::read_dir`].
1475    ///
1476    /// # Examples
1477    ///
1478    /// ```no_run
1479    /// use camino::Utf8Path;
1480    ///
1481    /// let path = Utf8Path::new("/laputa");
1482    /// for entry in path.read_dir().expect("read_dir call failed") {
1483    ///     if let Ok(entry) = entry {
1484    ///         println!("{:?}", entry.path());
1485    ///     }
1486    /// }
1487    /// ```
1488    #[inline]
1489    pub fn read_dir(&self) -> io::Result<fs::ReadDir> {
1490        self.0.read_dir()
1491    }
1492
1493    /// Returns an iterator over the entries within a directory.
1494    ///
1495    /// The iterator will yield instances of [`io::Result`]`<`[`Utf8DirEntry`]`>`. New
1496    /// errors may be encountered after an iterator is initially constructed.
1497    ///
1498    /// # Errors
1499    ///
1500    /// The I/O operation may return an error: see the [`fs::read_dir`]
1501    /// documentation for more.
1502    ///
1503    /// If a directory entry is not UTF-8, an [`io::Error`] is returned with the
1504    /// [`ErrorKind`](io::ErrorKind) set to [`InvalidData`](io::ErrorKind::InvalidData)
1505    /// and the payload set to a [`FromPathBufError`].
1506    ///
1507    /// # Examples
1508    ///
1509    /// ```no_run
1510    /// use camino::Utf8Path;
1511    ///
1512    /// let path = Utf8Path::new("/laputa");
1513    /// for entry in path.read_dir_utf8().expect("read_dir call failed") {
1514    ///     if let Ok(entry) = entry {
1515    ///         println!("{}", entry.path());
1516    ///     }
1517    /// }
1518    /// ```
1519    #[inline]
1520    pub fn read_dir_utf8(&self) -> io::Result<ReadDirUtf8> {
1521        self.0.read_dir().map(|inner| ReadDirUtf8 { inner })
1522    }
1523
1524    /// Returns `true` if the path points at an existing entity.
1525    ///
1526    /// Warning: this method may be error-prone, consider using [`try_exists()`] instead!
1527    /// It also has a risk of introducing time-of-check to time-of-use (TOCTOU) bugs.
1528    ///
1529    /// This function will traverse symbolic links to query information about the
1530    /// destination file. In case of broken symbolic links this will return `false`.
1531    ///
1532    /// If you cannot access the directory containing the file, e.g., because of a
1533    /// permission error, this will return `false`.
1534    ///
1535    /// # Examples
1536    ///
1537    /// ```no_run
1538    /// use camino::Utf8Path;
1539    /// assert!(!Utf8Path::new("does_not_exist.txt").exists());
1540    /// ```
1541    ///
1542    /// # See Also
1543    ///
1544    /// This is a convenience function that coerces errors to false. If you want to
1545    /// check errors, call [`fs::metadata`].
1546    ///
1547    /// [`try_exists()`]: Self::try_exists
1548    #[must_use]
1549    #[inline]
1550    pub fn exists(&self) -> bool {
1551        self.0.exists()
1552    }
1553
1554    /// Returns `Ok(true)` if the path points at an existing entity.
1555    ///
1556    /// This function will traverse symbolic links to query information about the
1557    /// destination file. In case of broken symbolic links this will return `Ok(false)`.
1558    ///
1559    /// As opposed to the [`exists()`] method, this one doesn't silently ignore errors
1560    /// unrelated to the path not existing. (E.g. it will return [`Err`] in case of permission
1561    /// denied on some of the parent directories.)
1562    ///
1563    /// Note that while this avoids some pitfalls of the `exists()` method, it still can not
1564    /// prevent time-of-check to time-of-use (TOCTOU) bugs. You should only use it in scenarios
1565    /// where those bugs are not an issue.
1566    ///
1567    /// # Examples
1568    ///
1569    /// ```no_run
1570    /// use camino::Utf8Path;
1571    /// assert!(
1572    ///     !Utf8Path::new("does_not_exist.txt")
1573    ///         .try_exists()
1574    ///         .expect("Can't check existence of file does_not_exist.txt")
1575    /// );
1576    /// assert!(Utf8Path::new("/root/secret_file.txt").try_exists().is_err());
1577    /// ```
1578    ///
1579    /// [`exists()`]: Self::exists
1580    #[inline]
1581    pub fn try_exists(&self) -> io::Result<bool> {
1582        match fs::metadata(self) {
1583            Ok(_) => Ok(true),
1584            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
1585            Err(error) => Err(error),
1586        }
1587    }
1588
1589    /// Returns `true` if the path exists on disk and is pointing at a regular file.
1590    ///
1591    /// This function will traverse symbolic links to query information about the
1592    /// destination file. In case of broken symbolic links this will return `false`.
1593    ///
1594    /// If you cannot access the directory containing the file, e.g., because of a
1595    /// permission error, this will return `false`.
1596    ///
1597    /// # Examples
1598    ///
1599    /// ```no_run
1600    /// use camino::Utf8Path;
1601    /// assert_eq!(Utf8Path::new("./is_a_directory/").is_file(), false);
1602    /// assert_eq!(Utf8Path::new("a_file.txt").is_file(), true);
1603    /// ```
1604    ///
1605    /// # See Also
1606    ///
1607    /// This is a convenience function that coerces errors to false. If you want to
1608    /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
1609    /// [`fs::Metadata::is_file`] if it was [`Ok`].
1610    ///
1611    /// When the goal is simply to read from (or write to) the source, the most
1612    /// reliable way to test the source can be read (or written to) is to open
1613    /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on
1614    /// a Unix-like system for example. See [`fs::File::open`] or
1615    /// [`fs::OpenOptions::open`] for more information.
1616    #[must_use]
1617    #[inline]
1618    pub fn is_file(&self) -> bool {
1619        self.0.is_file()
1620    }
1621
1622    /// Returns `true` if the path exists on disk and is pointing at a directory.
1623    ///
1624    /// This function will traverse symbolic links to query information about the
1625    /// destination file. In case of broken symbolic links this will return `false`.
1626    ///
1627    /// If you cannot access the directory containing the file, e.g., because of a
1628    /// permission error, this will return `false`.
1629    ///
1630    /// # Examples
1631    ///
1632    /// ```no_run
1633    /// use camino::Utf8Path;
1634    /// assert_eq!(Utf8Path::new("./is_a_directory/").is_dir(), true);
1635    /// assert_eq!(Utf8Path::new("a_file.txt").is_dir(), false);
1636    /// ```
1637    ///
1638    /// # See Also
1639    ///
1640    /// This is a convenience function that coerces errors to false. If you want to
1641    /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call
1642    /// [`fs::Metadata::is_dir`] if it was [`Ok`].
1643    #[must_use]
1644    #[inline]
1645    pub fn is_dir(&self) -> bool {
1646        self.0.is_dir()
1647    }
1648
1649    /// Returns `true` if the path exists on disk and is pointing at a symbolic link.
1650    ///
1651    /// This function will not traverse symbolic links.
1652    /// In case of a broken symbolic link this will also return true.
1653    ///
1654    /// If you cannot access the directory containing the file, e.g., because of a
1655    /// permission error, this will return false.
1656    ///
1657    /// # Examples
1658    ///
1659    #[cfg_attr(unix, doc = "```no_run")]
1660    #[cfg_attr(not(unix), doc = "```ignore")]
1661    /// use camino::Utf8Path;
1662    /// use std::os::unix::fs::symlink;
1663    ///
1664    /// let link_path = Utf8Path::new("link");
1665    /// symlink("/origin_does_not_exist/", link_path).unwrap();
1666    /// assert_eq!(link_path.is_symlink(), true);
1667    /// assert_eq!(link_path.exists(), false);
1668    /// ```
1669    ///
1670    /// # See Also
1671    ///
1672    /// This is a convenience function that coerces errors to false. If you want to
1673    /// check errors, call [`Utf8Path::symlink_metadata`] and handle its [`Result`]. Then call
1674    /// [`fs::Metadata::is_symlink`] if it was [`Ok`].
1675    #[must_use]
1676    pub fn is_symlink(&self) -> bool {
1677        self.symlink_metadata()
1678            .map(|m| m.file_type().is_symlink())
1679            .unwrap_or(false)
1680    }
1681
1682    /// Converts a [`Box<Utf8Path>`] into a [`Utf8PathBuf`] without copying or allocating.
1683    #[must_use = "`self` will be dropped if the result is not used"]
1684    #[inline]
1685    pub fn into_path_buf(self: Box<Utf8Path>) -> Utf8PathBuf {
1686        Utf8PathBuf(self.into_std_boxed_path().into_path_buf())
1687    }
1688
1689    // NOTE: `From<Box<Utf8Path>> for Box<Path>` is available, but doesn't render
1690    // due to a rustdoc bug similar to
1691    // https://github.com/rust-lang/rust/issues/82465. That's why we don't link it in the doc
1692    // comment below.
1693    /// Converts a [`Box<Utf8Path>`] into a [`Box<Path>`] without copying or allocating.
1694    ///
1695    /// This is equivalent to the `From<Box<Utf8Path>> for Box<Path>` implementation,
1696    /// but may aid in type inference.
1697    ///
1698    /// # Examples
1699    ///
1700    /// ```
1701    /// use camino::{Utf8Path, Utf8PathBuf};
1702    /// use std::path::Path;
1703    ///
1704    /// let utf8_path_buf = Utf8PathBuf::from("foo.txt");
1705    /// let boxed_utf8_path = utf8_path_buf.into_boxed_path();
1706    /// let boxed_std_path = boxed_utf8_path.into_std_boxed_path();
1707    /// assert_eq!(boxed_std_path.to_str(), Some("foo.txt"));
1708    ///
1709    /// // Convert back to a Box<Utf8Path>.
1710    /// let new_boxed_utf8_path = Utf8Path::from_boxed_path(boxed_std_path).unwrap();
1711    /// assert_eq!(&*new_boxed_utf8_path, Utf8Path::new("foo.txt"));
1712    /// ```
1713    #[must_use = "`self` will be dropped if the result is not used"]
1714    #[inline]
1715    pub fn into_std_boxed_path(self: Box<Utf8Path>) -> Box<Path> {
1716        let ptr = Box::into_raw(self) as *mut Path;
1717        // SAFETY:
1718        // * ptr was constructed by consuming self so it represents an owned path.
1719        // * Utf8Path is marked as #[repr(transparent)] so the conversion from a *mut Utf8Path to a
1720        //   *mut Path is valid.
1721        unsafe { Box::from_raw(ptr) }
1722    }
1723
1724    /// Creates a new [`Box<Utf8Path>`] from a [`Box<Path>`] containing valid UTF-8 characters,
1725    /// without copying or allocating.
1726    ///
1727    /// Errors with the original [`Box<Path>`] if it is not valid UTF-8.
1728    ///
1729    /// For a version that returns a type that implements [`std::error::Error`],
1730    /// see [`TryFrom<Box<Path>>`][tryfrom].
1731    ///
1732    /// [tryfrom]: #impl-TryFrom<Box<Path>>-for-Box<Utf8Path>
1733    ///
1734    /// # Examples
1735    ///
1736    /// ```
1737    /// use camino::Utf8Path;
1738    /// use std::ffi::OsStr;
1739    /// # #[cfg(unix)]
1740    /// use std::os::unix::ffi::OsStrExt;
1741    /// use std::path::Path;
1742    ///
1743    /// let unicode_path: Box<Path> = Path::new("/valid/unicode").into();
1744    /// Utf8Path::from_boxed_path(unicode_path).expect("valid Unicode path succeeded");
1745    ///
1746    /// // Paths on Unix can be non-UTF-8.
1747    /// # #[cfg(unix)]
1748    /// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
1749    /// # #[cfg(unix)]
1750    /// let non_unicode_path: Box<Path> = Path::new(non_unicode_str).into();
1751    /// # #[cfg(unix)]
1752    /// Utf8Path::from_boxed_path(non_unicode_path).expect_err("non-Unicode path failed");
1753    /// ```
1754    pub fn from_boxed_path(path: Box<Path>) -> Result<Box<Utf8Path>, Box<Path>> {
1755        if path.as_os_str().to_str().is_some() {
1756            let ptr = Box::into_raw(path) as *mut Utf8Path;
1757            // SAFETY:
1758            // * path is valid UTF-8 (just checked above)
1759            // * ptr was constructed by consuming path so it represents an owned path.
1760            // * Utf8Path is marked as #[repr(transparent)] so the conversion from a *mut Path to a
1761            //   *mut Utf8Path is valid.
1762            Ok(unsafe { Box::from_raw(ptr) })
1763        } else {
1764            Err(path)
1765        }
1766    }
1767
1768    // invariant: Path must be guaranteed to be utf-8 data
1769    #[inline]
1770    unsafe fn assume_utf8(path: &Path) -> &Utf8Path {
1771        // SAFETY: Utf8Path is marked as #[repr(transparent)] so the conversion from a
1772        // *const Path to a *const Utf8Path is valid.
1773        &*(path as *const Path as *const Utf8Path)
1774    }
1775
1776    #[cfg(path_buf_deref_mut)]
1777    #[inline]
1778    unsafe fn assume_utf8_mut(path: &mut Path) -> &mut Utf8Path {
1779        &mut *(path as *mut Path as *mut Utf8Path)
1780    }
1781}
1782
1783impl Clone for Box<Utf8Path> {
1784    fn clone(&self) -> Self {
1785        let boxed: Box<Path> = self.0.into();
1786        let ptr = Box::into_raw(boxed) as *mut Utf8Path;
1787        // SAFETY:
1788        // * self is valid UTF-8
1789        // * ptr was created by consuming a Box<Path> so it represents an rced pointer
1790        // * Utf8Path is marked as #[repr(transparent)] so the conversion from *mut Path to
1791        //   *mut Utf8Path is valid
1792        unsafe { Box::from_raw(ptr) }
1793    }
1794}
1795
1796impl fmt::Display for Utf8Path {
1797    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1798        fmt::Display::fmt(self.as_str(), f)
1799    }
1800}
1801
1802impl fmt::Debug for Utf8Path {
1803    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1804        fmt::Debug::fmt(self.as_str(), f)
1805    }
1806}
1807
1808/// An iterator over [`Utf8Path`] and its ancestors.
1809///
1810/// This `struct` is created by the [`ancestors`] method on [`Utf8Path`].
1811/// See its documentation for more.
1812///
1813/// # Examples
1814///
1815/// ```
1816/// use camino::Utf8Path;
1817///
1818/// let path = Utf8Path::new("/foo/bar");
1819///
1820/// for ancestor in path.ancestors() {
1821///     println!("{}", ancestor);
1822/// }
1823/// ```
1824///
1825/// [`ancestors`]: Utf8Path::ancestors
1826#[derive(Copy, Clone)]
1827#[must_use = "iterators are lazy and do nothing unless consumed"]
1828#[repr(transparent)]
1829pub struct Utf8Ancestors<'a>(Ancestors<'a>);
1830
1831impl fmt::Debug for Utf8Ancestors<'_> {
1832    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1833        fmt::Debug::fmt(&self.0, f)
1834    }
1835}
1836
1837impl<'a> Iterator for Utf8Ancestors<'a> {
1838    type Item = &'a Utf8Path;
1839
1840    #[inline]
1841    fn next(&mut self) -> Option<Self::Item> {
1842        self.0.next().map(|path| {
1843            // SAFETY: Utf8Ancestors was constructed from a Utf8Path, so it is guaranteed to
1844            // be valid UTF-8
1845            unsafe { Utf8Path::assume_utf8(path) }
1846        })
1847    }
1848}
1849
1850impl FusedIterator for Utf8Ancestors<'_> {}
1851
1852/// An iterator over the [`Utf8Component`]s of a [`Utf8Path`].
1853///
1854/// This `struct` is created by the [`components`] method on [`Utf8Path`].
1855/// See its documentation for more.
1856///
1857/// # Examples
1858///
1859/// ```
1860/// use camino::Utf8Path;
1861///
1862/// let path = Utf8Path::new("/tmp/foo/bar.txt");
1863///
1864/// for component in path.components() {
1865///     println!("{:?}", component);
1866/// }
1867/// ```
1868///
1869/// [`components`]: Utf8Path::components
1870#[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
1871#[must_use = "iterators are lazy and do nothing unless consumed"]
1872pub struct Utf8Components<'a>(Components<'a>);
1873
1874impl<'a> Utf8Components<'a> {
1875    /// Extracts a slice corresponding to the portion of the path remaining for iteration.
1876    ///
1877    /// # Examples
1878    ///
1879    /// ```
1880    /// use camino::Utf8Path;
1881    ///
1882    /// let mut components = Utf8Path::new("/tmp/foo/bar.txt").components();
1883    /// components.next();
1884    /// components.next();
1885    ///
1886    /// assert_eq!(Utf8Path::new("foo/bar.txt"), components.as_path());
1887    /// ```
1888    #[must_use]
1889    #[inline]
1890    pub fn as_path(&self) -> &'a Utf8Path {
1891        // SAFETY: Utf8Components was constructed from a Utf8Path, so it is guaranteed to be valid
1892        // UTF-8
1893        unsafe { Utf8Path::assume_utf8(self.0.as_path()) }
1894    }
1895}
1896
1897impl<'a> Iterator for Utf8Components<'a> {
1898    type Item = Utf8Component<'a>;
1899
1900    #[inline]
1901    fn next(&mut self) -> Option<Self::Item> {
1902        self.0.next().map(|component| {
1903            // SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be
1904            // valid UTF-8
1905            unsafe { Utf8Component::new(component) }
1906        })
1907    }
1908}
1909
1910impl FusedIterator for Utf8Components<'_> {}
1911
1912impl DoubleEndedIterator for Utf8Components<'_> {
1913    #[inline]
1914    fn next_back(&mut self) -> Option<Self::Item> {
1915        self.0.next_back().map(|component| {
1916            // SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be
1917            // valid UTF-8
1918            unsafe { Utf8Component::new(component) }
1919        })
1920    }
1921}
1922
1923impl fmt::Debug for Utf8Components<'_> {
1924    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1925        fmt::Debug::fmt(&self.0, f)
1926    }
1927}
1928
1929impl AsRef<Utf8Path> for Utf8Components<'_> {
1930    #[inline]
1931    fn as_ref(&self) -> &Utf8Path {
1932        self.as_path()
1933    }
1934}
1935
1936impl AsRef<Path> for Utf8Components<'_> {
1937    #[inline]
1938    fn as_ref(&self) -> &Path {
1939        self.as_path().as_ref()
1940    }
1941}
1942
1943impl AsRef<str> for Utf8Components<'_> {
1944    #[inline]
1945    fn as_ref(&self) -> &str {
1946        self.as_path().as_ref()
1947    }
1948}
1949
1950impl AsRef<OsStr> for Utf8Components<'_> {
1951    #[inline]
1952    fn as_ref(&self) -> &OsStr {
1953        self.as_path().as_os_str()
1954    }
1955}
1956
1957/// An iterator over the [`Utf8Component`]s of a [`Utf8Path`], as [`str`] slices.
1958///
1959/// This `struct` is created by the [`iter`] method on [`Utf8Path`].
1960/// See its documentation for more.
1961///
1962/// [`iter`]: Utf8Path::iter
1963#[derive(Clone)]
1964#[must_use = "iterators are lazy and do nothing unless consumed"]
1965pub struct Iter<'a> {
1966    inner: Utf8Components<'a>,
1967}
1968
1969impl fmt::Debug for Iter<'_> {
1970    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1971        struct DebugHelper<'a>(&'a Utf8Path);
1972
1973        impl fmt::Debug for DebugHelper<'_> {
1974            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1975                f.debug_list().entries(self.0.iter()).finish()
1976            }
1977        }
1978
1979        f.debug_tuple("Iter")
1980            .field(&DebugHelper(self.as_path()))
1981            .finish()
1982    }
1983}
1984
1985impl<'a> Iter<'a> {
1986    /// Extracts a slice corresponding to the portion of the path remaining for iteration.
1987    ///
1988    /// # Examples
1989    ///
1990    /// ```
1991    /// use camino::Utf8Path;
1992    ///
1993    /// let mut iter = Utf8Path::new("/tmp/foo/bar.txt").iter();
1994    /// iter.next();
1995    /// iter.next();
1996    ///
1997    /// assert_eq!(Utf8Path::new("foo/bar.txt"), iter.as_path());
1998    /// ```
1999    #[must_use]
2000    #[inline]
2001    pub fn as_path(&self) -> &'a Utf8Path {
2002        self.inner.as_path()
2003    }
2004}
2005
2006impl AsRef<Utf8Path> for Iter<'_> {
2007    #[inline]
2008    fn as_ref(&self) -> &Utf8Path {
2009        self.as_path()
2010    }
2011}
2012
2013impl AsRef<Path> for Iter<'_> {
2014    #[inline]
2015    fn as_ref(&self) -> &Path {
2016        self.as_path().as_ref()
2017    }
2018}
2019
2020impl AsRef<str> for Iter<'_> {
2021    #[inline]
2022    fn as_ref(&self) -> &str {
2023        self.as_path().as_ref()
2024    }
2025}
2026
2027impl AsRef<OsStr> for Iter<'_> {
2028    #[inline]
2029    fn as_ref(&self) -> &OsStr {
2030        self.as_path().as_os_str()
2031    }
2032}
2033
2034impl<'a> Iterator for Iter<'a> {
2035    type Item = &'a str;
2036
2037    #[inline]
2038    fn next(&mut self) -> Option<&'a str> {
2039        self.inner.next().map(|component| component.as_str())
2040    }
2041}
2042
2043impl<'a> DoubleEndedIterator for Iter<'a> {
2044    #[inline]
2045    fn next_back(&mut self) -> Option<&'a str> {
2046        self.inner.next_back().map(|component| component.as_str())
2047    }
2048}
2049
2050impl FusedIterator for Iter<'_> {}
2051
2052/// A single component of a path.
2053///
2054/// A [`Utf8Component`] roughly corresponds to a substring between path separators
2055/// (`/` or `\`).
2056///
2057/// This `enum` is created by iterating over [`Utf8Components`], which in turn is
2058/// created by the [`components`](Utf8Path::components) method on [`Utf8Path`].
2059///
2060/// # Examples
2061///
2062/// ```rust
2063/// use camino::{Utf8Component, Utf8Path};
2064///
2065/// let path = Utf8Path::new("/tmp/foo/bar.txt");
2066/// let components = path.components().collect::<Vec<_>>();
2067/// assert_eq!(&components, &[
2068///     Utf8Component::RootDir,
2069///     Utf8Component::Normal("tmp"),
2070///     Utf8Component::Normal("foo"),
2071///     Utf8Component::Normal("bar.txt"),
2072/// ]);
2073/// ```
2074#[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
2075pub enum Utf8Component<'a> {
2076    /// A Windows path prefix, e.g., `C:` or `\\server\share`.
2077    ///
2078    /// There is a large variety of prefix types, see [`Utf8Prefix`]'s documentation
2079    /// for more.
2080    ///
2081    /// Does not occur on Unix.
2082    Prefix(Utf8PrefixComponent<'a>),
2083
2084    /// The root directory component, appears after any prefix and before anything else.
2085    ///
2086    /// It represents a separator that designates that a path starts from root.
2087    RootDir,
2088
2089    /// A reference to the current directory, i.e., `.`.
2090    CurDir,
2091
2092    /// A reference to the parent directory, i.e., `..`.
2093    ParentDir,
2094
2095    /// A normal component, e.g., `a` and `b` in `a/b`.
2096    ///
2097    /// This variant is the most common one, it represents references to files
2098    /// or directories.
2099    Normal(&'a str),
2100}
2101
2102impl<'a> Utf8Component<'a> {
2103    unsafe fn new(component: Component<'a>) -> Utf8Component<'a> {
2104        match component {
2105            Component::Prefix(prefix) => Utf8Component::Prefix(Utf8PrefixComponent(prefix)),
2106            Component::RootDir => Utf8Component::RootDir,
2107            Component::CurDir => Utf8Component::CurDir,
2108            Component::ParentDir => Utf8Component::ParentDir,
2109            Component::Normal(s) => Utf8Component::Normal(str_assume_utf8(s)),
2110        }
2111    }
2112
2113    /// Extracts the underlying [`str`] slice.
2114    ///
2115    /// # Examples
2116    ///
2117    /// ```
2118    /// use camino::Utf8Path;
2119    ///
2120    /// let path = Utf8Path::new("./tmp/foo/bar.txt");
2121    /// let components: Vec<_> = path.components().map(|comp| comp.as_str()).collect();
2122    /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
2123    /// ```
2124    #[must_use]
2125    #[inline]
2126    pub fn as_str(&self) -> &'a str {
2127        // SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be
2128        // valid UTF-8
2129        unsafe { str_assume_utf8(self.as_os_str()) }
2130    }
2131
2132    /// Extracts the underlying [`OsStr`] slice.
2133    ///
2134    /// # Examples
2135    ///
2136    /// ```
2137    /// use camino::Utf8Path;
2138    ///
2139    /// let path = Utf8Path::new("./tmp/foo/bar.txt");
2140    /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
2141    /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
2142    /// ```
2143    #[must_use]
2144    pub fn as_os_str(&self) -> &'a OsStr {
2145        match *self {
2146            Utf8Component::Prefix(prefix) => prefix.as_os_str(),
2147            Utf8Component::RootDir => Component::RootDir.as_os_str(),
2148            Utf8Component::CurDir => Component::CurDir.as_os_str(),
2149            Utf8Component::ParentDir => Component::ParentDir.as_os_str(),
2150            Utf8Component::Normal(s) => OsStr::new(s),
2151        }
2152    }
2153}
2154
2155impl fmt::Debug for Utf8Component<'_> {
2156    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2157        fmt::Debug::fmt(self.as_os_str(), f)
2158    }
2159}
2160
2161impl fmt::Display for Utf8Component<'_> {
2162    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2163        fmt::Display::fmt(self.as_str(), f)
2164    }
2165}
2166
2167impl AsRef<Utf8Path> for Utf8Component<'_> {
2168    #[inline]
2169    fn as_ref(&self) -> &Utf8Path {
2170        self.as_str().as_ref()
2171    }
2172}
2173
2174impl AsRef<Path> for Utf8Component<'_> {
2175    #[inline]
2176    fn as_ref(&self) -> &Path {
2177        self.as_os_str().as_ref()
2178    }
2179}
2180
2181impl AsRef<str> for Utf8Component<'_> {
2182    #[inline]
2183    fn as_ref(&self) -> &str {
2184        self.as_str()
2185    }
2186}
2187
2188impl AsRef<OsStr> for Utf8Component<'_> {
2189    #[inline]
2190    fn as_ref(&self) -> &OsStr {
2191        self.as_os_str()
2192    }
2193}
2194
2195/// Windows path prefixes, e.g., `C:` or `\\server\share`.
2196///
2197/// Windows uses a variety of path prefix styles, including references to drive
2198/// volumes (like `C:`), network shared folders (like `\\server\share`), and
2199/// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
2200/// `\\?\`), in which case `/` is *not* treated as a separator and essentially
2201/// no normalization is performed.
2202///
2203/// # Examples
2204///
2205/// ```
2206/// use camino::{Utf8Component, Utf8Path, Utf8Prefix};
2207/// use camino::Utf8Prefix::*;
2208///
2209/// fn get_path_prefix(s: &str) -> Utf8Prefix {
2210///     let path = Utf8Path::new(s);
2211///     match path.components().next().unwrap() {
2212///         Utf8Component::Prefix(prefix_component) => prefix_component.kind(),
2213///         _ => panic!(),
2214///     }
2215/// }
2216///
2217/// # if cfg!(windows) {
2218/// assert_eq!(Verbatim("pictures"), get_path_prefix(r"\\?\pictures\kittens"));
2219/// assert_eq!(VerbatimUNC("server", "share"), get_path_prefix(r"\\?\UNC\server\share"));
2220/// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\C:\"));
2221/// assert_eq!(DeviceNS("BrainInterface"), get_path_prefix(r"\\.\BrainInterface"));
2222/// assert_eq!(UNC("server", "share"), get_path_prefix(r"\\server\share"));
2223/// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
2224/// # }
2225/// ```
2226#[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
2227pub enum Utf8Prefix<'a> {
2228    /// Verbatim prefix, e.g., `\\?\cat_pics`.
2229    ///
2230    /// Verbatim prefixes consist of `\\?\` immediately followed by the given
2231    /// component.
2232    Verbatim(&'a str),
2233
2234    /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
2235    /// e.g., `\\?\UNC\server\share`.
2236    ///
2237    /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
2238    /// server's hostname and a share name.
2239    VerbatimUNC(&'a str, &'a str),
2240
2241    /// Verbatim disk prefix, e.g., `\\?\C:`.
2242    ///
2243    /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
2244    /// drive letter and `:`.
2245    VerbatimDisk(u8),
2246
2247    /// Device namespace prefix, e.g., `\\.\COM42`.
2248    ///
2249    /// Device namespace prefixes consist of `\\.\` immediately followed by the
2250    /// device name.
2251    DeviceNS(&'a str),
2252
2253    /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
2254    /// `\\server\share`.
2255    ///
2256    /// UNC prefixes consist of the server's hostname and a share name.
2257    UNC(&'a str, &'a str),
2258
2259    /// Prefix `C:` for the given disk drive.
2260    Disk(u8),
2261}
2262
2263impl Utf8Prefix<'_> {
2264    /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
2265    ///
2266    /// # Examples
2267    ///
2268    /// ```
2269    /// use camino::Utf8Prefix::*;
2270    ///
2271    /// assert!(Verbatim("pictures").is_verbatim());
2272    /// assert!(VerbatimUNC("server", "share").is_verbatim());
2273    /// assert!(VerbatimDisk(b'C').is_verbatim());
2274    /// assert!(!DeviceNS("BrainInterface").is_verbatim());
2275    /// assert!(!UNC("server", "share").is_verbatim());
2276    /// assert!(!Disk(b'C').is_verbatim());
2277    /// ```
2278    #[must_use]
2279    pub fn is_verbatim(&self) -> bool {
2280        use Utf8Prefix::*;
2281        matches!(self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
2282    }
2283}
2284
2285/// A structure wrapping a Windows path prefix as well as its unparsed string
2286/// representation.
2287///
2288/// In addition to the parsed [`Utf8Prefix`] information returned by [`kind`],
2289/// [`Utf8PrefixComponent`] also holds the raw and unparsed [`str`] slice,
2290/// returned by [`as_str`].
2291///
2292/// Instances of this `struct` can be obtained by matching against the
2293/// [`Prefix` variant] on [`Utf8Component`].
2294///
2295/// Does not occur on Unix.
2296///
2297/// # Examples
2298///
2299/// ```
2300/// # if cfg!(windows) {
2301/// use camino::{Utf8Component, Utf8Path, Utf8Prefix};
2302/// use std::ffi::OsStr;
2303///
2304/// let path = Utf8Path::new(r"C:\you\later\");
2305/// match path.components().next().unwrap() {
2306///     Utf8Component::Prefix(prefix_component) => {
2307///         assert_eq!(Utf8Prefix::Disk(b'C'), prefix_component.kind());
2308///         assert_eq!("C:", prefix_component.as_str());
2309///     }
2310///     _ => unreachable!(),
2311/// }
2312/// # }
2313/// ```
2314///
2315/// [`as_str`]: Utf8PrefixComponent::as_str
2316/// [`kind`]: Utf8PrefixComponent::kind
2317/// [`Prefix` variant]: Utf8Component::Prefix
2318#[repr(transparent)]
2319#[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
2320pub struct Utf8PrefixComponent<'a>(PrefixComponent<'a>);
2321
2322impl<'a> Utf8PrefixComponent<'a> {
2323    /// Returns the parsed prefix data.
2324    ///
2325    /// See [`Utf8Prefix`]'s documentation for more information on the different
2326    /// kinds of prefixes.
2327    #[must_use]
2328    pub fn kind(&self) -> Utf8Prefix<'a> {
2329        // SAFETY for all the below unsafe blocks: the path self was originally constructed from was
2330        // UTF-8 so any parts of it are valid UTF-8
2331        match self.0.kind() {
2332            Prefix::Verbatim(prefix) => Utf8Prefix::Verbatim(unsafe { str_assume_utf8(prefix) }),
2333            Prefix::VerbatimUNC(server, share) => {
2334                let server = unsafe { str_assume_utf8(server) };
2335                let share = unsafe { str_assume_utf8(share) };
2336                Utf8Prefix::VerbatimUNC(server, share)
2337            }
2338            Prefix::VerbatimDisk(drive) => Utf8Prefix::VerbatimDisk(drive),
2339            Prefix::DeviceNS(prefix) => Utf8Prefix::DeviceNS(unsafe { str_assume_utf8(prefix) }),
2340            Prefix::UNC(server, share) => {
2341                let server = unsafe { str_assume_utf8(server) };
2342                let share = unsafe { str_assume_utf8(share) };
2343                Utf8Prefix::UNC(server, share)
2344            }
2345            Prefix::Disk(drive) => Utf8Prefix::Disk(drive),
2346        }
2347    }
2348
2349    /// Returns the [`str`] slice for this prefix.
2350    #[must_use]
2351    #[inline]
2352    pub fn as_str(&self) -> &'a str {
2353        // SAFETY: Utf8PrefixComponent was constructed from a Utf8Path, so it is guaranteed to be
2354        // valid UTF-8
2355        unsafe { str_assume_utf8(self.as_os_str()) }
2356    }
2357
2358    /// Returns the raw [`OsStr`] slice for this prefix.
2359    #[must_use]
2360    #[inline]
2361    pub fn as_os_str(&self) -> &'a OsStr {
2362        self.0.as_os_str()
2363    }
2364}
2365
2366impl fmt::Debug for Utf8PrefixComponent<'_> {
2367    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2368        fmt::Debug::fmt(&self.0, f)
2369    }
2370}
2371
2372impl fmt::Display for Utf8PrefixComponent<'_> {
2373    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2374        fmt::Display::fmt(self.as_str(), f)
2375    }
2376}
2377
2378// ---
2379// read_dir_utf8
2380// ---
2381
2382/// Iterator over the entries in a directory.
2383///
2384/// This iterator is returned from [`Utf8Path::read_dir_utf8`] and will yield instances of
2385/// <code>[io::Result]<[Utf8DirEntry]></code>. Through a [`Utf8DirEntry`] information like the entry's path
2386/// and possibly other metadata can be learned.
2387///
2388/// The order in which this iterator returns entries is platform and filesystem
2389/// dependent.
2390///
2391/// # Errors
2392///
2393/// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
2394/// IO error during iteration.
2395///
2396/// If a directory entry is not UTF-8, an [`io::Error`] is returned with the
2397/// [`ErrorKind`](io::ErrorKind) set to [`InvalidData`][io::ErrorKind::InvalidData]
2398/// and the payload set to a [`FromPathBufError`].
2399#[derive(Debug)]
2400pub struct ReadDirUtf8 {
2401    inner: fs::ReadDir,
2402}
2403
2404impl Iterator for ReadDirUtf8 {
2405    type Item = io::Result<Utf8DirEntry>;
2406
2407    fn next(&mut self) -> Option<io::Result<Utf8DirEntry>> {
2408        self.inner
2409            .next()
2410            .map(|entry| entry.and_then(Utf8DirEntry::new))
2411    }
2412}
2413
2414/// Entries returned by the [`ReadDirUtf8`] iterator.
2415///
2416/// An instance of [`Utf8DirEntry`] represents an entry inside of a directory on the filesystem. Each
2417/// entry can be inspected via methods to learn about the full path or possibly other metadata.
2418#[derive(Debug)]
2419pub struct Utf8DirEntry {
2420    inner: fs::DirEntry,
2421    path: Utf8PathBuf,
2422}
2423
2424impl Utf8DirEntry {
2425    fn new(inner: fs::DirEntry) -> io::Result<Self> {
2426        let path = inner
2427            .path()
2428            .try_into()
2429            .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
2430        Ok(Self { inner, path })
2431    }
2432
2433    /// Returns the full path to the file that this entry represents.
2434    ///
2435    /// The full path is created by joining the original path to `read_dir`
2436    /// with the filename of this entry.
2437    ///
2438    /// # Examples
2439    ///
2440    /// ```no_run
2441    /// use camino::Utf8Path;
2442    ///
2443    /// fn main() -> std::io::Result<()> {
2444    ///     for entry in Utf8Path::new(".").read_dir_utf8()? {
2445    ///         let dir = entry?;
2446    ///         println!("{}", dir.path());
2447    ///     }
2448    ///     Ok(())
2449    /// }
2450    /// ```
2451    ///
2452    /// This prints output like:
2453    ///
2454    /// ```text
2455    /// ./whatever.txt
2456    /// ./foo.html
2457    /// ./hello_world.rs
2458    /// ```
2459    ///
2460    /// The exact text, of course, depends on what files you have in `.`.
2461    #[inline]
2462    pub fn path(&self) -> &Utf8Path {
2463        &self.path
2464    }
2465
2466    /// Returns the metadata for the file that this entry points at.
2467    ///
2468    /// This function will not traverse symlinks if this entry points at a symlink. To traverse
2469    /// symlinks use [`Utf8Path::metadata`] or [`fs::File::metadata`].
2470    ///
2471    /// # Platform-specific behavior
2472    ///
2473    /// On Windows this function is cheap to call (no extra system calls
2474    /// needed), but on Unix platforms this function is the equivalent of
2475    /// calling `symlink_metadata` on the path.
2476    ///
2477    /// # Examples
2478    ///
2479    /// ```
2480    /// use camino::Utf8Path;
2481    ///
2482    /// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
2483    ///     for entry in entries {
2484    ///         if let Ok(entry) = entry {
2485    ///             // Here, `entry` is a `Utf8DirEntry`.
2486    ///             if let Ok(metadata) = entry.metadata() {
2487    ///                 // Now let's show our entry's permissions!
2488    ///                 println!("{}: {:?}", entry.path(), metadata.permissions());
2489    ///             } else {
2490    ///                 println!("Couldn't get metadata for {}", entry.path());
2491    ///             }
2492    ///         }
2493    ///     }
2494    /// }
2495    /// ```
2496    #[inline]
2497    pub fn metadata(&self) -> io::Result<Metadata> {
2498        self.inner.metadata()
2499    }
2500
2501    /// Returns the file type for the file that this entry points at.
2502    ///
2503    /// This function will not traverse symlinks if this entry points at a
2504    /// symlink.
2505    ///
2506    /// # Platform-specific behavior
2507    ///
2508    /// On Windows and most Unix platforms this function is free (no extra
2509    /// system calls needed), but some Unix platforms may require the equivalent
2510    /// call to `symlink_metadata` to learn about the target file type.
2511    ///
2512    /// # Examples
2513    ///
2514    /// ```
2515    /// use camino::Utf8Path;
2516    ///
2517    /// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
2518    ///     for entry in entries {
2519    ///         if let Ok(entry) = entry {
2520    ///             // Here, `entry` is a `DirEntry`.
2521    ///             if let Ok(file_type) = entry.file_type() {
2522    ///                 // Now let's show our entry's file type!
2523    ///                 println!("{}: {:?}", entry.path(), file_type);
2524    ///             } else {
2525    ///                 println!("Couldn't get file type for {}", entry.path());
2526    ///             }
2527    ///         }
2528    ///     }
2529    /// }
2530    /// ```
2531    #[inline]
2532    pub fn file_type(&self) -> io::Result<fs::FileType> {
2533        self.inner.file_type()
2534    }
2535
2536    /// Returns the bare file name of this directory entry without any other
2537    /// leading path component.
2538    ///
2539    /// # Examples
2540    ///
2541    /// ```
2542    /// use camino::Utf8Path;
2543    ///
2544    /// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
2545    ///     for entry in entries {
2546    ///         if let Ok(entry) = entry {
2547    ///             // Here, `entry` is a `DirEntry`.
2548    ///             println!("{}", entry.file_name());
2549    ///         }
2550    ///     }
2551    /// }
2552    /// ```
2553    pub fn file_name(&self) -> &str {
2554        self.path
2555            .file_name()
2556            .expect("path created through DirEntry must have a filename")
2557    }
2558
2559    /// Returns the original [`fs::DirEntry`] within this [`Utf8DirEntry`].
2560    #[inline]
2561    pub fn into_inner(self) -> fs::DirEntry {
2562        self.inner
2563    }
2564
2565    /// Returns the full path to the file that this entry represents.
2566    ///
2567    /// This is analogous to [`path`], but moves ownership of the path.
2568    ///
2569    /// [`path`]: struct.Utf8DirEntry.html#method.path
2570    #[inline]
2571    #[must_use = "`self` will be dropped if the result is not used"]
2572    pub fn into_path(self) -> Utf8PathBuf {
2573        self.path
2574    }
2575}
2576
2577impl From<String> for Utf8PathBuf {
2578    fn from(string: String) -> Utf8PathBuf {
2579        Utf8PathBuf(string.into())
2580    }
2581}
2582
2583impl FromStr for Utf8PathBuf {
2584    type Err = Infallible;
2585
2586    fn from_str(s: &str) -> Result<Self, Self::Err> {
2587        Ok(Utf8PathBuf(s.into()))
2588    }
2589}
2590
2591// ---
2592// From impls: borrowed -> borrowed
2593// ---
2594
2595impl<'a> From<&'a str> for &'a Utf8Path {
2596    fn from(s: &'a str) -> &'a Utf8Path {
2597        Utf8Path::new(s)
2598    }
2599}
2600
2601// ---
2602// From impls: borrowed -> owned
2603// ---
2604
2605impl<T: ?Sized + AsRef<str>> From<&T> for Utf8PathBuf {
2606    fn from(s: &T) -> Utf8PathBuf {
2607        Utf8PathBuf::from(s.as_ref().to_owned())
2608    }
2609}
2610
2611impl<T: ?Sized + AsRef<str>> From<&T> for Box<Utf8Path> {
2612    fn from(s: &T) -> Box<Utf8Path> {
2613        Utf8PathBuf::from(s).into_boxed_path()
2614    }
2615}
2616
2617impl From<&'_ Utf8Path> for Arc<Utf8Path> {
2618    fn from(path: &Utf8Path) -> Arc<Utf8Path> {
2619        let arc: Arc<Path> = Arc::from(AsRef::<Path>::as_ref(path));
2620        let ptr = Arc::into_raw(arc) as *const Utf8Path;
2621        // SAFETY:
2622        // * path is valid UTF-8
2623        // * ptr was created by consuming an Arc<Path> so it represents an arced pointer
2624        // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
2625        //   *const Utf8Path is valid
2626        unsafe { Arc::from_raw(ptr) }
2627    }
2628}
2629
2630impl From<&'_ Utf8Path> for Rc<Utf8Path> {
2631    fn from(path: &Utf8Path) -> Rc<Utf8Path> {
2632        let rc: Rc<Path> = Rc::from(AsRef::<Path>::as_ref(path));
2633        let ptr = Rc::into_raw(rc) as *const Utf8Path;
2634        // SAFETY:
2635        // * path is valid UTF-8
2636        // * ptr was created by consuming an Rc<Path> so it represents an rced pointer
2637        // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
2638        //   *const Utf8Path is valid
2639        unsafe { Rc::from_raw(ptr) }
2640    }
2641}
2642
2643impl<'a> From<&'a Utf8Path> for Cow<'a, Utf8Path> {
2644    fn from(path: &'a Utf8Path) -> Cow<'a, Utf8Path> {
2645        Cow::Borrowed(path)
2646    }
2647}
2648
2649impl From<&'_ Utf8Path> for Box<Path> {
2650    fn from(path: &Utf8Path) -> Box<Path> {
2651        AsRef::<Path>::as_ref(path).into()
2652    }
2653}
2654
2655impl From<&'_ Utf8Path> for Arc<Path> {
2656    fn from(path: &Utf8Path) -> Arc<Path> {
2657        AsRef::<Path>::as_ref(path).into()
2658    }
2659}
2660
2661impl From<&'_ Utf8Path> for Rc<Path> {
2662    fn from(path: &Utf8Path) -> Rc<Path> {
2663        AsRef::<Path>::as_ref(path).into()
2664    }
2665}
2666
2667impl<'a> From<&'a Utf8Path> for Cow<'a, Path> {
2668    fn from(path: &'a Utf8Path) -> Cow<'a, Path> {
2669        Cow::Borrowed(path.as_ref())
2670    }
2671}
2672
2673// ---
2674// From impls: owned -> owned
2675// ---
2676
2677impl From<Box<Utf8Path>> for Utf8PathBuf {
2678    fn from(path: Box<Utf8Path>) -> Utf8PathBuf {
2679        path.into_path_buf()
2680    }
2681}
2682
2683impl From<Box<Utf8Path>> for Box<Path> {
2684    fn from(path: Box<Utf8Path>) -> Box<Path> {
2685        path.into_std_boxed_path()
2686    }
2687}
2688
2689impl From<Utf8PathBuf> for Box<Utf8Path> {
2690    fn from(path: Utf8PathBuf) -> Box<Utf8Path> {
2691        path.into_boxed_path()
2692    }
2693}
2694
2695impl<'a> From<Cow<'a, Utf8Path>> for Utf8PathBuf {
2696    fn from(path: Cow<'a, Utf8Path>) -> Utf8PathBuf {
2697        path.into_owned()
2698    }
2699}
2700
2701impl From<Utf8PathBuf> for String {
2702    fn from(path: Utf8PathBuf) -> String {
2703        path.into_string()
2704    }
2705}
2706
2707impl From<Utf8PathBuf> for OsString {
2708    fn from(path: Utf8PathBuf) -> OsString {
2709        path.into_os_string()
2710    }
2711}
2712
2713impl<'a> From<Utf8PathBuf> for Cow<'a, Utf8Path> {
2714    fn from(path: Utf8PathBuf) -> Cow<'a, Utf8Path> {
2715        Cow::Owned(path)
2716    }
2717}
2718
2719impl From<Utf8PathBuf> for Arc<Utf8Path> {
2720    fn from(path: Utf8PathBuf) -> Arc<Utf8Path> {
2721        let arc: Arc<Path> = Arc::from(path.0);
2722        let ptr = Arc::into_raw(arc) as *const Utf8Path;
2723        // SAFETY:
2724        // * path is valid UTF-8
2725        // * ptr was created by consuming an Arc<Path> so it represents an arced pointer
2726        // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
2727        //   *const Utf8Path is valid
2728        unsafe { Arc::from_raw(ptr) }
2729    }
2730}
2731
2732impl From<Utf8PathBuf> for Rc<Utf8Path> {
2733    fn from(path: Utf8PathBuf) -> Rc<Utf8Path> {
2734        let rc: Rc<Path> = Rc::from(path.0);
2735        let ptr = Rc::into_raw(rc) as *const Utf8Path;
2736        // SAFETY:
2737        // * path is valid UTF-8
2738        // * ptr was created by consuming an Rc<Path> so it represents an rced pointer
2739        // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
2740        //   *const Utf8Path is valid
2741        unsafe { Rc::from_raw(ptr) }
2742    }
2743}
2744
2745impl From<Utf8PathBuf> for PathBuf {
2746    fn from(path: Utf8PathBuf) -> PathBuf {
2747        path.0
2748    }
2749}
2750
2751impl From<Utf8PathBuf> for Box<Path> {
2752    fn from(path: Utf8PathBuf) -> Box<Path> {
2753        PathBuf::from(path).into_boxed_path()
2754    }
2755}
2756
2757impl From<Utf8PathBuf> for Arc<Path> {
2758    fn from(path: Utf8PathBuf) -> Arc<Path> {
2759        PathBuf::from(path).into()
2760    }
2761}
2762
2763impl From<Utf8PathBuf> for Rc<Path> {
2764    fn from(path: Utf8PathBuf) -> Rc<Path> {
2765        PathBuf::from(path).into()
2766    }
2767}
2768
2769impl<'a> From<Utf8PathBuf> for Cow<'a, Path> {
2770    fn from(path: Utf8PathBuf) -> Cow<'a, Path> {
2771        PathBuf::from(path).into()
2772    }
2773}
2774
2775// ---
2776// TryFrom impls
2777// ---
2778
2779impl TryFrom<PathBuf> for Utf8PathBuf {
2780    type Error = FromPathBufError;
2781
2782    fn try_from(path: PathBuf) -> Result<Utf8PathBuf, Self::Error> {
2783        Utf8PathBuf::from_path_buf(path).map_err(|path| FromPathBufError {
2784            path,
2785            error: FromPathError(()),
2786        })
2787    }
2788}
2789
2790impl TryFrom<OsString> for Utf8PathBuf {
2791    type Error = FromOsStringError;
2792
2793    fn try_from(os_string: OsString) -> Result<Utf8PathBuf, Self::Error> {
2794        Utf8PathBuf::from_os_string(os_string).map_err(|os_string| FromOsStringError {
2795            os_string,
2796            error: FromOsStrError(()),
2797        })
2798    }
2799}
2800
2801/// Converts a [`Path`] to a [`Utf8Path`].
2802///
2803/// Returns [`FromPathError`] if the path is not valid UTF-8.
2804///
2805/// # Examples
2806///
2807/// ```
2808/// use camino::Utf8Path;
2809/// use std::convert::TryFrom;
2810/// use std::ffi::OsStr;
2811/// # #[cfg(unix)]
2812/// use std::os::unix::ffi::OsStrExt;
2813/// use std::path::Path;
2814///
2815/// let unicode_path = Path::new("/valid/unicode");
2816/// <&Utf8Path>::try_from(unicode_path).expect("valid Unicode path succeeded");
2817///
2818/// // Paths on Unix can be non-UTF-8.
2819/// # #[cfg(unix)]
2820/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
2821/// # #[cfg(unix)]
2822/// let non_unicode_path = Path::new(non_unicode_str);
2823/// # #[cfg(unix)]
2824/// assert!(<&Utf8Path>::try_from(non_unicode_path).is_err(), "non-Unicode path failed");
2825/// ```
2826impl<'a> TryFrom<&'a Path> for &'a Utf8Path {
2827    type Error = FromPathError;
2828
2829    fn try_from(path: &'a Path) -> Result<&'a Utf8Path, Self::Error> {
2830        Utf8Path::from_path(path).ok_or(FromPathError(()))
2831    }
2832}
2833
2834/// Converts an [`OsStr`] to a [`Utf8Path`].
2835///
2836/// Returns the original [`OsStr`] if it is not valid UTF-8.
2837///
2838/// # Examples
2839///
2840/// ```
2841/// use camino::Utf8Path;
2842/// use std::convert::TryFrom;
2843/// use std::ffi::OsStr;
2844/// # #[cfg(unix)]
2845/// use std::os::unix::ffi::OsStrExt;
2846/// use std::path::Path;
2847///
2848/// # #[cfg(unix)]
2849/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
2850/// # #[cfg(unix)]
2851/// assert!(<&Utf8Path>::try_from(non_unicode_str).is_err(), "non-Unicode string path failed");
2852/// ```
2853impl<'a> TryFrom<&'a OsStr> for &'a Utf8Path {
2854    type Error = FromOsStrError;
2855
2856    fn try_from(os_str: &'a OsStr) -> Result<&'a Utf8Path, Self::Error> {
2857        Utf8Path::from_os_str(os_str).ok_or(FromOsStrError(()))
2858    }
2859}
2860
2861/// Converts a [`Box<Path>`] to a [`Box<Utf8Path>`].
2862///
2863/// Returns [`FromBoxedPathError`] if the path is not valid UTF-8.
2864///
2865/// # Examples
2866///
2867/// ```
2868/// use camino::Utf8Path;
2869/// use std::convert::TryFrom;
2870/// use std::ffi::OsStr;
2871/// # #[cfg(unix)]
2872/// use std::os::unix::ffi::OsStrExt;
2873/// use std::path::Path;
2874///
2875/// let unicode_path: Box<Path> = Path::new("/valid/unicode").into();
2876/// <Box<Utf8Path>>::try_from(unicode_path).expect("valid Unicode path succeeded");
2877///
2878/// // Paths on Unix can be non-UTF-8.
2879/// # #[cfg(unix)]
2880/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
2881/// # #[cfg(unix)]
2882/// let non_unicode_path: Box<Path> = Path::new(non_unicode_str).into();
2883/// # #[cfg(unix)]
2884/// assert!(<Box<Utf8Path>>::try_from(non_unicode_path).is_err(), "non-Unicode path failed");
2885/// ```
2886impl TryFrom<Box<Path>> for Box<Utf8Path> {
2887    type Error = FromBoxedPathError;
2888
2889    fn try_from(path: Box<Path>) -> Result<Box<Utf8Path>, Self::Error> {
2890        Utf8Path::from_boxed_path(path).map_err(|path| FromBoxedPathError {
2891            path,
2892            error: FromPathError(()),
2893        })
2894    }
2895}
2896
2897/// A possible error value while converting a [`PathBuf`] to a [`Utf8PathBuf`].
2898///
2899/// Produced by the [`TryFrom<&PathBuf>`][tryfrom] implementation for [`Utf8PathBuf`].
2900///
2901/// [tryfrom]: Utf8PathBuf#impl-TryFrom<PathBuf>-for-Utf8PathBuf
2902///
2903/// # Examples
2904///
2905/// ```
2906/// use camino::{Utf8PathBuf, FromPathBufError};
2907/// use std::convert::{TryFrom, TryInto};
2908/// use std::ffi::OsStr;
2909/// # #[cfg(unix)]
2910/// use std::os::unix::ffi::OsStrExt;
2911/// use std::path::PathBuf;
2912///
2913/// let unicode_path = PathBuf::from("/valid/unicode");
2914/// let utf8_path_buf: Utf8PathBuf = unicode_path.try_into().expect("valid Unicode path succeeded");
2915///
2916/// // Paths on Unix can be non-UTF-8.
2917/// # #[cfg(unix)]
2918/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
2919/// # #[cfg(unix)]
2920/// let non_unicode_path = PathBuf::from(non_unicode_str);
2921/// # #[cfg(unix)]
2922/// let err: FromPathBufError = Utf8PathBuf::try_from(non_unicode_path.clone())
2923///     .expect_err("non-Unicode path failed");
2924/// # #[cfg(unix)]
2925/// assert_eq!(err.as_path(), &non_unicode_path);
2926/// # #[cfg(unix)]
2927/// assert_eq!(err.into_path_buf(), non_unicode_path);
2928/// ```
2929#[derive(Clone, Debug, Eq, PartialEq)]
2930pub struct FromPathBufError {
2931    path: PathBuf,
2932    error: FromPathError,
2933}
2934
2935impl FromPathBufError {
2936    /// Returns the [`Path`] slice that was attempted to be converted to [`Utf8PathBuf`].
2937    #[inline]
2938    pub fn as_path(&self) -> &Path {
2939        &self.path
2940    }
2941
2942    /// Returns the [`PathBuf`] that was attempted to be converted to [`Utf8PathBuf`].
2943    #[inline]
2944    pub fn into_path_buf(self) -> PathBuf {
2945        self.path
2946    }
2947
2948    /// Fetches a [`FromPathError`] for more about the conversion failure.
2949    ///
2950    /// At the moment this struct does not contain any additional information, but is provided for
2951    /// completeness.
2952    #[inline]
2953    pub fn from_path_error(&self) -> FromPathError {
2954        self.error
2955    }
2956
2957    /// Converts self into a [`std::io::Error`] with kind
2958    /// [`InvalidData`](io::ErrorKind::InvalidData).
2959    ///
2960    /// Many users of [`FromPathBufError`] will want to convert it into an [`io::Error`]. This is a
2961    /// convenience method to do that.
2962    pub fn into_io_error(self) -> io::Error {
2963        // NOTE: we don't currently implement `From<FromPathBufError> for io::Error` because we want
2964        // to ensure the user actually desires that conversion.
2965        io::Error::new(io::ErrorKind::InvalidData, self)
2966    }
2967}
2968
2969impl fmt::Display for FromPathBufError {
2970    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2971        write!(f, "PathBuf contains invalid UTF-8: {}", self.path.display())
2972    }
2973}
2974
2975impl error::Error for FromPathBufError {
2976    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
2977        Some(&self.error)
2978    }
2979}
2980
2981/// A possible error value while converting a [`Path`] to a [`Utf8Path`].
2982///
2983/// Produced by the [`TryFrom<&Path>`][tryfrom] implementation for [`&Utf8Path`](Utf8Path).
2984///
2985/// [tryfrom]: Utf8Path#impl-TryFrom<%26Path>-for-%26Utf8Path
2986///
2987///
2988/// # Examples
2989///
2990/// ```
2991/// use camino::{Utf8Path, FromPathError};
2992/// use std::convert::{TryFrom, TryInto};
2993/// use std::ffi::OsStr;
2994/// # #[cfg(unix)]
2995/// use std::os::unix::ffi::OsStrExt;
2996/// use std::path::Path;
2997///
2998/// let unicode_path = Path::new("/valid/unicode");
2999/// let utf8_path: &Utf8Path = unicode_path.try_into().expect("valid Unicode path succeeded");
3000///
3001/// // Paths on Unix can be non-UTF-8.
3002/// # #[cfg(unix)]
3003/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
3004/// # #[cfg(unix)]
3005/// let non_unicode_path = Path::new(non_unicode_str);
3006/// # #[cfg(unix)]
3007/// let err: FromPathError = <&Utf8Path>::try_from(non_unicode_path)
3008///     .expect_err("non-Unicode path failed");
3009/// ```
3010#[derive(Copy, Clone, Debug, Eq, PartialEq)]
3011pub struct FromPathError(());
3012
3013impl FromPathError {
3014    /// Converts self into a [`std::io::Error`] with kind
3015    /// [`InvalidData`](io::ErrorKind::InvalidData).
3016    ///
3017    /// Many users of [`FromPathError`] will want to convert it into an [`io::Error`]. This is a
3018    /// convenience method to do that.
3019    pub fn into_io_error(self) -> io::Error {
3020        // NOTE: we don't currently implement `From<FromPathError> for io::Error` because we want
3021        // to ensure the user actually desires that conversion.
3022        io::Error::new(io::ErrorKind::InvalidData, self)
3023    }
3024}
3025
3026impl fmt::Display for FromPathError {
3027    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3028        write!(f, "Path contains invalid UTF-8")
3029    }
3030}
3031
3032impl error::Error for FromPathError {
3033    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
3034        None
3035    }
3036}
3037
3038/// A possible error value while converting a [`OsString`] to a [`Utf8PathBuf`].
3039///
3040/// Produced by the `TryFrom<OsString>` implementation for [`Utf8PathBuf`].
3041///
3042/// # Examples
3043///
3044/// ```
3045/// # #[cfg(osstring_from_str)] {
3046/// use camino::{Utf8PathBuf, FromOsStringError};
3047/// use std::convert::{TryFrom, TryInto};
3048/// use std::ffi::OsStr;
3049/// use std::str::FromStr;
3050/// use std::ffi::OsString;
3051/// # #[cfg(unix)]
3052/// use std::os::unix::ffi::OsStrExt;
3053///
3054/// let unicode_string = OsString::from_str("/valid/unicode").unwrap();
3055/// let utf8_path_buf: Utf8PathBuf = unicode_string.try_into()
3056///     .expect("valid Unicode path succeeded");
3057///
3058/// // Paths on Unix can be non-UTF-8.
3059/// # #[cfg(unix)]
3060/// let non_unicode_string = OsStr::from_bytes(b"\xFF\xFF\xFF").to_owned();
3061/// # #[cfg(unix)]
3062/// let err: FromOsStringError = Utf8PathBuf::try_from(non_unicode_string.clone())
3063///     .expect_err("non-Unicode path failed");
3064/// # #[cfg(unix)]
3065/// assert_eq!(err.as_os_str(), &non_unicode_string);
3066/// # #[cfg(unix)]
3067/// assert_eq!(err.into_os_string(), non_unicode_string);
3068/// # }
3069/// ```
3070#[derive(Clone, Debug, Eq, PartialEq)]
3071pub struct FromOsStringError {
3072    os_string: OsString,
3073    error: FromOsStrError,
3074}
3075
3076impl FromOsStringError {
3077    /// Returns the [`OsStr`] slice that was attempted to be converted to [`Utf8PathBuf`].
3078    #[inline]
3079    pub fn as_os_str(&self) -> &OsStr {
3080        &self.os_string
3081    }
3082
3083    /// Returns the [`OsString`] that was attempted to be converted to [`Utf8PathBuf`].
3084    #[inline]
3085    pub fn into_os_string(self) -> OsString {
3086        self.os_string
3087    }
3088
3089    /// Fetches a [`FromOsStrError`] for more about the conversion failure.
3090    ///
3091    /// At the moment this struct does not contain any additional information, but is provided for
3092    /// completeness.
3093    #[inline]
3094    pub fn from_os_str_error(&self) -> FromOsStrError {
3095        self.error
3096    }
3097
3098    /// Converts self into a [`std::io::Error`] with kind
3099    /// [`InvalidData`](io::ErrorKind::InvalidData).
3100    ///
3101    /// Many users of [`FromOsStringError`] will want to convert it into an [`io::Error`].
3102    /// This is a convenience method to do that.
3103    pub fn into_io_error(self) -> io::Error {
3104        // NOTE: we don't currently implement `From<FromOsStringError> for io::Error`
3105        // because we want to ensure the user actually desires that conversion.
3106        io::Error::new(io::ErrorKind::InvalidData, self)
3107    }
3108}
3109
3110impl fmt::Display for FromOsStringError {
3111    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3112        write!(
3113            f,
3114            "OsString contains invalid UTF-8: {}",
3115            // self.os_string.display() // this item is stable since `1.87.0`
3116            PathBuf::from(&self.os_string).display() // msrv hack
3117        )
3118    }
3119}
3120
3121impl error::Error for FromOsStringError {
3122    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
3123        Some(&self.error)
3124    }
3125}
3126
3127/// A possible error value while converting a [`OsStr`] to a [`Utf8Path`].
3128///
3129/// Produced by the `TryFrom<&OsStr>` implementation for [`&Utf8Path`](Utf8Path).
3130///
3131///
3132/// # Examples
3133///
3134/// ```
3135/// use camino::{Utf8Path, FromOsStrError};
3136/// use std::convert::{TryFrom, TryInto};
3137/// use std::ffi::OsStr;
3138/// # #[cfg(unix)]
3139/// use std::os::unix::ffi::OsStrExt;
3140///
3141/// let unicode_str = OsStr::new("/valid/unicode");
3142/// let utf8_path: &Utf8Path = unicode_str.try_into().expect("valid Unicode path succeeded");
3143///
3144/// // Paths on Unix can be non-UTF-8.
3145/// # #[cfg(unix)]
3146/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
3147/// # #[cfg(unix)]
3148/// let err: FromOsStrError = <&Utf8Path>::try_from(non_unicode_str)
3149///     .expect_err("non-Unicode path failed");
3150/// ```
3151#[derive(Copy, Clone, Debug, Eq, PartialEq)]
3152pub struct FromOsStrError(());
3153
3154impl FromOsStrError {
3155    /// Converts self into a [`std::io::Error`] with kind
3156    /// [`InvalidData`](io::ErrorKind::InvalidData).
3157    ///
3158    /// Many users of [`FromOsStrError`] will want to convert it into an [`io::Error`]. This is a
3159    /// convenience method to do that.
3160    pub fn into_io_error(self) -> io::Error {
3161        // NOTE: we don't currently implement `From<FromOsStrError> for io::Error`
3162        // because we want to ensure the user actually desires that conversion.
3163        io::Error::new(io::ErrorKind::InvalidData, self)
3164    }
3165}
3166
3167impl fmt::Display for FromOsStrError {
3168    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3169        write!(f, "OsStr contains invalid UTF-8")
3170    }
3171}
3172
3173impl error::Error for FromOsStrError {
3174    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
3175        None
3176    }
3177}
3178
3179/// A possible error value while converting a [`Box<Path>`] to a [`Box<Utf8Path>`].
3180///
3181/// Produced by the [`TryFrom<Box<Path>>`][tryfrom] implementation for [`Box<Utf8Path>`].
3182///
3183/// [tryfrom]: Utf8Path#impl-TryFrom<Box<Path>>-for-Box<Utf8Path>
3184///
3185/// # Examples
3186///
3187/// ```
3188/// use camino::{Utf8Path, FromBoxedPathError};
3189/// use std::convert::{TryFrom, TryInto};
3190/// use std::ffi::OsStr;
3191/// # #[cfg(unix)]
3192/// use std::os::unix::ffi::OsStrExt;
3193/// use std::path::Path;
3194///
3195/// let unicode_path: Box<Path> = Path::new("/valid/unicode").into();
3196/// let utf8_path: Box<Utf8Path> = unicode_path.try_into().expect("valid Unicode path succeeded");
3197///
3198/// // Paths on Unix can be non-UTF-8.
3199/// # #[cfg(unix)]
3200/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
3201/// # #[cfg(unix)]
3202/// let non_unicode_path: Box<Path> = Path::new(non_unicode_str).into();
3203/// # #[cfg(unix)]
3204/// let err: FromBoxedPathError = <Box<Utf8Path>>::try_from(non_unicode_path.clone())
3205///     .expect_err("non-Unicode path failed");
3206/// # #[cfg(unix)]
3207/// assert_eq!(err.as_path(), &*non_unicode_path);
3208/// # #[cfg(unix)]
3209/// assert_eq!(err.into_boxed_path(), non_unicode_path);
3210/// ```
3211#[derive(Clone, Debug, Eq, PartialEq)]
3212pub struct FromBoxedPathError {
3213    path: Box<Path>,
3214    error: FromPathError,
3215}
3216
3217impl FromBoxedPathError {
3218    /// Returns the [`Path`] slice that was attempted to be converted to [`Box<Utf8Path>`].
3219    #[inline]
3220    pub fn as_path(&self) -> &Path {
3221        &self.path
3222    }
3223
3224    /// Returns the [`Box<Path>`] that was attempted to be converted to [`Box<Utf8Path>`].
3225    #[inline]
3226    pub fn into_boxed_path(self) -> Box<Path> {
3227        self.path
3228    }
3229
3230    /// Fetches a [`FromPathError`] for more about the conversion failure.
3231    ///
3232    /// At the moment this struct does not contain any additional information, but is provided for
3233    /// completeness.
3234    #[inline]
3235    pub fn from_path_error(&self) -> FromPathError {
3236        self.error
3237    }
3238
3239    /// Converts self into a [`std::io::Error`] with kind
3240    /// [`InvalidData`](io::ErrorKind::InvalidData).
3241    ///
3242    /// Many users of [`FromBoxedPathError`] will want to convert it into an [`io::Error`]. This is a
3243    /// convenience method to do that.
3244    pub fn into_io_error(self) -> io::Error {
3245        // NOTE: we don't currently implement `From<FromBoxedPathError> for io::Error` because we
3246        // want to ensure the user actually desires that conversion.
3247        io::Error::new(io::ErrorKind::InvalidData, self)
3248    }
3249}
3250
3251impl fmt::Display for FromBoxedPathError {
3252    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3253        write!(
3254            f,
3255            "Box<Path> contains invalid UTF-8: {}",
3256            self.path.display()
3257        )
3258    }
3259}
3260
3261impl error::Error for FromBoxedPathError {
3262    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
3263        Some(&self.error)
3264    }
3265}
3266
3267// ---
3268// AsRef impls
3269// ---
3270
3271impl AsRef<Utf8Path> for Utf8Path {
3272    #[inline]
3273    fn as_ref(&self) -> &Utf8Path {
3274        self
3275    }
3276}
3277
3278impl AsRef<Utf8Path> for Utf8PathBuf {
3279    #[inline]
3280    fn as_ref(&self) -> &Utf8Path {
3281        self.as_path()
3282    }
3283}
3284
3285impl AsRef<Utf8Path> for str {
3286    #[inline]
3287    fn as_ref(&self) -> &Utf8Path {
3288        Utf8Path::new(self)
3289    }
3290}
3291
3292impl AsRef<Utf8Path> for String {
3293    #[inline]
3294    fn as_ref(&self) -> &Utf8Path {
3295        Utf8Path::new(self)
3296    }
3297}
3298
3299impl AsRef<Path> for Utf8Path {
3300    #[inline]
3301    fn as_ref(&self) -> &Path {
3302        &self.0
3303    }
3304}
3305
3306impl AsRef<Path> for Utf8PathBuf {
3307    #[inline]
3308    fn as_ref(&self) -> &Path {
3309        &self.0
3310    }
3311}
3312
3313impl AsRef<str> for Utf8Path {
3314    #[inline]
3315    fn as_ref(&self) -> &str {
3316        self.as_str()
3317    }
3318}
3319
3320impl AsRef<str> for Utf8PathBuf {
3321    #[inline]
3322    fn as_ref(&self) -> &str {
3323        self.as_str()
3324    }
3325}
3326
3327impl AsRef<OsStr> for Utf8Path {
3328    #[inline]
3329    fn as_ref(&self) -> &OsStr {
3330        self.as_os_str()
3331    }
3332}
3333
3334impl AsRef<OsStr> for Utf8PathBuf {
3335    #[inline]
3336    fn as_ref(&self) -> &OsStr {
3337        self.as_os_str()
3338    }
3339}
3340
3341// ---
3342// Borrow and ToOwned
3343// ---
3344
3345impl Borrow<Utf8Path> for Utf8PathBuf {
3346    #[inline]
3347    fn borrow(&self) -> &Utf8Path {
3348        self.as_path()
3349    }
3350}
3351
3352impl ToOwned for Utf8Path {
3353    type Owned = Utf8PathBuf;
3354
3355    #[inline]
3356    fn to_owned(&self) -> Utf8PathBuf {
3357        self.to_path_buf()
3358    }
3359}
3360
3361impl<P: AsRef<Utf8Path>> std::iter::FromIterator<P> for Utf8PathBuf {
3362    fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> Utf8PathBuf {
3363        let mut buf = Utf8PathBuf::new();
3364        buf.extend(iter);
3365        buf
3366    }
3367}
3368
3369// ---
3370// [Partial]Eq, [Partial]Ord, Hash
3371// ---
3372
3373impl PartialEq for Utf8PathBuf {
3374    #[inline]
3375    fn eq(&self, other: &Utf8PathBuf) -> bool {
3376        self.components() == other.components()
3377    }
3378}
3379
3380impl Eq for Utf8PathBuf {}
3381
3382impl Hash for Utf8PathBuf {
3383    #[inline]
3384    fn hash<H: Hasher>(&self, state: &mut H) {
3385        self.as_path().hash(state)
3386    }
3387}
3388
3389impl PartialOrd for Utf8PathBuf {
3390    #[inline]
3391    fn partial_cmp(&self, other: &Utf8PathBuf) -> Option<Ordering> {
3392        Some(self.cmp(other))
3393    }
3394}
3395
3396impl Ord for Utf8PathBuf {
3397    fn cmp(&self, other: &Utf8PathBuf) -> Ordering {
3398        self.components().cmp(other.components())
3399    }
3400}
3401
3402impl PartialEq for Utf8Path {
3403    #[inline]
3404    fn eq(&self, other: &Utf8Path) -> bool {
3405        self.components().eq(other.components())
3406    }
3407}
3408
3409impl Eq for Utf8Path {}
3410
3411impl Hash for Utf8Path {
3412    #[inline]
3413    fn hash<H: Hasher>(&self, state: &mut H) {
3414        self.0.hash(state)
3415    }
3416}
3417
3418impl PartialOrd for Utf8Path {
3419    #[inline]
3420    fn partial_cmp(&self, other: &Utf8Path) -> Option<Ordering> {
3421        Some(self.cmp(other))
3422    }
3423}
3424
3425impl Ord for Utf8Path {
3426    fn cmp(&self, other: &Utf8Path) -> Ordering {
3427        self.components().cmp(other.components())
3428    }
3429}
3430
3431impl<'a> IntoIterator for &'a Utf8PathBuf {
3432    type Item = &'a str;
3433    type IntoIter = Iter<'a>;
3434    #[inline]
3435    fn into_iter(self) -> Iter<'a> {
3436        self.iter()
3437    }
3438}
3439
3440impl<'a> IntoIterator for &'a Utf8Path {
3441    type Item = &'a str;
3442    type IntoIter = Iter<'a>;
3443    #[inline]
3444    fn into_iter(self) -> Iter<'a> {
3445        self.iter()
3446    }
3447}
3448
3449macro_rules! impl_cmp {
3450    ($lhs:ty, $rhs: ty) => {
3451        #[allow(clippy::extra_unused_lifetimes)]
3452        impl<'a, 'b> PartialEq<$rhs> for $lhs {
3453            #[inline]
3454            fn eq(&self, other: &$rhs) -> bool {
3455                <Utf8Path as PartialEq>::eq(self, other)
3456            }
3457        }
3458
3459        #[allow(clippy::extra_unused_lifetimes)]
3460        impl<'a, 'b> PartialEq<$lhs> for $rhs {
3461            #[inline]
3462            fn eq(&self, other: &$lhs) -> bool {
3463                <Utf8Path as PartialEq>::eq(self, other)
3464            }
3465        }
3466
3467        #[allow(clippy::extra_unused_lifetimes)]
3468        impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3469            #[inline]
3470            fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> {
3471                <Utf8Path as PartialOrd>::partial_cmp(self, other)
3472            }
3473        }
3474
3475        #[allow(clippy::extra_unused_lifetimes)]
3476        impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3477            #[inline]
3478            fn partial_cmp(&self, other: &$lhs) -> Option<Ordering> {
3479                <Utf8Path as PartialOrd>::partial_cmp(self, other)
3480            }
3481        }
3482    };
3483}
3484
3485impl_cmp!(Utf8PathBuf, Utf8Path);
3486impl_cmp!(Utf8PathBuf, &'a Utf8Path);
3487impl_cmp!(Cow<'a, Utf8Path>, Utf8Path);
3488impl_cmp!(Cow<'a, Utf8Path>, &'b Utf8Path);
3489impl_cmp!(Cow<'a, Utf8Path>, Utf8PathBuf);
3490
3491macro_rules! impl_cmp_std_path {
3492    ($lhs:ty, $rhs: ty) => {
3493        #[allow(clippy::extra_unused_lifetimes)]
3494        impl<'a, 'b> PartialEq<$rhs> for $lhs {
3495            #[inline]
3496            fn eq(&self, other: &$rhs) -> bool {
3497                <Path as PartialEq>::eq(self.as_ref(), other)
3498            }
3499        }
3500
3501        #[allow(clippy::extra_unused_lifetimes)]
3502        impl<'a, 'b> PartialEq<$lhs> for $rhs {
3503            #[inline]
3504            fn eq(&self, other: &$lhs) -> bool {
3505                <Path as PartialEq>::eq(self, other.as_ref())
3506            }
3507        }
3508
3509        #[allow(clippy::extra_unused_lifetimes)]
3510        impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3511            #[inline]
3512            fn partial_cmp(&self, other: &$rhs) -> Option<std::cmp::Ordering> {
3513                <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
3514            }
3515        }
3516
3517        #[allow(clippy::extra_unused_lifetimes)]
3518        impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3519            #[inline]
3520            fn partial_cmp(&self, other: &$lhs) -> Option<std::cmp::Ordering> {
3521                <Path as PartialOrd>::partial_cmp(self, other.as_ref())
3522            }
3523        }
3524    };
3525}
3526
3527impl_cmp_std_path!(Utf8PathBuf, Path);
3528impl_cmp_std_path!(Utf8PathBuf, &'a Path);
3529impl_cmp_std_path!(Utf8PathBuf, Cow<'a, Path>);
3530impl_cmp_std_path!(Utf8PathBuf, PathBuf);
3531impl_cmp_std_path!(Utf8Path, Path);
3532impl_cmp_std_path!(Utf8Path, &'a Path);
3533impl_cmp_std_path!(Utf8Path, Cow<'a, Path>);
3534impl_cmp_std_path!(Utf8Path, PathBuf);
3535impl_cmp_std_path!(&'a Utf8Path, Path);
3536impl_cmp_std_path!(&'a Utf8Path, Cow<'b, Path>);
3537impl_cmp_std_path!(&'a Utf8Path, PathBuf);
3538// NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117)
3539
3540macro_rules! impl_cmp_str {
3541    ($lhs:ty, $rhs: ty) => {
3542        #[allow(clippy::extra_unused_lifetimes)]
3543        impl<'a, 'b> PartialEq<$rhs> for $lhs {
3544            #[inline]
3545            fn eq(&self, other: &$rhs) -> bool {
3546                <Utf8Path as PartialEq>::eq(self, Utf8Path::new(other))
3547            }
3548        }
3549
3550        #[allow(clippy::extra_unused_lifetimes)]
3551        impl<'a, 'b> PartialEq<$lhs> for $rhs {
3552            #[inline]
3553            fn eq(&self, other: &$lhs) -> bool {
3554                <Utf8Path as PartialEq>::eq(Utf8Path::new(self), other)
3555            }
3556        }
3557
3558        #[allow(clippy::extra_unused_lifetimes)]
3559        impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3560            #[inline]
3561            fn partial_cmp(&self, other: &$rhs) -> Option<std::cmp::Ordering> {
3562                <Utf8Path as PartialOrd>::partial_cmp(self, Utf8Path::new(other))
3563            }
3564        }
3565
3566        #[allow(clippy::extra_unused_lifetimes)]
3567        impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3568            #[inline]
3569            fn partial_cmp(&self, other: &$lhs) -> Option<std::cmp::Ordering> {
3570                <Utf8Path as PartialOrd>::partial_cmp(Utf8Path::new(self), other)
3571            }
3572        }
3573    };
3574}
3575
3576impl_cmp_str!(Utf8PathBuf, str);
3577impl_cmp_str!(Utf8PathBuf, &'a str);
3578impl_cmp_str!(Utf8PathBuf, Cow<'a, str>);
3579impl_cmp_str!(Utf8PathBuf, String);
3580impl_cmp_str!(Utf8Path, str);
3581impl_cmp_str!(Utf8Path, &'a str);
3582impl_cmp_str!(Utf8Path, Cow<'a, str>);
3583impl_cmp_str!(Utf8Path, String);
3584impl_cmp_str!(&'a Utf8Path, str);
3585impl_cmp_str!(&'a Utf8Path, Cow<'b, str>);
3586impl_cmp_str!(&'a Utf8Path, String);
3587// NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117)
3588
3589macro_rules! impl_cmp_os_str {
3590    ($lhs:ty, $rhs: ty) => {
3591        #[allow(clippy::extra_unused_lifetimes)]
3592        impl<'a, 'b> PartialEq<$rhs> for $lhs {
3593            #[inline]
3594            fn eq(&self, other: &$rhs) -> bool {
3595                <Path as PartialEq>::eq(self.as_ref(), other.as_ref())
3596            }
3597        }
3598
3599        #[allow(clippy::extra_unused_lifetimes)]
3600        impl<'a, 'b> PartialEq<$lhs> for $rhs {
3601            #[inline]
3602            fn eq(&self, other: &$lhs) -> bool {
3603                <Path as PartialEq>::eq(self.as_ref(), other.as_ref())
3604            }
3605        }
3606
3607        #[allow(clippy::extra_unused_lifetimes)]
3608        impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3609            #[inline]
3610            fn partial_cmp(&self, other: &$rhs) -> Option<std::cmp::Ordering> {
3611                <Path as PartialOrd>::partial_cmp(self.as_ref(), other.as_ref())
3612            }
3613        }
3614
3615        #[allow(clippy::extra_unused_lifetimes)]
3616        impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3617            #[inline]
3618            fn partial_cmp(&self, other: &$lhs) -> Option<std::cmp::Ordering> {
3619                <Path as PartialOrd>::partial_cmp(self.as_ref(), other.as_ref())
3620            }
3621        }
3622    };
3623}
3624
3625impl_cmp_os_str!(Utf8PathBuf, OsStr);
3626impl_cmp_os_str!(Utf8PathBuf, &'a OsStr);
3627impl_cmp_os_str!(Utf8PathBuf, Cow<'a, OsStr>);
3628impl_cmp_os_str!(Utf8PathBuf, OsString);
3629impl_cmp_os_str!(Utf8Path, OsStr);
3630impl_cmp_os_str!(Utf8Path, &'a OsStr);
3631impl_cmp_os_str!(Utf8Path, Cow<'a, OsStr>);
3632impl_cmp_os_str!(Utf8Path, OsString);
3633impl_cmp_os_str!(&'a Utf8Path, OsStr);
3634impl_cmp_os_str!(&'a Utf8Path, Cow<'b, OsStr>);
3635impl_cmp_os_str!(&'a Utf8Path, OsString);
3636// NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117)
3637
3638/// Makes the path absolute without accessing the filesystem, converting it to a [`Utf8PathBuf`].
3639///
3640/// If the path is relative, the current directory is used as the base directory. All intermediate
3641/// components will be resolved according to platform-specific rules, but unlike
3642/// [`canonicalize`][Utf8Path::canonicalize] or [`canonicalize_utf8`](Utf8Path::canonicalize_utf8),
3643/// this does not resolve symlinks and may succeed even if the path does not exist.
3644///
3645/// *Requires Rust 1.79 or newer.*
3646///
3647/// # Errors
3648///
3649/// Errors if:
3650///
3651/// * The path is empty.
3652/// * The [current directory][std::env::current_dir] cannot be determined.
3653/// * The path is not valid UTF-8.
3654///
3655/// # Examples
3656///
3657/// ## POSIX paths
3658///
3659/// ```
3660/// # #[cfg(unix)]
3661/// fn main() -> std::io::Result<()> {
3662///     use camino::Utf8Path;
3663///
3664///     // Relative to absolute
3665///     let absolute = camino::absolute_utf8("foo/./bar")?;
3666///     assert!(absolute.ends_with("foo/bar"));
3667///
3668///     // Absolute to absolute
3669///     let absolute = camino::absolute_utf8("/foo//test/.././bar.rs")?;
3670///     assert_eq!(absolute, Utf8Path::new("/foo/test/../bar.rs"));
3671///     Ok(())
3672/// }
3673/// # #[cfg(not(unix))]
3674/// # fn main() {}
3675/// ```
3676///
3677/// The path is resolved using [POSIX semantics][posix-semantics] except that it stops short of
3678/// resolving symlinks. This means it will keep `..` components and trailing slashes.
3679///
3680/// ## Windows paths
3681///
3682/// ```
3683/// # #[cfg(windows)]
3684/// fn main() -> std::io::Result<()> {
3685///     use camino::Utf8Path;
3686///
3687///     // Relative to absolute
3688///     let absolute = camino::absolute_utf8("foo/./bar")?;
3689///     assert!(absolute.ends_with(r"foo\bar"));
3690///
3691///     // Absolute to absolute
3692///     let absolute = camino::absolute_utf8(r"C:\foo//test\..\./bar.rs")?;
3693///
3694///     assert_eq!(absolute, Utf8Path::new(r"C:\foo\bar.rs"));
3695///     Ok(())
3696/// }
3697/// # #[cfg(not(windows))]
3698/// # fn main() {}
3699/// ```
3700///
3701/// For verbatim paths this will simply return the path as given. For other paths this is currently
3702/// equivalent to calling [`GetFullPathNameW`][windows-path].
3703///
3704/// Note that this [may change in the future][changes].
3705///
3706/// [changes]: io#platform-specific-behavior
3707/// [posix-semantics]:
3708///     https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
3709/// [windows-path]:
3710///     https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew
3711#[cfg(absolute_path)]
3712pub fn absolute_utf8<P: AsRef<Path>>(path: P) -> io::Result<Utf8PathBuf> {
3713    // Note that even if the passed in path is valid UTF-8, it is not guaranteed
3714    // that the absolute path will be valid UTF-8. For example, the current
3715    // directory may not be valid UTF-8.
3716    //
3717    // That's why we take `AsRef<Path>` instead of `AsRef<Utf8Path>` here -- we
3718    // have to pay the cost of checking for valid UTF-8 anyway.
3719    let path = path.as_ref();
3720    #[allow(clippy::incompatible_msrv)]
3721    Utf8PathBuf::try_from(std::path::absolute(path)?).map_err(|error| error.into_io_error())
3722}
3723
3724// invariant: OsStr must be guaranteed to be utf8 data
3725#[inline]
3726unsafe fn str_assume_utf8(string: &OsStr) -> &str {
3727    #[cfg(os_str_bytes)]
3728    {
3729        // SAFETY: OsStr is guaranteed to be utf8 data from the invariant
3730        unsafe {
3731            std::str::from_utf8_unchecked(
3732                #[allow(clippy::incompatible_msrv)]
3733                string.as_encoded_bytes(),
3734            )
3735        }
3736    }
3737    #[cfg(not(os_str_bytes))]
3738    {
3739        // Adapted from the source code for Option::unwrap_unchecked.
3740        match string.to_str() {
3741            Some(val) => val,
3742            None => std::hint::unreachable_unchecked(),
3743        }
3744    }
3745}