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