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 let ptr = Box::into_raw(self) as *mut Path;
1687 // SAFETY:
1688 // * self is valid UTF-8
1689 // * ptr was constructed by consuming self so it represents an owned path.
1690 // * Utf8Path is marked as #[repr(transparent)] so the conversion from a *mut Utf8Path to a
1691 // *mut Path is valid.
1692 let boxed_path = unsafe { Box::from_raw(ptr) };
1693 Utf8PathBuf(boxed_path.into_path_buf())
1694 }
1695
1696 // invariant: Path must be guaranteed to be utf-8 data
1697 #[inline]
1698 unsafe fn assume_utf8(path: &Path) -> &Utf8Path {
1699 // SAFETY: Utf8Path is marked as #[repr(transparent)] so the conversion from a
1700 // *const Path to a *const Utf8Path is valid.
1701 &*(path as *const Path as *const Utf8Path)
1702 }
1703
1704 #[cfg(path_buf_deref_mut)]
1705 #[inline]
1706 unsafe fn assume_utf8_mut(path: &mut Path) -> &mut Utf8Path {
1707 &mut *(path as *mut Path as *mut Utf8Path)
1708 }
1709}
1710
1711impl Clone for Box<Utf8Path> {
1712 fn clone(&self) -> Self {
1713 let boxed: Box<Path> = self.0.into();
1714 let ptr = Box::into_raw(boxed) as *mut Utf8Path;
1715 // SAFETY:
1716 // * self is valid UTF-8
1717 // * ptr was created by consuming a Box<Path> so it represents an rced pointer
1718 // * Utf8Path is marked as #[repr(transparent)] so the conversion from *mut Path to
1719 // *mut Utf8Path is valid
1720 unsafe { Box::from_raw(ptr) }
1721 }
1722}
1723
1724impl fmt::Display for Utf8Path {
1725 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1726 fmt::Display::fmt(self.as_str(), f)
1727 }
1728}
1729
1730impl fmt::Debug for Utf8Path {
1731 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1732 fmt::Debug::fmt(self.as_str(), f)
1733 }
1734}
1735
1736/// An iterator over [`Utf8Path`] and its ancestors.
1737///
1738/// This `struct` is created by the [`ancestors`] method on [`Utf8Path`].
1739/// See its documentation for more.
1740///
1741/// # Examples
1742///
1743/// ```
1744/// use camino::Utf8Path;
1745///
1746/// let path = Utf8Path::new("/foo/bar");
1747///
1748/// for ancestor in path.ancestors() {
1749/// println!("{}", ancestor);
1750/// }
1751/// ```
1752///
1753/// [`ancestors`]: Utf8Path::ancestors
1754#[derive(Copy, Clone)]
1755#[must_use = "iterators are lazy and do nothing unless consumed"]
1756#[repr(transparent)]
1757pub struct Utf8Ancestors<'a>(Ancestors<'a>);
1758
1759impl fmt::Debug for Utf8Ancestors<'_> {
1760 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1761 fmt::Debug::fmt(&self.0, f)
1762 }
1763}
1764
1765impl<'a> Iterator for Utf8Ancestors<'a> {
1766 type Item = &'a Utf8Path;
1767
1768 #[inline]
1769 fn next(&mut self) -> Option<Self::Item> {
1770 self.0.next().map(|path| {
1771 // SAFETY: Utf8Ancestors was constructed from a Utf8Path, so it is guaranteed to
1772 // be valid UTF-8
1773 unsafe { Utf8Path::assume_utf8(path) }
1774 })
1775 }
1776}
1777
1778impl FusedIterator for Utf8Ancestors<'_> {}
1779
1780/// An iterator over the [`Utf8Component`]s of a [`Utf8Path`].
1781///
1782/// This `struct` is created by the [`components`] method on [`Utf8Path`].
1783/// See its documentation for more.
1784///
1785/// # Examples
1786///
1787/// ```
1788/// use camino::Utf8Path;
1789///
1790/// let path = Utf8Path::new("/tmp/foo/bar.txt");
1791///
1792/// for component in path.components() {
1793/// println!("{:?}", component);
1794/// }
1795/// ```
1796///
1797/// [`components`]: Utf8Path::components
1798#[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
1799#[must_use = "iterators are lazy and do nothing unless consumed"]
1800pub struct Utf8Components<'a>(Components<'a>);
1801
1802impl<'a> Utf8Components<'a> {
1803 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
1804 ///
1805 /// # Examples
1806 ///
1807 /// ```
1808 /// use camino::Utf8Path;
1809 ///
1810 /// let mut components = Utf8Path::new("/tmp/foo/bar.txt").components();
1811 /// components.next();
1812 /// components.next();
1813 ///
1814 /// assert_eq!(Utf8Path::new("foo/bar.txt"), components.as_path());
1815 /// ```
1816 #[must_use]
1817 #[inline]
1818 pub fn as_path(&self) -> &'a Utf8Path {
1819 // SAFETY: Utf8Components was constructed from a Utf8Path, so it is guaranteed to be valid
1820 // UTF-8
1821 unsafe { Utf8Path::assume_utf8(self.0.as_path()) }
1822 }
1823}
1824
1825impl<'a> Iterator for Utf8Components<'a> {
1826 type Item = Utf8Component<'a>;
1827
1828 #[inline]
1829 fn next(&mut self) -> Option<Self::Item> {
1830 self.0.next().map(|component| {
1831 // SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be
1832 // valid UTF-8
1833 unsafe { Utf8Component::new(component) }
1834 })
1835 }
1836}
1837
1838impl FusedIterator for Utf8Components<'_> {}
1839
1840impl DoubleEndedIterator for Utf8Components<'_> {
1841 #[inline]
1842 fn next_back(&mut self) -> Option<Self::Item> {
1843 self.0.next_back().map(|component| {
1844 // SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be
1845 // valid UTF-8
1846 unsafe { Utf8Component::new(component) }
1847 })
1848 }
1849}
1850
1851impl fmt::Debug for Utf8Components<'_> {
1852 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1853 fmt::Debug::fmt(&self.0, f)
1854 }
1855}
1856
1857impl AsRef<Utf8Path> for Utf8Components<'_> {
1858 #[inline]
1859 fn as_ref(&self) -> &Utf8Path {
1860 self.as_path()
1861 }
1862}
1863
1864impl AsRef<Path> for Utf8Components<'_> {
1865 #[inline]
1866 fn as_ref(&self) -> &Path {
1867 self.as_path().as_ref()
1868 }
1869}
1870
1871impl AsRef<str> for Utf8Components<'_> {
1872 #[inline]
1873 fn as_ref(&self) -> &str {
1874 self.as_path().as_ref()
1875 }
1876}
1877
1878impl AsRef<OsStr> for Utf8Components<'_> {
1879 #[inline]
1880 fn as_ref(&self) -> &OsStr {
1881 self.as_path().as_os_str()
1882 }
1883}
1884
1885/// An iterator over the [`Utf8Component`]s of a [`Utf8Path`], as [`str`] slices.
1886///
1887/// This `struct` is created by the [`iter`] method on [`Utf8Path`].
1888/// See its documentation for more.
1889///
1890/// [`iter`]: Utf8Path::iter
1891#[derive(Clone)]
1892#[must_use = "iterators are lazy and do nothing unless consumed"]
1893pub struct Iter<'a> {
1894 inner: Utf8Components<'a>,
1895}
1896
1897impl fmt::Debug for Iter<'_> {
1898 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1899 struct DebugHelper<'a>(&'a Utf8Path);
1900
1901 impl fmt::Debug for DebugHelper<'_> {
1902 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1903 f.debug_list().entries(self.0.iter()).finish()
1904 }
1905 }
1906
1907 f.debug_tuple("Iter")
1908 .field(&DebugHelper(self.as_path()))
1909 .finish()
1910 }
1911}
1912
1913impl<'a> Iter<'a> {
1914 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
1915 ///
1916 /// # Examples
1917 ///
1918 /// ```
1919 /// use camino::Utf8Path;
1920 ///
1921 /// let mut iter = Utf8Path::new("/tmp/foo/bar.txt").iter();
1922 /// iter.next();
1923 /// iter.next();
1924 ///
1925 /// assert_eq!(Utf8Path::new("foo/bar.txt"), iter.as_path());
1926 /// ```
1927 #[must_use]
1928 #[inline]
1929 pub fn as_path(&self) -> &'a Utf8Path {
1930 self.inner.as_path()
1931 }
1932}
1933
1934impl AsRef<Utf8Path> for Iter<'_> {
1935 #[inline]
1936 fn as_ref(&self) -> &Utf8Path {
1937 self.as_path()
1938 }
1939}
1940
1941impl AsRef<Path> for Iter<'_> {
1942 #[inline]
1943 fn as_ref(&self) -> &Path {
1944 self.as_path().as_ref()
1945 }
1946}
1947
1948impl AsRef<str> for Iter<'_> {
1949 #[inline]
1950 fn as_ref(&self) -> &str {
1951 self.as_path().as_ref()
1952 }
1953}
1954
1955impl AsRef<OsStr> for Iter<'_> {
1956 #[inline]
1957 fn as_ref(&self) -> &OsStr {
1958 self.as_path().as_os_str()
1959 }
1960}
1961
1962impl<'a> Iterator for Iter<'a> {
1963 type Item = &'a str;
1964
1965 #[inline]
1966 fn next(&mut self) -> Option<&'a str> {
1967 self.inner.next().map(|component| component.as_str())
1968 }
1969}
1970
1971impl<'a> DoubleEndedIterator for Iter<'a> {
1972 #[inline]
1973 fn next_back(&mut self) -> Option<&'a str> {
1974 self.inner.next_back().map(|component| component.as_str())
1975 }
1976}
1977
1978impl FusedIterator for Iter<'_> {}
1979
1980/// A single component of a path.
1981///
1982/// A [`Utf8Component`] roughly corresponds to a substring between path separators
1983/// (`/` or `\`).
1984///
1985/// This `enum` is created by iterating over [`Utf8Components`], which in turn is
1986/// created by the [`components`](Utf8Path::components) method on [`Utf8Path`].
1987///
1988/// # Examples
1989///
1990/// ```rust
1991/// use camino::{Utf8Component, Utf8Path};
1992///
1993/// let path = Utf8Path::new("/tmp/foo/bar.txt");
1994/// let components = path.components().collect::<Vec<_>>();
1995/// assert_eq!(&components, &[
1996/// Utf8Component::RootDir,
1997/// Utf8Component::Normal("tmp"),
1998/// Utf8Component::Normal("foo"),
1999/// Utf8Component::Normal("bar.txt"),
2000/// ]);
2001/// ```
2002#[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
2003pub enum Utf8Component<'a> {
2004 /// A Windows path prefix, e.g., `C:` or `\\server\share`.
2005 ///
2006 /// There is a large variety of prefix types, see [`Utf8Prefix`]'s documentation
2007 /// for more.
2008 ///
2009 /// Does not occur on Unix.
2010 Prefix(Utf8PrefixComponent<'a>),
2011
2012 /// The root directory component, appears after any prefix and before anything else.
2013 ///
2014 /// It represents a separator that designates that a path starts from root.
2015 RootDir,
2016
2017 /// A reference to the current directory, i.e., `.`.
2018 CurDir,
2019
2020 /// A reference to the parent directory, i.e., `..`.
2021 ParentDir,
2022
2023 /// A normal component, e.g., `a` and `b` in `a/b`.
2024 ///
2025 /// This variant is the most common one, it represents references to files
2026 /// or directories.
2027 Normal(&'a str),
2028}
2029
2030impl<'a> Utf8Component<'a> {
2031 unsafe fn new(component: Component<'a>) -> Utf8Component<'a> {
2032 match component {
2033 Component::Prefix(prefix) => Utf8Component::Prefix(Utf8PrefixComponent(prefix)),
2034 Component::RootDir => Utf8Component::RootDir,
2035 Component::CurDir => Utf8Component::CurDir,
2036 Component::ParentDir => Utf8Component::ParentDir,
2037 Component::Normal(s) => Utf8Component::Normal(str_assume_utf8(s)),
2038 }
2039 }
2040
2041 /// Extracts the underlying [`str`] slice.
2042 ///
2043 /// # Examples
2044 ///
2045 /// ```
2046 /// use camino::Utf8Path;
2047 ///
2048 /// let path = Utf8Path::new("./tmp/foo/bar.txt");
2049 /// let components: Vec<_> = path.components().map(|comp| comp.as_str()).collect();
2050 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
2051 /// ```
2052 #[must_use]
2053 #[inline]
2054 pub fn as_str(&self) -> &'a str {
2055 // SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be
2056 // valid UTF-8
2057 unsafe { str_assume_utf8(self.as_os_str()) }
2058 }
2059
2060 /// Extracts the underlying [`OsStr`] slice.
2061 ///
2062 /// # Examples
2063 ///
2064 /// ```
2065 /// use camino::Utf8Path;
2066 ///
2067 /// let path = Utf8Path::new("./tmp/foo/bar.txt");
2068 /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect();
2069 /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]);
2070 /// ```
2071 #[must_use]
2072 pub fn as_os_str(&self) -> &'a OsStr {
2073 match *self {
2074 Utf8Component::Prefix(prefix) => prefix.as_os_str(),
2075 Utf8Component::RootDir => Component::RootDir.as_os_str(),
2076 Utf8Component::CurDir => Component::CurDir.as_os_str(),
2077 Utf8Component::ParentDir => Component::ParentDir.as_os_str(),
2078 Utf8Component::Normal(s) => OsStr::new(s),
2079 }
2080 }
2081}
2082
2083impl fmt::Debug for Utf8Component<'_> {
2084 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2085 fmt::Debug::fmt(self.as_os_str(), f)
2086 }
2087}
2088
2089impl fmt::Display for Utf8Component<'_> {
2090 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2091 fmt::Display::fmt(self.as_str(), f)
2092 }
2093}
2094
2095impl AsRef<Utf8Path> for Utf8Component<'_> {
2096 #[inline]
2097 fn as_ref(&self) -> &Utf8Path {
2098 self.as_str().as_ref()
2099 }
2100}
2101
2102impl AsRef<Path> for Utf8Component<'_> {
2103 #[inline]
2104 fn as_ref(&self) -> &Path {
2105 self.as_os_str().as_ref()
2106 }
2107}
2108
2109impl AsRef<str> for Utf8Component<'_> {
2110 #[inline]
2111 fn as_ref(&self) -> &str {
2112 self.as_str()
2113 }
2114}
2115
2116impl AsRef<OsStr> for Utf8Component<'_> {
2117 #[inline]
2118 fn as_ref(&self) -> &OsStr {
2119 self.as_os_str()
2120 }
2121}
2122
2123/// Windows path prefixes, e.g., `C:` or `\\server\share`.
2124///
2125/// Windows uses a variety of path prefix styles, including references to drive
2126/// volumes (like `C:`), network shared folders (like `\\server\share`), and
2127/// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with
2128/// `\\?\`), in which case `/` is *not* treated as a separator and essentially
2129/// no normalization is performed.
2130///
2131/// # Examples
2132///
2133/// ```
2134/// use camino::{Utf8Component, Utf8Path, Utf8Prefix};
2135/// use camino::Utf8Prefix::*;
2136///
2137/// fn get_path_prefix(s: &str) -> Utf8Prefix {
2138/// let path = Utf8Path::new(s);
2139/// match path.components().next().unwrap() {
2140/// Utf8Component::Prefix(prefix_component) => prefix_component.kind(),
2141/// _ => panic!(),
2142/// }
2143/// }
2144///
2145/// # if cfg!(windows) {
2146/// assert_eq!(Verbatim("pictures"), get_path_prefix(r"\\?\pictures\kittens"));
2147/// assert_eq!(VerbatimUNC("server", "share"), get_path_prefix(r"\\?\UNC\server\share"));
2148/// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\C:\"));
2149/// assert_eq!(DeviceNS("BrainInterface"), get_path_prefix(r"\\.\BrainInterface"));
2150/// assert_eq!(UNC("server", "share"), get_path_prefix(r"\\server\share"));
2151/// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris"));
2152/// # }
2153/// ```
2154#[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
2155pub enum Utf8Prefix<'a> {
2156 /// Verbatim prefix, e.g., `\\?\cat_pics`.
2157 ///
2158 /// Verbatim prefixes consist of `\\?\` immediately followed by the given
2159 /// component.
2160 Verbatim(&'a str),
2161
2162 /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
2163 /// e.g., `\\?\UNC\server\share`.
2164 ///
2165 /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
2166 /// server's hostname and a share name.
2167 VerbatimUNC(&'a str, &'a str),
2168
2169 /// Verbatim disk prefix, e.g., `\\?\C:`.
2170 ///
2171 /// Verbatim disk prefixes consist of `\\?\` immediately followed by the
2172 /// drive letter and `:`.
2173 VerbatimDisk(u8),
2174
2175 /// Device namespace prefix, e.g., `\\.\COM42`.
2176 ///
2177 /// Device namespace prefixes consist of `\\.\` immediately followed by the
2178 /// device name.
2179 DeviceNS(&'a str),
2180
2181 /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
2182 /// `\\server\share`.
2183 ///
2184 /// UNC prefixes consist of the server's hostname and a share name.
2185 UNC(&'a str, &'a str),
2186
2187 /// Prefix `C:` for the given disk drive.
2188 Disk(u8),
2189}
2190
2191impl Utf8Prefix<'_> {
2192 /// Determines if the prefix is verbatim, i.e., begins with `\\?\`.
2193 ///
2194 /// # Examples
2195 ///
2196 /// ```
2197 /// use camino::Utf8Prefix::*;
2198 ///
2199 /// assert!(Verbatim("pictures").is_verbatim());
2200 /// assert!(VerbatimUNC("server", "share").is_verbatim());
2201 /// assert!(VerbatimDisk(b'C').is_verbatim());
2202 /// assert!(!DeviceNS("BrainInterface").is_verbatim());
2203 /// assert!(!UNC("server", "share").is_verbatim());
2204 /// assert!(!Disk(b'C').is_verbatim());
2205 /// ```
2206 #[must_use]
2207 pub fn is_verbatim(&self) -> bool {
2208 use Utf8Prefix::*;
2209 matches!(self, Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..))
2210 }
2211}
2212
2213/// A structure wrapping a Windows path prefix as well as its unparsed string
2214/// representation.
2215///
2216/// In addition to the parsed [`Utf8Prefix`] information returned by [`kind`],
2217/// [`Utf8PrefixComponent`] also holds the raw and unparsed [`str`] slice,
2218/// returned by [`as_str`].
2219///
2220/// Instances of this `struct` can be obtained by matching against the
2221/// [`Prefix` variant] on [`Utf8Component`].
2222///
2223/// Does not occur on Unix.
2224///
2225/// # Examples
2226///
2227/// ```
2228/// # if cfg!(windows) {
2229/// use camino::{Utf8Component, Utf8Path, Utf8Prefix};
2230/// use std::ffi::OsStr;
2231///
2232/// let path = Utf8Path::new(r"C:\you\later\");
2233/// match path.components().next().unwrap() {
2234/// Utf8Component::Prefix(prefix_component) => {
2235/// assert_eq!(Utf8Prefix::Disk(b'C'), prefix_component.kind());
2236/// assert_eq!("C:", prefix_component.as_str());
2237/// }
2238/// _ => unreachable!(),
2239/// }
2240/// # }
2241/// ```
2242///
2243/// [`as_str`]: Utf8PrefixComponent::as_str
2244/// [`kind`]: Utf8PrefixComponent::kind
2245/// [`Prefix` variant]: Utf8Component::Prefix
2246#[repr(transparent)]
2247#[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
2248pub struct Utf8PrefixComponent<'a>(PrefixComponent<'a>);
2249
2250impl<'a> Utf8PrefixComponent<'a> {
2251 /// Returns the parsed prefix data.
2252 ///
2253 /// See [`Utf8Prefix`]'s documentation for more information on the different
2254 /// kinds of prefixes.
2255 #[must_use]
2256 pub fn kind(&self) -> Utf8Prefix<'a> {
2257 // SAFETY for all the below unsafe blocks: the path self was originally constructed from was
2258 // UTF-8 so any parts of it are valid UTF-8
2259 match self.0.kind() {
2260 Prefix::Verbatim(prefix) => Utf8Prefix::Verbatim(unsafe { str_assume_utf8(prefix) }),
2261 Prefix::VerbatimUNC(server, share) => {
2262 let server = unsafe { str_assume_utf8(server) };
2263 let share = unsafe { str_assume_utf8(share) };
2264 Utf8Prefix::VerbatimUNC(server, share)
2265 }
2266 Prefix::VerbatimDisk(drive) => Utf8Prefix::VerbatimDisk(drive),
2267 Prefix::DeviceNS(prefix) => Utf8Prefix::DeviceNS(unsafe { str_assume_utf8(prefix) }),
2268 Prefix::UNC(server, share) => {
2269 let server = unsafe { str_assume_utf8(server) };
2270 let share = unsafe { str_assume_utf8(share) };
2271 Utf8Prefix::UNC(server, share)
2272 }
2273 Prefix::Disk(drive) => Utf8Prefix::Disk(drive),
2274 }
2275 }
2276
2277 /// Returns the [`str`] slice for this prefix.
2278 #[must_use]
2279 #[inline]
2280 pub fn as_str(&self) -> &'a str {
2281 // SAFETY: Utf8PrefixComponent was constructed from a Utf8Path, so it is guaranteed to be
2282 // valid UTF-8
2283 unsafe { str_assume_utf8(self.as_os_str()) }
2284 }
2285
2286 /// Returns the raw [`OsStr`] slice for this prefix.
2287 #[must_use]
2288 #[inline]
2289 pub fn as_os_str(&self) -> &'a OsStr {
2290 self.0.as_os_str()
2291 }
2292}
2293
2294impl fmt::Debug for Utf8PrefixComponent<'_> {
2295 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2296 fmt::Debug::fmt(&self.0, f)
2297 }
2298}
2299
2300impl fmt::Display for Utf8PrefixComponent<'_> {
2301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2302 fmt::Display::fmt(self.as_str(), f)
2303 }
2304}
2305
2306// ---
2307// read_dir_utf8
2308// ---
2309
2310/// Iterator over the entries in a directory.
2311///
2312/// This iterator is returned from [`Utf8Path::read_dir_utf8`] and will yield instances of
2313/// <code>[io::Result]<[Utf8DirEntry]></code>. Through a [`Utf8DirEntry`] information like the entry's path
2314/// and possibly other metadata can be learned.
2315///
2316/// The order in which this iterator returns entries is platform and filesystem
2317/// dependent.
2318///
2319/// # Errors
2320///
2321/// This [`io::Result`] will be an [`Err`] if there's some sort of intermittent
2322/// IO error during iteration.
2323///
2324/// If a directory entry is not UTF-8, an [`io::Error`] is returned with the
2325/// [`ErrorKind`](io::ErrorKind) set to [`InvalidData`][io::ErrorKind::InvalidData]
2326/// and the payload set to a [`FromPathBufError`].
2327#[derive(Debug)]
2328pub struct ReadDirUtf8 {
2329 inner: fs::ReadDir,
2330}
2331
2332impl Iterator for ReadDirUtf8 {
2333 type Item = io::Result<Utf8DirEntry>;
2334
2335 fn next(&mut self) -> Option<io::Result<Utf8DirEntry>> {
2336 self.inner
2337 .next()
2338 .map(|entry| entry.and_then(Utf8DirEntry::new))
2339 }
2340}
2341
2342/// Entries returned by the [`ReadDirUtf8`] iterator.
2343///
2344/// An instance of [`Utf8DirEntry`] represents an entry inside of a directory on the filesystem. Each
2345/// entry can be inspected via methods to learn about the full path or possibly other metadata.
2346#[derive(Debug)]
2347pub struct Utf8DirEntry {
2348 inner: fs::DirEntry,
2349 path: Utf8PathBuf,
2350}
2351
2352impl Utf8DirEntry {
2353 fn new(inner: fs::DirEntry) -> io::Result<Self> {
2354 let path = inner
2355 .path()
2356 .try_into()
2357 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
2358 Ok(Self { inner, path })
2359 }
2360
2361 /// Returns the full path to the file that this entry represents.
2362 ///
2363 /// The full path is created by joining the original path to `read_dir`
2364 /// with the filename of this entry.
2365 ///
2366 /// # Examples
2367 ///
2368 /// ```no_run
2369 /// use camino::Utf8Path;
2370 ///
2371 /// fn main() -> std::io::Result<()> {
2372 /// for entry in Utf8Path::new(".").read_dir_utf8()? {
2373 /// let dir = entry?;
2374 /// println!("{}", dir.path());
2375 /// }
2376 /// Ok(())
2377 /// }
2378 /// ```
2379 ///
2380 /// This prints output like:
2381 ///
2382 /// ```text
2383 /// ./whatever.txt
2384 /// ./foo.html
2385 /// ./hello_world.rs
2386 /// ```
2387 ///
2388 /// The exact text, of course, depends on what files you have in `.`.
2389 #[inline]
2390 pub fn path(&self) -> &Utf8Path {
2391 &self.path
2392 }
2393
2394 /// Returns the metadata for the file that this entry points at.
2395 ///
2396 /// This function will not traverse symlinks if this entry points at a symlink. To traverse
2397 /// symlinks use [`Utf8Path::metadata`] or [`fs::File::metadata`].
2398 ///
2399 /// # Platform-specific behavior
2400 ///
2401 /// On Windows this function is cheap to call (no extra system calls
2402 /// needed), but on Unix platforms this function is the equivalent of
2403 /// calling `symlink_metadata` on the path.
2404 ///
2405 /// # Examples
2406 ///
2407 /// ```
2408 /// use camino::Utf8Path;
2409 ///
2410 /// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
2411 /// for entry in entries {
2412 /// if let Ok(entry) = entry {
2413 /// // Here, `entry` is a `Utf8DirEntry`.
2414 /// if let Ok(metadata) = entry.metadata() {
2415 /// // Now let's show our entry's permissions!
2416 /// println!("{}: {:?}", entry.path(), metadata.permissions());
2417 /// } else {
2418 /// println!("Couldn't get metadata for {}", entry.path());
2419 /// }
2420 /// }
2421 /// }
2422 /// }
2423 /// ```
2424 #[inline]
2425 pub fn metadata(&self) -> io::Result<Metadata> {
2426 self.inner.metadata()
2427 }
2428
2429 /// Returns the file type for the file that this entry points at.
2430 ///
2431 /// This function will not traverse symlinks if this entry points at a
2432 /// symlink.
2433 ///
2434 /// # Platform-specific behavior
2435 ///
2436 /// On Windows and most Unix platforms this function is free (no extra
2437 /// system calls needed), but some Unix platforms may require the equivalent
2438 /// call to `symlink_metadata` to learn about the target file type.
2439 ///
2440 /// # Examples
2441 ///
2442 /// ```
2443 /// use camino::Utf8Path;
2444 ///
2445 /// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
2446 /// for entry in entries {
2447 /// if let Ok(entry) = entry {
2448 /// // Here, `entry` is a `DirEntry`.
2449 /// if let Ok(file_type) = entry.file_type() {
2450 /// // Now let's show our entry's file type!
2451 /// println!("{}: {:?}", entry.path(), file_type);
2452 /// } else {
2453 /// println!("Couldn't get file type for {}", entry.path());
2454 /// }
2455 /// }
2456 /// }
2457 /// }
2458 /// ```
2459 #[inline]
2460 pub fn file_type(&self) -> io::Result<fs::FileType> {
2461 self.inner.file_type()
2462 }
2463
2464 /// Returns the bare file name of this directory entry without any other
2465 /// leading path component.
2466 ///
2467 /// # Examples
2468 ///
2469 /// ```
2470 /// use camino::Utf8Path;
2471 ///
2472 /// if let Ok(entries) = Utf8Path::new(".").read_dir_utf8() {
2473 /// for entry in entries {
2474 /// if let Ok(entry) = entry {
2475 /// // Here, `entry` is a `DirEntry`.
2476 /// println!("{}", entry.file_name());
2477 /// }
2478 /// }
2479 /// }
2480 /// ```
2481 pub fn file_name(&self) -> &str {
2482 self.path
2483 .file_name()
2484 .expect("path created through DirEntry must have a filename")
2485 }
2486
2487 /// Returns the original [`fs::DirEntry`] within this [`Utf8DirEntry`].
2488 #[inline]
2489 pub fn into_inner(self) -> fs::DirEntry {
2490 self.inner
2491 }
2492
2493 /// Returns the full path to the file that this entry represents.
2494 ///
2495 /// This is analogous to [`path`], but moves ownership of the path.
2496 ///
2497 /// [`path`]: struct.Utf8DirEntry.html#method.path
2498 #[inline]
2499 #[must_use = "`self` will be dropped if the result is not used"]
2500 pub fn into_path(self) -> Utf8PathBuf {
2501 self.path
2502 }
2503}
2504
2505impl From<String> for Utf8PathBuf {
2506 fn from(string: String) -> Utf8PathBuf {
2507 Utf8PathBuf(string.into())
2508 }
2509}
2510
2511impl FromStr for Utf8PathBuf {
2512 type Err = Infallible;
2513
2514 fn from_str(s: &str) -> Result<Self, Self::Err> {
2515 Ok(Utf8PathBuf(s.into()))
2516 }
2517}
2518
2519// ---
2520// From impls: borrowed -> borrowed
2521// ---
2522
2523impl<'a> From<&'a str> for &'a Utf8Path {
2524 fn from(s: &'a str) -> &'a Utf8Path {
2525 Utf8Path::new(s)
2526 }
2527}
2528
2529// ---
2530// From impls: borrowed -> owned
2531// ---
2532
2533impl<T: ?Sized + AsRef<str>> From<&T> for Utf8PathBuf {
2534 fn from(s: &T) -> Utf8PathBuf {
2535 Utf8PathBuf::from(s.as_ref().to_owned())
2536 }
2537}
2538
2539impl<T: ?Sized + AsRef<str>> From<&T> for Box<Utf8Path> {
2540 fn from(s: &T) -> Box<Utf8Path> {
2541 Utf8PathBuf::from(s).into_boxed_path()
2542 }
2543}
2544
2545impl From<&'_ Utf8Path> for Arc<Utf8Path> {
2546 fn from(path: &Utf8Path) -> Arc<Utf8Path> {
2547 let arc: Arc<Path> = Arc::from(AsRef::<Path>::as_ref(path));
2548 let ptr = Arc::into_raw(arc) as *const Utf8Path;
2549 // SAFETY:
2550 // * path is valid UTF-8
2551 // * ptr was created by consuming an Arc<Path> so it represents an arced pointer
2552 // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
2553 // *const Utf8Path is valid
2554 unsafe { Arc::from_raw(ptr) }
2555 }
2556}
2557
2558impl From<&'_ Utf8Path> for Rc<Utf8Path> {
2559 fn from(path: &Utf8Path) -> Rc<Utf8Path> {
2560 let rc: Rc<Path> = Rc::from(AsRef::<Path>::as_ref(path));
2561 let ptr = Rc::into_raw(rc) as *const Utf8Path;
2562 // SAFETY:
2563 // * path is valid UTF-8
2564 // * ptr was created by consuming an Rc<Path> so it represents an rced pointer
2565 // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
2566 // *const Utf8Path is valid
2567 unsafe { Rc::from_raw(ptr) }
2568 }
2569}
2570
2571impl<'a> From<&'a Utf8Path> for Cow<'a, Utf8Path> {
2572 fn from(path: &'a Utf8Path) -> Cow<'a, Utf8Path> {
2573 Cow::Borrowed(path)
2574 }
2575}
2576
2577impl From<&'_ Utf8Path> for Box<Path> {
2578 fn from(path: &Utf8Path) -> Box<Path> {
2579 AsRef::<Path>::as_ref(path).into()
2580 }
2581}
2582
2583impl From<&'_ Utf8Path> for Arc<Path> {
2584 fn from(path: &Utf8Path) -> Arc<Path> {
2585 AsRef::<Path>::as_ref(path).into()
2586 }
2587}
2588
2589impl From<&'_ Utf8Path> for Rc<Path> {
2590 fn from(path: &Utf8Path) -> Rc<Path> {
2591 AsRef::<Path>::as_ref(path).into()
2592 }
2593}
2594
2595impl<'a> From<&'a Utf8Path> for Cow<'a, Path> {
2596 fn from(path: &'a Utf8Path) -> Cow<'a, Path> {
2597 Cow::Borrowed(path.as_ref())
2598 }
2599}
2600
2601// ---
2602// From impls: owned -> owned
2603// ---
2604
2605impl From<Box<Utf8Path>> for Utf8PathBuf {
2606 fn from(path: Box<Utf8Path>) -> Utf8PathBuf {
2607 path.into_path_buf()
2608 }
2609}
2610
2611impl From<Utf8PathBuf> for Box<Utf8Path> {
2612 fn from(path: Utf8PathBuf) -> Box<Utf8Path> {
2613 path.into_boxed_path()
2614 }
2615}
2616
2617impl<'a> From<Cow<'a, Utf8Path>> for Utf8PathBuf {
2618 fn from(path: Cow<'a, Utf8Path>) -> Utf8PathBuf {
2619 path.into_owned()
2620 }
2621}
2622
2623impl From<Utf8PathBuf> for String {
2624 fn from(path: Utf8PathBuf) -> String {
2625 path.into_string()
2626 }
2627}
2628
2629impl From<Utf8PathBuf> for OsString {
2630 fn from(path: Utf8PathBuf) -> OsString {
2631 path.into_os_string()
2632 }
2633}
2634
2635impl<'a> From<Utf8PathBuf> for Cow<'a, Utf8Path> {
2636 fn from(path: Utf8PathBuf) -> Cow<'a, Utf8Path> {
2637 Cow::Owned(path)
2638 }
2639}
2640
2641impl From<Utf8PathBuf> for Arc<Utf8Path> {
2642 fn from(path: Utf8PathBuf) -> Arc<Utf8Path> {
2643 let arc: Arc<Path> = Arc::from(path.0);
2644 let ptr = Arc::into_raw(arc) as *const Utf8Path;
2645 // SAFETY:
2646 // * path is valid UTF-8
2647 // * ptr was created by consuming an Arc<Path> so it represents an arced pointer
2648 // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
2649 // *const Utf8Path is valid
2650 unsafe { Arc::from_raw(ptr) }
2651 }
2652}
2653
2654impl From<Utf8PathBuf> for Rc<Utf8Path> {
2655 fn from(path: Utf8PathBuf) -> Rc<Utf8Path> {
2656 let rc: Rc<Path> = Rc::from(path.0);
2657 let ptr = Rc::into_raw(rc) as *const Utf8Path;
2658 // SAFETY:
2659 // * path is valid UTF-8
2660 // * ptr was created by consuming an Rc<Path> so it represents an rced pointer
2661 // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to
2662 // *const Utf8Path is valid
2663 unsafe { Rc::from_raw(ptr) }
2664 }
2665}
2666
2667impl From<Utf8PathBuf> for PathBuf {
2668 fn from(path: Utf8PathBuf) -> PathBuf {
2669 path.0
2670 }
2671}
2672
2673impl From<Utf8PathBuf> for Box<Path> {
2674 fn from(path: Utf8PathBuf) -> Box<Path> {
2675 PathBuf::from(path).into_boxed_path()
2676 }
2677}
2678
2679impl From<Utf8PathBuf> for Arc<Path> {
2680 fn from(path: Utf8PathBuf) -> Arc<Path> {
2681 PathBuf::from(path).into()
2682 }
2683}
2684
2685impl From<Utf8PathBuf> for Rc<Path> {
2686 fn from(path: Utf8PathBuf) -> Rc<Path> {
2687 PathBuf::from(path).into()
2688 }
2689}
2690
2691impl<'a> From<Utf8PathBuf> for Cow<'a, Path> {
2692 fn from(path: Utf8PathBuf) -> Cow<'a, Path> {
2693 PathBuf::from(path).into()
2694 }
2695}
2696
2697// ---
2698// TryFrom impls
2699// ---
2700
2701impl TryFrom<PathBuf> for Utf8PathBuf {
2702 type Error = FromPathBufError;
2703
2704 fn try_from(path: PathBuf) -> Result<Utf8PathBuf, Self::Error> {
2705 Utf8PathBuf::from_path_buf(path).map_err(|path| FromPathBufError {
2706 path,
2707 error: FromPathError(()),
2708 })
2709 }
2710}
2711
2712impl TryFrom<OsString> for Utf8PathBuf {
2713 type Error = FromOsStringError;
2714
2715 fn try_from(os_string: OsString) -> Result<Utf8PathBuf, Self::Error> {
2716 Utf8PathBuf::from_os_string(os_string).map_err(|os_string| FromOsStringError {
2717 os_string,
2718 error: FromOsStrError(()),
2719 })
2720 }
2721}
2722
2723/// Converts a [`Path`] to a [`Utf8Path`].
2724///
2725/// Returns [`FromPathError`] if the path is not valid UTF-8.
2726///
2727/// # Examples
2728///
2729/// ```
2730/// use camino::Utf8Path;
2731/// use std::convert::TryFrom;
2732/// use std::ffi::OsStr;
2733/// # #[cfg(unix)]
2734/// use std::os::unix::ffi::OsStrExt;
2735/// use std::path::Path;
2736///
2737/// let unicode_path = Path::new("/valid/unicode");
2738/// <&Utf8Path>::try_from(unicode_path).expect("valid Unicode path succeeded");
2739///
2740/// // Paths on Unix can be non-UTF-8.
2741/// # #[cfg(unix)]
2742/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
2743/// # #[cfg(unix)]
2744/// let non_unicode_path = Path::new(non_unicode_str);
2745/// # #[cfg(unix)]
2746/// assert!(<&Utf8Path>::try_from(non_unicode_path).is_err(), "non-Unicode path failed");
2747/// ```
2748impl<'a> TryFrom<&'a Path> for &'a Utf8Path {
2749 type Error = FromPathError;
2750
2751 fn try_from(path: &'a Path) -> Result<&'a Utf8Path, Self::Error> {
2752 Utf8Path::from_path(path).ok_or(FromPathError(()))
2753 }
2754}
2755
2756/// Converts an [`OsStr`] to a [`Utf8Path`].
2757///
2758/// Returns the original [`OsStr`] if it is not valid UTF-8.
2759///
2760/// # Examples
2761///
2762/// ```
2763/// use camino::Utf8Path;
2764/// use std::convert::TryFrom;
2765/// use std::ffi::OsStr;
2766/// # #[cfg(unix)]
2767/// use std::os::unix::ffi::OsStrExt;
2768/// use std::path::Path;
2769///
2770/// # #[cfg(unix)]
2771/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
2772/// # #[cfg(unix)]
2773/// assert!(<&Utf8Path>::try_from(non_unicode_str).is_err(), "non-Unicode string path failed");
2774/// ```
2775impl<'a> TryFrom<&'a OsStr> for &'a Utf8Path {
2776 type Error = FromOsStrError;
2777
2778 fn try_from(os_str: &'a OsStr) -> Result<&'a Utf8Path, Self::Error> {
2779 Utf8Path::from_os_str(os_str).ok_or(FromOsStrError(()))
2780 }
2781}
2782
2783/// A possible error value while converting a [`PathBuf`] to a [`Utf8PathBuf`].
2784///
2785/// Produced by the [`TryFrom<&PathBuf>`][tryfrom] implementation for [`Utf8PathBuf`].
2786///
2787/// [tryfrom]: Utf8PathBuf#impl-TryFrom<PathBuf>-for-Utf8PathBuf
2788///
2789/// # Examples
2790///
2791/// ```
2792/// use camino::{Utf8PathBuf, FromPathBufError};
2793/// use std::convert::{TryFrom, TryInto};
2794/// use std::ffi::OsStr;
2795/// # #[cfg(unix)]
2796/// use std::os::unix::ffi::OsStrExt;
2797/// use std::path::PathBuf;
2798///
2799/// let unicode_path = PathBuf::from("/valid/unicode");
2800/// let utf8_path_buf: Utf8PathBuf = unicode_path.try_into().expect("valid Unicode path succeeded");
2801///
2802/// // Paths on Unix can be non-UTF-8.
2803/// # #[cfg(unix)]
2804/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
2805/// # #[cfg(unix)]
2806/// let non_unicode_path = PathBuf::from(non_unicode_str);
2807/// # #[cfg(unix)]
2808/// let err: FromPathBufError = Utf8PathBuf::try_from(non_unicode_path.clone())
2809/// .expect_err("non-Unicode path failed");
2810/// # #[cfg(unix)]
2811/// assert_eq!(err.as_path(), &non_unicode_path);
2812/// # #[cfg(unix)]
2813/// assert_eq!(err.into_path_buf(), non_unicode_path);
2814/// ```
2815#[derive(Clone, Debug, Eq, PartialEq)]
2816pub struct FromPathBufError {
2817 path: PathBuf,
2818 error: FromPathError,
2819}
2820
2821impl FromPathBufError {
2822 /// Returns the [`Path`] slice that was attempted to be converted to [`Utf8PathBuf`].
2823 #[inline]
2824 pub fn as_path(&self) -> &Path {
2825 &self.path
2826 }
2827
2828 /// Returns the [`PathBuf`] that was attempted to be converted to [`Utf8PathBuf`].
2829 #[inline]
2830 pub fn into_path_buf(self) -> PathBuf {
2831 self.path
2832 }
2833
2834 /// Fetches a [`FromPathError`] for more about the conversion failure.
2835 ///
2836 /// At the moment this struct does not contain any additional information, but is provided for
2837 /// completeness.
2838 #[inline]
2839 pub fn from_path_error(&self) -> FromPathError {
2840 self.error
2841 }
2842
2843 /// Converts self into a [`std::io::Error`] with kind
2844 /// [`InvalidData`](io::ErrorKind::InvalidData).
2845 ///
2846 /// Many users of [`FromPathBufError`] will want to convert it into an [`io::Error`]. This is a
2847 /// convenience method to do that.
2848 pub fn into_io_error(self) -> io::Error {
2849 // NOTE: we don't currently implement `From<FromPathBufError> for io::Error` because we want
2850 // to ensure the user actually desires that conversion.
2851 io::Error::new(io::ErrorKind::InvalidData, self)
2852 }
2853}
2854
2855impl fmt::Display for FromPathBufError {
2856 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2857 write!(f, "PathBuf contains invalid UTF-8: {}", self.path.display())
2858 }
2859}
2860
2861impl error::Error for FromPathBufError {
2862 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
2863 Some(&self.error)
2864 }
2865}
2866
2867/// A possible error value while converting a [`Path`] to a [`Utf8Path`].
2868///
2869/// Produced by the [`TryFrom<&Path>`][tryfrom] implementation for [`&Utf8Path`](Utf8Path).
2870///
2871/// [tryfrom]: Utf8Path#impl-TryFrom<%26Path>-for-%26Utf8Path
2872///
2873///
2874/// # Examples
2875///
2876/// ```
2877/// use camino::{Utf8Path, FromPathError};
2878/// use std::convert::{TryFrom, TryInto};
2879/// use std::ffi::OsStr;
2880/// # #[cfg(unix)]
2881/// use std::os::unix::ffi::OsStrExt;
2882/// use std::path::Path;
2883///
2884/// let unicode_path = Path::new("/valid/unicode");
2885/// let utf8_path: &Utf8Path = unicode_path.try_into().expect("valid Unicode path succeeded");
2886///
2887/// // Paths on Unix can be non-UTF-8.
2888/// # #[cfg(unix)]
2889/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
2890/// # #[cfg(unix)]
2891/// let non_unicode_path = Path::new(non_unicode_str);
2892/// # #[cfg(unix)]
2893/// let err: FromPathError = <&Utf8Path>::try_from(non_unicode_path)
2894/// .expect_err("non-Unicode path failed");
2895/// ```
2896#[derive(Copy, Clone, Debug, Eq, PartialEq)]
2897pub struct FromPathError(());
2898
2899impl FromPathError {
2900 /// Converts self into a [`std::io::Error`] with kind
2901 /// [`InvalidData`](io::ErrorKind::InvalidData).
2902 ///
2903 /// Many users of [`FromPathError`] will want to convert it into an [`io::Error`]. This is a
2904 /// convenience method to do that.
2905 pub fn into_io_error(self) -> io::Error {
2906 // NOTE: we don't currently implement `From<FromPathError> for io::Error` because we want
2907 // to ensure the user actually desires that conversion.
2908 io::Error::new(io::ErrorKind::InvalidData, self)
2909 }
2910}
2911
2912impl fmt::Display for FromPathError {
2913 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2914 write!(f, "Path contains invalid UTF-8")
2915 }
2916}
2917
2918impl error::Error for FromPathError {
2919 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
2920 None
2921 }
2922}
2923
2924/// A possible error value while converting a [`OsString`] to a [`Utf8PathBuf`].
2925///
2926/// Produced by the `TryFrom<OsString>` implementation for [`Utf8PathBuf`].
2927///
2928/// # Examples
2929///
2930/// ```
2931/// # #[cfg(osstring_from_str)] {
2932/// use camino::{Utf8PathBuf, FromOsStringError};
2933/// use std::convert::{TryFrom, TryInto};
2934/// use std::ffi::OsStr;
2935/// use std::str::FromStr;
2936/// use std::ffi::OsString;
2937/// # #[cfg(unix)]
2938/// use std::os::unix::ffi::OsStrExt;
2939///
2940/// let unicode_string = OsString::from_str("/valid/unicode").unwrap();
2941/// let utf8_path_buf: Utf8PathBuf = unicode_string.try_into()
2942/// .expect("valid Unicode path succeeded");
2943///
2944/// // Paths on Unix can be non-UTF-8.
2945/// # #[cfg(unix)]
2946/// let non_unicode_string = OsStr::from_bytes(b"\xFF\xFF\xFF").to_owned();
2947/// # #[cfg(unix)]
2948/// let err: FromOsStringError = Utf8PathBuf::try_from(non_unicode_string.clone())
2949/// .expect_err("non-Unicode path failed");
2950/// # #[cfg(unix)]
2951/// assert_eq!(err.as_os_str(), &non_unicode_string);
2952/// # #[cfg(unix)]
2953/// assert_eq!(err.into_os_string(), non_unicode_string);
2954/// # }
2955/// ```
2956#[derive(Clone, Debug, Eq, PartialEq)]
2957pub struct FromOsStringError {
2958 os_string: OsString,
2959 error: FromOsStrError,
2960}
2961
2962impl FromOsStringError {
2963 /// Returns the [`OsStr`] slice that was attempted to be converted to [`Utf8PathBuf`].
2964 #[inline]
2965 pub fn as_os_str(&self) -> &OsStr {
2966 &self.os_string
2967 }
2968
2969 /// Returns the [`OsString`] that was attempted to be converted to [`Utf8PathBuf`].
2970 #[inline]
2971 pub fn into_os_string(self) -> OsString {
2972 self.os_string
2973 }
2974
2975 /// Fetches a [`FromOsStrError`] for more about the conversion failure.
2976 ///
2977 /// At the moment this struct does not contain any additional information, but is provided for
2978 /// completeness.
2979 #[inline]
2980 pub fn from_os_str_error(&self) -> FromOsStrError {
2981 self.error
2982 }
2983
2984 /// Converts self into a [`std::io::Error`] with kind
2985 /// [`InvalidData`](io::ErrorKind::InvalidData).
2986 ///
2987 /// Many users of [`FromOsStringError`] will want to convert it into an [`io::Error`].
2988 /// This is a convenience method to do that.
2989 pub fn into_io_error(self) -> io::Error {
2990 // NOTE: we don't currently implement `From<FromOsStringError> for io::Error`
2991 // because we want to ensure the user actually desires that conversion.
2992 io::Error::new(io::ErrorKind::InvalidData, self)
2993 }
2994}
2995
2996impl fmt::Display for FromOsStringError {
2997 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2998 write!(
2999 f,
3000 "OsString contains invalid UTF-8: {}",
3001 // self.os_string.display() // this item is stable since `1.87.0`
3002 PathBuf::from(&self.os_string).display() // msrv hack
3003 )
3004 }
3005}
3006
3007impl error::Error for FromOsStringError {
3008 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
3009 Some(&self.error)
3010 }
3011}
3012
3013/// A possible error value while converting a [`OsStr`] to a [`Utf8Path`].
3014///
3015/// Produced by the `TryFrom<&OsStr>` implementation for [`&Utf8Path`](Utf8Path).
3016///
3017///
3018/// # Examples
3019///
3020/// ```
3021/// use camino::{Utf8Path, FromOsStrError};
3022/// use std::convert::{TryFrom, TryInto};
3023/// use std::ffi::OsStr;
3024/// # #[cfg(unix)]
3025/// use std::os::unix::ffi::OsStrExt;
3026///
3027/// let unicode_str = OsStr::new("/valid/unicode");
3028/// let utf8_path: &Utf8Path = unicode_str.try_into().expect("valid Unicode path succeeded");
3029///
3030/// // Paths on Unix can be non-UTF-8.
3031/// # #[cfg(unix)]
3032/// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF");
3033/// # #[cfg(unix)]
3034/// let err: FromOsStrError = <&Utf8Path>::try_from(non_unicode_str)
3035/// .expect_err("non-Unicode path failed");
3036/// ```
3037#[derive(Copy, Clone, Debug, Eq, PartialEq)]
3038pub struct FromOsStrError(());
3039
3040impl FromOsStrError {
3041 /// Converts self into a [`std::io::Error`] with kind
3042 /// [`InvalidData`](io::ErrorKind::InvalidData).
3043 ///
3044 /// Many users of [`FromOsStrError`] will want to convert it into an [`io::Error`]. This is a
3045 /// convenience method to do that.
3046 pub fn into_io_error(self) -> io::Error {
3047 // NOTE: we don't currently implement `From<FromOsStrError> for io::Error`
3048 // because we want to ensure the user actually desires that conversion.
3049 io::Error::new(io::ErrorKind::InvalidData, self)
3050 }
3051}
3052
3053impl fmt::Display for FromOsStrError {
3054 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3055 write!(f, "OsStr contains invalid UTF-8")
3056 }
3057}
3058
3059impl error::Error for FromOsStrError {
3060 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
3061 None
3062 }
3063}
3064
3065// ---
3066// AsRef impls
3067// ---
3068
3069impl AsRef<Utf8Path> for Utf8Path {
3070 #[inline]
3071 fn as_ref(&self) -> &Utf8Path {
3072 self
3073 }
3074}
3075
3076impl AsRef<Utf8Path> for Utf8PathBuf {
3077 #[inline]
3078 fn as_ref(&self) -> &Utf8Path {
3079 self.as_path()
3080 }
3081}
3082
3083impl AsRef<Utf8Path> for str {
3084 #[inline]
3085 fn as_ref(&self) -> &Utf8Path {
3086 Utf8Path::new(self)
3087 }
3088}
3089
3090impl AsRef<Utf8Path> for String {
3091 #[inline]
3092 fn as_ref(&self) -> &Utf8Path {
3093 Utf8Path::new(self)
3094 }
3095}
3096
3097impl AsRef<Path> for Utf8Path {
3098 #[inline]
3099 fn as_ref(&self) -> &Path {
3100 &self.0
3101 }
3102}
3103
3104impl AsRef<Path> for Utf8PathBuf {
3105 #[inline]
3106 fn as_ref(&self) -> &Path {
3107 &self.0
3108 }
3109}
3110
3111impl AsRef<str> for Utf8Path {
3112 #[inline]
3113 fn as_ref(&self) -> &str {
3114 self.as_str()
3115 }
3116}
3117
3118impl AsRef<str> for Utf8PathBuf {
3119 #[inline]
3120 fn as_ref(&self) -> &str {
3121 self.as_str()
3122 }
3123}
3124
3125impl AsRef<OsStr> for Utf8Path {
3126 #[inline]
3127 fn as_ref(&self) -> &OsStr {
3128 self.as_os_str()
3129 }
3130}
3131
3132impl AsRef<OsStr> for Utf8PathBuf {
3133 #[inline]
3134 fn as_ref(&self) -> &OsStr {
3135 self.as_os_str()
3136 }
3137}
3138
3139// ---
3140// Borrow and ToOwned
3141// ---
3142
3143impl Borrow<Utf8Path> for Utf8PathBuf {
3144 #[inline]
3145 fn borrow(&self) -> &Utf8Path {
3146 self.as_path()
3147 }
3148}
3149
3150impl ToOwned for Utf8Path {
3151 type Owned = Utf8PathBuf;
3152
3153 #[inline]
3154 fn to_owned(&self) -> Utf8PathBuf {
3155 self.to_path_buf()
3156 }
3157}
3158
3159impl<P: AsRef<Utf8Path>> std::iter::FromIterator<P> for Utf8PathBuf {
3160 fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> Utf8PathBuf {
3161 let mut buf = Utf8PathBuf::new();
3162 buf.extend(iter);
3163 buf
3164 }
3165}
3166
3167// ---
3168// [Partial]Eq, [Partial]Ord, Hash
3169// ---
3170
3171impl PartialEq for Utf8PathBuf {
3172 #[inline]
3173 fn eq(&self, other: &Utf8PathBuf) -> bool {
3174 self.components() == other.components()
3175 }
3176}
3177
3178impl Eq for Utf8PathBuf {}
3179
3180impl Hash for Utf8PathBuf {
3181 #[inline]
3182 fn hash<H: Hasher>(&self, state: &mut H) {
3183 self.as_path().hash(state)
3184 }
3185}
3186
3187impl PartialOrd for Utf8PathBuf {
3188 #[inline]
3189 fn partial_cmp(&self, other: &Utf8PathBuf) -> Option<Ordering> {
3190 Some(self.cmp(other))
3191 }
3192}
3193
3194impl Ord for Utf8PathBuf {
3195 fn cmp(&self, other: &Utf8PathBuf) -> Ordering {
3196 self.components().cmp(other.components())
3197 }
3198}
3199
3200impl PartialEq for Utf8Path {
3201 #[inline]
3202 fn eq(&self, other: &Utf8Path) -> bool {
3203 self.components().eq(other.components())
3204 }
3205}
3206
3207impl Eq for Utf8Path {}
3208
3209impl Hash for Utf8Path {
3210 fn hash<H: Hasher>(&self, state: &mut H) {
3211 for component in self.components() {
3212 component.hash(state)
3213 }
3214 }
3215}
3216
3217impl PartialOrd for Utf8Path {
3218 #[inline]
3219 fn partial_cmp(&self, other: &Utf8Path) -> Option<Ordering> {
3220 Some(self.cmp(other))
3221 }
3222}
3223
3224impl Ord for Utf8Path {
3225 fn cmp(&self, other: &Utf8Path) -> Ordering {
3226 self.components().cmp(other.components())
3227 }
3228}
3229
3230impl<'a> IntoIterator for &'a Utf8PathBuf {
3231 type Item = &'a str;
3232 type IntoIter = Iter<'a>;
3233 #[inline]
3234 fn into_iter(self) -> Iter<'a> {
3235 self.iter()
3236 }
3237}
3238
3239impl<'a> IntoIterator for &'a Utf8Path {
3240 type Item = &'a str;
3241 type IntoIter = Iter<'a>;
3242 #[inline]
3243 fn into_iter(self) -> Iter<'a> {
3244 self.iter()
3245 }
3246}
3247
3248macro_rules! impl_cmp {
3249 ($lhs:ty, $rhs: ty) => {
3250 #[allow(clippy::extra_unused_lifetimes)]
3251 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3252 #[inline]
3253 fn eq(&self, other: &$rhs) -> bool {
3254 <Utf8Path as PartialEq>::eq(self, other)
3255 }
3256 }
3257
3258 #[allow(clippy::extra_unused_lifetimes)]
3259 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3260 #[inline]
3261 fn eq(&self, other: &$lhs) -> bool {
3262 <Utf8Path as PartialEq>::eq(self, other)
3263 }
3264 }
3265
3266 #[allow(clippy::extra_unused_lifetimes)]
3267 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3268 #[inline]
3269 fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> {
3270 <Utf8Path as PartialOrd>::partial_cmp(self, other)
3271 }
3272 }
3273
3274 #[allow(clippy::extra_unused_lifetimes)]
3275 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3276 #[inline]
3277 fn partial_cmp(&self, other: &$lhs) -> Option<Ordering> {
3278 <Utf8Path as PartialOrd>::partial_cmp(self, other)
3279 }
3280 }
3281 };
3282}
3283
3284impl_cmp!(Utf8PathBuf, Utf8Path);
3285impl_cmp!(Utf8PathBuf, &'a Utf8Path);
3286impl_cmp!(Cow<'a, Utf8Path>, Utf8Path);
3287impl_cmp!(Cow<'a, Utf8Path>, &'b Utf8Path);
3288impl_cmp!(Cow<'a, Utf8Path>, Utf8PathBuf);
3289
3290macro_rules! impl_cmp_std_path {
3291 ($lhs:ty, $rhs: ty) => {
3292 #[allow(clippy::extra_unused_lifetimes)]
3293 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3294 #[inline]
3295 fn eq(&self, other: &$rhs) -> bool {
3296 <Path as PartialEq>::eq(self.as_ref(), other)
3297 }
3298 }
3299
3300 #[allow(clippy::extra_unused_lifetimes)]
3301 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3302 #[inline]
3303 fn eq(&self, other: &$lhs) -> bool {
3304 <Path as PartialEq>::eq(self, other.as_ref())
3305 }
3306 }
3307
3308 #[allow(clippy::extra_unused_lifetimes)]
3309 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3310 #[inline]
3311 fn partial_cmp(&self, other: &$rhs) -> Option<std::cmp::Ordering> {
3312 <Path as PartialOrd>::partial_cmp(self.as_ref(), other)
3313 }
3314 }
3315
3316 #[allow(clippy::extra_unused_lifetimes)]
3317 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3318 #[inline]
3319 fn partial_cmp(&self, other: &$lhs) -> Option<std::cmp::Ordering> {
3320 <Path as PartialOrd>::partial_cmp(self, other.as_ref())
3321 }
3322 }
3323 };
3324}
3325
3326impl_cmp_std_path!(Utf8PathBuf, Path);
3327impl_cmp_std_path!(Utf8PathBuf, &'a Path);
3328impl_cmp_std_path!(Utf8PathBuf, Cow<'a, Path>);
3329impl_cmp_std_path!(Utf8PathBuf, PathBuf);
3330impl_cmp_std_path!(Utf8Path, Path);
3331impl_cmp_std_path!(Utf8Path, &'a Path);
3332impl_cmp_std_path!(Utf8Path, Cow<'a, Path>);
3333impl_cmp_std_path!(Utf8Path, PathBuf);
3334impl_cmp_std_path!(&'a Utf8Path, Path);
3335impl_cmp_std_path!(&'a Utf8Path, Cow<'b, Path>);
3336impl_cmp_std_path!(&'a Utf8Path, PathBuf);
3337// NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117)
3338
3339macro_rules! impl_cmp_str {
3340 ($lhs:ty, $rhs: ty) => {
3341 #[allow(clippy::extra_unused_lifetimes)]
3342 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3343 #[inline]
3344 fn eq(&self, other: &$rhs) -> bool {
3345 <Utf8Path as PartialEq>::eq(self, Utf8Path::new(other))
3346 }
3347 }
3348
3349 #[allow(clippy::extra_unused_lifetimes)]
3350 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3351 #[inline]
3352 fn eq(&self, other: &$lhs) -> bool {
3353 <Utf8Path as PartialEq>::eq(Utf8Path::new(self), other)
3354 }
3355 }
3356
3357 #[allow(clippy::extra_unused_lifetimes)]
3358 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3359 #[inline]
3360 fn partial_cmp(&self, other: &$rhs) -> Option<std::cmp::Ordering> {
3361 <Utf8Path as PartialOrd>::partial_cmp(self, Utf8Path::new(other))
3362 }
3363 }
3364
3365 #[allow(clippy::extra_unused_lifetimes)]
3366 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3367 #[inline]
3368 fn partial_cmp(&self, other: &$lhs) -> Option<std::cmp::Ordering> {
3369 <Utf8Path as PartialOrd>::partial_cmp(Utf8Path::new(self), other)
3370 }
3371 }
3372 };
3373}
3374
3375impl_cmp_str!(Utf8PathBuf, str);
3376impl_cmp_str!(Utf8PathBuf, &'a str);
3377impl_cmp_str!(Utf8PathBuf, Cow<'a, str>);
3378impl_cmp_str!(Utf8PathBuf, String);
3379impl_cmp_str!(Utf8Path, str);
3380impl_cmp_str!(Utf8Path, &'a str);
3381impl_cmp_str!(Utf8Path, Cow<'a, str>);
3382impl_cmp_str!(Utf8Path, String);
3383impl_cmp_str!(&'a Utf8Path, str);
3384impl_cmp_str!(&'a Utf8Path, Cow<'b, str>);
3385impl_cmp_str!(&'a Utf8Path, String);
3386// NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117)
3387
3388macro_rules! impl_cmp_os_str {
3389 ($lhs:ty, $rhs: ty) => {
3390 #[allow(clippy::extra_unused_lifetimes)]
3391 impl<'a, 'b> PartialEq<$rhs> for $lhs {
3392 #[inline]
3393 fn eq(&self, other: &$rhs) -> bool {
3394 <Path as PartialEq>::eq(self.as_ref(), other.as_ref())
3395 }
3396 }
3397
3398 #[allow(clippy::extra_unused_lifetimes)]
3399 impl<'a, 'b> PartialEq<$lhs> for $rhs {
3400 #[inline]
3401 fn eq(&self, other: &$lhs) -> bool {
3402 <Path as PartialEq>::eq(self.as_ref(), other.as_ref())
3403 }
3404 }
3405
3406 #[allow(clippy::extra_unused_lifetimes)]
3407 impl<'a, 'b> PartialOrd<$rhs> for $lhs {
3408 #[inline]
3409 fn partial_cmp(&self, other: &$rhs) -> Option<std::cmp::Ordering> {
3410 <Path as PartialOrd>::partial_cmp(self.as_ref(), other.as_ref())
3411 }
3412 }
3413
3414 #[allow(clippy::extra_unused_lifetimes)]
3415 impl<'a, 'b> PartialOrd<$lhs> for $rhs {
3416 #[inline]
3417 fn partial_cmp(&self, other: &$lhs) -> Option<std::cmp::Ordering> {
3418 <Path as PartialOrd>::partial_cmp(self.as_ref(), other.as_ref())
3419 }
3420 }
3421 };
3422}
3423
3424impl_cmp_os_str!(Utf8PathBuf, OsStr);
3425impl_cmp_os_str!(Utf8PathBuf, &'a OsStr);
3426impl_cmp_os_str!(Utf8PathBuf, Cow<'a, OsStr>);
3427impl_cmp_os_str!(Utf8PathBuf, OsString);
3428impl_cmp_os_str!(Utf8Path, OsStr);
3429impl_cmp_os_str!(Utf8Path, &'a OsStr);
3430impl_cmp_os_str!(Utf8Path, Cow<'a, OsStr>);
3431impl_cmp_os_str!(Utf8Path, OsString);
3432impl_cmp_os_str!(&'a Utf8Path, OsStr);
3433impl_cmp_os_str!(&'a Utf8Path, Cow<'b, OsStr>);
3434impl_cmp_os_str!(&'a Utf8Path, OsString);
3435// NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117)
3436
3437/// Makes the path absolute without accessing the filesystem, converting it to a [`Utf8PathBuf`].
3438///
3439/// If the path is relative, the current directory is used as the base directory. All intermediate
3440/// components will be resolved according to platform-specific rules, but unlike
3441/// [`canonicalize`][Utf8Path::canonicalize] or [`canonicalize_utf8`](Utf8Path::canonicalize_utf8),
3442/// this does not resolve symlinks and may succeed even if the path does not exist.
3443///
3444/// *Requires Rust 1.79 or newer.*
3445///
3446/// # Errors
3447///
3448/// Errors if:
3449///
3450/// * The path is empty.
3451/// * The [current directory][std::env::current_dir] cannot be determined.
3452/// * The path is not valid UTF-8.
3453///
3454/// # Examples
3455///
3456/// ## POSIX paths
3457///
3458/// ```
3459/// # #[cfg(unix)]
3460/// fn main() -> std::io::Result<()> {
3461/// use camino::Utf8Path;
3462///
3463/// // Relative to absolute
3464/// let absolute = camino::absolute_utf8("foo/./bar")?;
3465/// assert!(absolute.ends_with("foo/bar"));
3466///
3467/// // Absolute to absolute
3468/// let absolute = camino::absolute_utf8("/foo//test/.././bar.rs")?;
3469/// assert_eq!(absolute, Utf8Path::new("/foo/test/../bar.rs"));
3470/// Ok(())
3471/// }
3472/// # #[cfg(not(unix))]
3473/// # fn main() {}
3474/// ```
3475///
3476/// The path is resolved using [POSIX semantics][posix-semantics] except that it stops short of
3477/// resolving symlinks. This means it will keep `..` components and trailing slashes.
3478///
3479/// ## Windows paths
3480///
3481/// ```
3482/// # #[cfg(windows)]
3483/// fn main() -> std::io::Result<()> {
3484/// use camino::Utf8Path;
3485///
3486/// // Relative to absolute
3487/// let absolute = camino::absolute_utf8("foo/./bar")?;
3488/// assert!(absolute.ends_with(r"foo\bar"));
3489///
3490/// // Absolute to absolute
3491/// let absolute = camino::absolute_utf8(r"C:\foo//test\..\./bar.rs")?;
3492///
3493/// assert_eq!(absolute, Utf8Path::new(r"C:\foo\bar.rs"));
3494/// Ok(())
3495/// }
3496/// # #[cfg(not(windows))]
3497/// # fn main() {}
3498/// ```
3499///
3500/// For verbatim paths this will simply return the path as given. For other paths this is currently
3501/// equivalent to calling [`GetFullPathNameW`][windows-path].
3502///
3503/// Note that this [may change in the future][changes].
3504///
3505/// [changes]: io#platform-specific-behavior
3506/// [posix-semantics]:
3507/// https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
3508/// [windows-path]:
3509/// https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew
3510#[cfg(absolute_path)]
3511pub fn absolute_utf8<P: AsRef<Path>>(path: P) -> io::Result<Utf8PathBuf> {
3512 // Note that even if the passed in path is valid UTF-8, it is not guaranteed
3513 // that the absolute path will be valid UTF-8. For example, the current
3514 // directory may not be valid UTF-8.
3515 //
3516 // That's why we take `AsRef<Path>` instead of `AsRef<Utf8Path>` here -- we
3517 // have to pay the cost of checking for valid UTF-8 anyway.
3518 let path = path.as_ref();
3519 #[allow(clippy::incompatible_msrv)]
3520 Utf8PathBuf::try_from(std::path::absolute(path)?).map_err(|error| error.into_io_error())
3521}
3522
3523// invariant: OsStr must be guaranteed to be utf8 data
3524#[inline]
3525unsafe fn str_assume_utf8(string: &OsStr) -> &str {
3526 #[cfg(os_str_bytes)]
3527 {
3528 // SAFETY: OsStr is guaranteed to be utf8 data from the invariant
3529 unsafe {
3530 std::str::from_utf8_unchecked(
3531 #[allow(clippy::incompatible_msrv)]
3532 string.as_encoded_bytes(),
3533 )
3534 }
3535 }
3536 #[cfg(not(os_str_bytes))]
3537 {
3538 // Adapted from the source code for Option::unwrap_unchecked.
3539 match string.to_str() {
3540 Some(val) => val,
3541 None => std::hint::unreachable_unchecked(),
3542 }
3543 }
3544}