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