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