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