path-dedot-3.1.1/.cargo_vcs_info.json0000644000000001360000000000100130670ustar { "git": { "sha1": "36c197f922d4c8779594ce25b8ffc6cb0315c6a8" }, "path_in_vcs": "" }path-dedot-3.1.1/Cargo.toml0000644000000025700000000000100110710ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.60" name = "path-dedot" version = "3.1.1" authors = ["Magic Len "] include = [ "src/**/*", "Cargo.toml", "README.md", "LICENSE", "benches/bench.rs", ] description = "A library for extending `Path` and `PathBuf` in order to parse the path which contains dots." homepage = "https://magiclen.org/path-dedot" readme = "README.md" keywords = [ "path", "dot", "dedot", "absolute", "canonical", ] categories = [ "parser-implementations", "filesystem", ] license = "MIT" repository = "https://github.com/magiclen/path-dedot" [[bench]] name = "bench" harness = false [dependencies.lazy_static] version = "1.4" optional = true [dependencies.once_cell] version = "1.4" [dev-dependencies.bencher] version = "0.1.5" [features] lazy_static_cache = ["lazy_static"] once_cell_cache = [] unsafe_cache = [] use_unix_paths_on_wasm = [] path-dedot-3.1.1/Cargo.toml.orig000064400000000000000000000014761046102023000145560ustar 00000000000000[package] name = "path-dedot" version = "3.1.1" authors = ["Magic Len "] edition = "2021" rust-version = "1.60" repository = "https://github.com/magiclen/path-dedot" homepage = "https://magiclen.org/path-dedot" keywords = ["path", "dot", "dedot", "absolute", "canonical"] categories = ["parser-implementations", "filesystem"] description = "A library for extending `Path` and `PathBuf` in order to parse the path which contains dots." license = "MIT" include = ["src/**/*", "Cargo.toml", "README.md", "LICENSE", "benches/bench.rs"] [dependencies] once_cell = "1.4" lazy_static = { version = "1.4", optional = true } [dev-dependencies] bencher = "0.1.5" [features] once_cell_cache = [] lazy_static_cache = ["lazy_static"] unsafe_cache = [] use_unix_paths_on_wasm = [] [[bench]] name = "bench" harness = false path-dedot-3.1.1/LICENSE000064400000000000000000000020661046102023000126700ustar 00000000000000MIT License Copyright (c) 2018 magiclen.org (Ron Li) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. path-dedot-3.1.1/README.md000064400000000000000000000130111046102023000131320ustar 00000000000000Path Dedot ==================== [![CI](https://github.com/magiclen/path-dedot/actions/workflows/ci.yml/badge.svg)](https://github.com/magiclen/path-dedot/actions/workflows/ci.yml) This is a library for extending `Path` and `PathBuf` in order to parse the path which contains dots. Please read the following examples to know the parsing rules. ## Examples If a path starts with a single dot, the dot means your program's **current working directory** (CWD). ```rust use std::path::Path; use std::env; use path_dedot::*; let p = Path::new("./path/to/123/456"); assert_eq!(Path::join(env::current_dir().unwrap().as_path(), Path::new("path/to/123/456")).to_str().unwrap(), p.parse_dot().unwrap().to_str().unwrap()); ``` If a path starts with a pair of dots, the dots means the parent of the CWD. If the CWD is **root**, the parent is still **root**. ```rust use std::path::Path; use std::env; use path_dedot::*; let p = Path::new("../path/to/123/456"); let cwd = env::current_dir().unwrap(); let cwd_parent = cwd.parent(); match cwd_parent { Some(cwd_parent) => { assert_eq!(Path::join(&cwd_parent, Path::new("path/to/123/456")).to_str().unwrap(), p.parse_dot().unwrap().to_str().unwrap()); } None => { assert_eq!(Path::join(Path::new("/"), Path::new("path/to/123/456")).to_str().unwrap(), p.parse_dot().unwrap().to_str().unwrap()); } } ``` In addition to starting with, the **Single Dot** and **Double Dots** can also be placed to other positions. **Single Dot** means noting and will be ignored. **Double Dots** means the parent. ```rust use std::path::Path; use path_dedot::*; let p = Path::new("/path/to/../123/456/./777"); assert_eq!("/path/123/456/777", p.parse_dot().unwrap().to_str().unwrap()); ``` ```rust use std::path::Path; use path_dedot::*; let p = Path::new("/path/to/../123/456/./777/.."); assert_eq!("/path/123/456", p.parse_dot().unwrap().to_str().unwrap()); ``` You should notice that `parse_dot` method does **not** aim to get an **absolute path**. A path which does not start with a `MAIN_SEPARATOR`, **Single Dot** and **Double Dots**, will not have each of them after the `parse_dot` method is used. ```rust use std::path::Path; use path_dedot::*; let p = Path::new("path/to/../123/456/./777/.."); assert_eq!("path/123/456", p.parse_dot().unwrap().to_str().unwrap()); ``` **Double Dots** which is not placed at the start cannot get the parent beyond the original path. Why not? With this constraint, you can insert an absolute path to the start as a virtual root in order to protect your file system from being exposed. ```rust use std::path::Path; use path_dedot::*; let p = Path::new("path/to/../../../../123/456/./777/.."); assert_eq!("123/456", p.parse_dot().unwrap().to_str().unwrap()); ``` ```rust use std::path::Path; use path_dedot::*; let p = Path::new("/path/to/../../../../123/456/./777/.."); assert_eq!("/123/456", p.parse_dot().unwrap().to_str().unwrap()); ``` ### Starting from a given current working directory With the `parse_dot_from` function, you can provide the current working directory that the relative paths should be resolved from. ```rust use std::env; use std::path::Path; use path_dedot::*; let p = Path::new("../path/to/123/456"); let cwd = env::current_dir().unwrap(); println!("{}", p.parse_dot_from(cwd).unwrap().to_str().unwrap()); ``` ## Caching By default, the `parse_dot` method creates a new `PathBuf` instance of the CWD every time in its operation. The overhead is obvious. Although it allows us to safely change the CWD at runtime by the program itself (e.g. using the `std::env::set_current_dir` function) or outside controls (e.g. using gdb to call `chdir`), we don't need that in most cases. In order to parse paths with better performance, this crate provides three ways to cache the CWD. ### once_cell_cache Enabling the `once_cell_cache` feature can let this crate use `once_cell` to cache the CWD. It's thread-safe and does not need to modify any code, but once the CWD is cached, it cannot be changed anymore at runtime. ```toml [dependencies.path-dedot] version = "*" features = ["once_cell_cache"] ``` ### lazy_static_cache Enabling the `lazy_static_cache` feature can let this crate use `lazy_static` to cache the CWD. It's thread-safe and does not need to modify any code, but once the CWD is cached, it cannot be changed anymore at runtime. ```toml [dependencies.path-dedot] version = "*" features = ["lazy_static_cache"] ``` ### unsafe_cache Enabling the `unsafe_cache` feature can let this crate use a mutable static variable to cache the CWD. It allows the program to change the CWD at runtime by the program itself, but it's not thread-safe. You need to use the `update_cwd` function to initialize the CWD first. The function should also be used to update the CWD after the CWD is changed. ```toml [dependencies.path-dedot] version = "*" features = ["unsafe_cache"] ``` ```rust use std::path::Path; use path_dedot::*; unsafe { update_cwd(); } let p = Path::new("./path/to/123/456"); println!("{}", p.parse_dot().unwrap().to_str().unwrap()); std::env::set_current_dir("/").unwrap(); unsafe { update_cwd(); } println!("{}", p.parse_dot().unwrap().to_str().unwrap()); ``` ## Benchmark #### No-cache ```bash cargo bench ``` #### once_cell_cache ```bash cargo bench --features once_cell_cache ``` #### lazy_static_cache ```bash cargo bench --features lazy_static_cache ``` #### unsafe_cache ```bash cargo bench --features unsafe_cache ``` ## Crates.io https://crates.io/crates/path-dedot ## Documentation https://docs.rs/path-dedot ## License [MIT](LICENSE)path-dedot-3.1.1/benches/bench.rs000064400000000000000000000021531046102023000147140ustar 00000000000000use std::path::Path; use bencher::{benchmark_group, benchmark_main, Bencher}; use path_dedot::ParseDot; fn no_dots(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_dedot::update_cwd() }; let path = Path::new("path/to/123/456"); bencher.iter(|| path.parse_dot()); } fn starts_with_a_single_dot(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_dedot::update_cwd() }; let path = Path::new("./path/to/123/456"); bencher.iter(|| path.parse_dot()); } fn starts_with_double_dots(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_dedot::update_cwd() }; let path = Path::new("../path/to/123/456"); bencher.iter(|| path.parse_dot()); } fn mix(bencher: &mut Bencher) { #[cfg(feature = "unsafe_cache")] unsafe { path_dedot::update_cwd() }; let path = Path::new("./path/to/123/../456"); bencher.iter(|| path.parse_dot()); } benchmark_group!(bench_group, no_dots, starts_with_a_single_dot, starts_with_double_dots, mix); benchmark_main!(bench_group); path-dedot-3.1.1/src/lib.rs000064400000000000000000000205441046102023000135670ustar 00000000000000/*! # Path Dedot This is a library for extending `Path` and `PathBuf` in order to parse the path which contains dots. Please read the following examples to know the parsing rules. ## Examples If a path starts with a single dot, the dot means your program's **current working directory** (CWD). ```rust use std::path::Path; use std::env; use path_dedot::*; let p = Path::new("./path/to/123/456"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!(Path::join(env::current_dir().unwrap().as_path(), Path::new("path/to/123/456")).to_str().unwrap(), p.parse_dot().unwrap().to_str().unwrap()); # } ``` If a path starts with a pair of dots, the dots means the parent of the CWD. If the CWD is **root**, the parent is still **root**. ```rust use std::path::Path; use std::env; use path_dedot::*; let p = Path::new("../path/to/123/456"); let cwd = env::current_dir().unwrap(); let cwd_parent = cwd.parent(); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } match cwd_parent { Some(cwd_parent) => { assert_eq!(Path::join(&cwd_parent, Path::new("path/to/123/456")).to_str().unwrap(), p.parse_dot().unwrap().to_str().unwrap()); } None => { assert_eq!(Path::join(Path::new("/"), Path::new("path/to/123/456")).to_str().unwrap(), p.parse_dot().unwrap().to_str().unwrap()); } } # } ``` In addition to starting with, the **Single Dot** and **Double Dots** can also be placed to other positions. **Single Dot** means noting and will be ignored. **Double Dots** means the parent. ```rust use std::path::Path; use path_dedot::*; let p = Path::new("/path/to/../123/456/./777"); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("/path/123/456/777", p.parse_dot().unwrap().to_str().unwrap()); # } ``` ```rust use std::path::Path; use path_dedot::*; let p = Path::new("/path/to/../123/456/./777/.."); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("/path/123/456", p.parse_dot().unwrap().to_str().unwrap()); # } ``` You should notice that `parse_dot` method does **not** aim to get an **absolute path**. A path which does not start with a `MAIN_SEPARATOR`, **Single Dot** and **Double Dots**, will not have each of them after the `parse_dot` method is used. ```rust use std::path::Path; use path_dedot::*; let p = Path::new("path/to/../123/456/./777/.."); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("path/123/456", p.parse_dot().unwrap().to_str().unwrap()); # } ``` **Double Dots** which is not placed at the start cannot get the parent beyond the original path. Why not? With this constraint, you can insert an absolute path to the start as a virtual root in order to protect your file system from being exposed. ```rust use std::path::Path; use path_dedot::*; let p = Path::new("path/to/../../../../123/456/./777/.."); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("123/456", p.parse_dot().unwrap().to_str().unwrap()); # } ``` ```rust use std::path::Path; use path_dedot::*; let p = Path::new("/path/to/../../../../123/456/./777/.."); # if cfg!(unix) { # #[cfg(feature = "unsafe_cache")] # { # unsafe { # update_cwd(); # } # } assert_eq!("/123/456", p.parse_dot().unwrap().to_str().unwrap()); # } ``` ### Starting from a given current working directory With the `parse_dot_from` function, you can provide the current working directory that the relative paths should be resolved from. ```rust use std::env; use std::path::Path; use path_dedot::*; let p = Path::new("../path/to/123/456"); let cwd = env::current_dir().unwrap(); println!("{}", p.parse_dot_from(cwd).unwrap().to_str().unwrap()); ``` ## Caching By default, the `parse_dot` method creates a new `PathBuf` instance of the CWD every time in its operation. The overhead is obvious. Although it allows us to safely change the CWD at runtime by the program itself (e.g. using the `std::env::set_current_dir` function) or outside controls (e.g. using gdb to call `chdir`), we don't need that in most cases. In order to parse paths with better performance, this crate provides three ways to cache the CWD. ### once_cell_cache Enabling the `once_cell_cache` feature can let this crate use `once_cell` to cache the CWD. It's thread-safe and does not need to modify any code, but once the CWD is cached, it cannot be changed anymore at runtime. ```toml [dependencies.path-dedot] version = "*" features = ["once_cell_cache"] ``` ### lazy_static_cache Enabling the `lazy_static_cache` feature can let this crate use `lazy_static` to cache the CWD. It's thread-safe and does not need to modify any code, but once the CWD is cached, it cannot be changed anymore at runtime. ```toml [dependencies.path-dedot] version = "*" features = ["lazy_static_cache"] ``` ### unsafe_cache Enabling the `unsafe_cache` feature can let this crate use a mutable static variable to cache the CWD. It allows the program to change the CWD at runtime by the program itself, but it's not thread-safe. You need to use the `update_cwd` function to initialize the CWD first. The function should also be used to update the CWD after the CWD is changed. ```toml [dependencies.path-dedot] version = "*" features = ["unsafe_cache"] ``` ```rust use std::path::Path; use path_dedot::*; # #[cfg(feature = "unsafe_cache")] unsafe { update_cwd(); } let p = Path::new("./path/to/123/456"); println!("{}", p.parse_dot().unwrap().to_str().unwrap()); std::env::set_current_dir("/").unwrap(); # #[cfg(feature = "unsafe_cache")] unsafe { update_cwd(); } println!("{}", p.parse_dot().unwrap().to_str().unwrap()); ``` ## Benchmark #### No-cache ```bash cargo bench ``` #### once_cell_cache ```bash cargo bench --features once_cell_cache ``` #### lazy_static_cache ```bash cargo bench --features lazy_static_cache ``` #### unsafe_cache ```bash cargo bench --features unsafe_cache ``` */ #[cfg(any( all(feature = "lazy_static_cache", feature = "unsafe_cache"), all(feature = "once_cell_cache", feature = "unsafe_cache"), all(feature = "lazy_static_cache", feature = "once_cell_cache") ))] compile_error!("You can only enable at most one caching mechanism for `path-dedot`."); #[cfg(feature = "lazy_static_cache")] #[macro_use] extern crate lazy_static; #[cfg(not(feature = "lazy_static_cache"))] extern crate once_cell; use std::{ borrow::Cow, ffi::OsString, io, path::{self, Path, PathBuf}, }; mod parse_dot; #[macro_use] mod macros; #[cfg(any(unix, all(target_family = "wasm", feature = "use_unix_paths_on_wasm")))] mod unix; #[cfg(windows)] mod windows; #[cfg(feature = "unsafe_cache")] mod unsafe_cwd; #[cfg(not(feature = "lazy_static_cache"))] use once_cell::sync::Lazy; pub use parse_dot::*; #[cfg(windows)] pub use windows::ParsePrefix; #[cfg(not(feature = "lazy_static_cache"))] /// The main separator for the target OS. pub static MAIN_SEPARATOR: Lazy = Lazy::new(|| OsString::from(path::MAIN_SEPARATOR.to_string())); #[cfg(feature = "lazy_static_cache")] lazy_static! { /// Current working directory. pub static ref MAIN_SEPARATOR: OsString = OsString::from(path::MAIN_SEPARATOR.to_string()); } impl ParseDot for PathBuf { #[inline] fn parse_dot(&self) -> io::Result> { self.as_path().parse_dot() } #[inline] fn parse_dot_from(&self, cwd: impl AsRef) -> io::Result> { self.as_path().parse_dot_from(cwd) } } #[cfg(feature = "once_cell_cache")] /// Current working directory. pub static CWD: Lazy = Lazy::new(|| std::env::current_dir().unwrap()); #[cfg(feature = "lazy_static_cache")] lazy_static! { /// Current working directory. pub static ref CWD: PathBuf = std::env::current_dir().unwrap(); } #[cfg(feature = "unsafe_cache")] /// Current working directory. pub static mut CWD: unsafe_cwd::UnsafeCWD = unsafe_cwd::UnsafeCWD::new(); #[cfg(feature = "unsafe_cache")] /// Initialize or update the CWD cached in the `path-dedot` crate after using the `std::env::set_current_dir` function. It is not a safe operation. Make sure there is no `parse_dot` method running at this moment. #[allow(clippy::missing_safety_doc)] pub unsafe fn update_cwd() { CWD.update(); } path-dedot-3.1.1/src/macros.rs000064400000000000000000000007141046102023000143020ustar 00000000000000#[cfg(not(any( feature = "once_cell_cache", feature = "lazy_static_cache", feature = "unsafe_cache" )))] macro_rules! get_cwd { () => { std::env::current_dir()? }; } #[cfg(any(feature = "once_cell_cache", feature = "lazy_static_cache"))] macro_rules! get_cwd { () => { $crate::CWD.as_path() }; } #[cfg(feature = "unsafe_cache")] macro_rules! get_cwd { () => { unsafe { $crate::CWD.as_path() } }; } path-dedot-3.1.1/src/parse_dot.rs000064400000000000000000000007231046102023000147760ustar 00000000000000use std::{borrow::Cow, io, path::Path}; /// Let `Path` and `PathBuf` have `parse_dot` method. pub trait ParseDot { /// Remove dots in the path and create a new `PathBuf` instance on demand. fn parse_dot(&self) -> io::Result>; /// Remove dots in the path and create a new `PathBuf` instance on demand. It gets the current working directory as the second argument. fn parse_dot_from(&self, cwd: impl AsRef) -> io::Result>; } path-dedot-3.1.1/src/unix.rs000064400000000000000000000077741046102023000140160ustar 00000000000000use std::{ borrow::Cow, ffi::OsString, io, path::{Component, Path, PathBuf}, }; use crate::{ParseDot, MAIN_SEPARATOR}; impl ParseDot for Path { #[inline] fn parse_dot(&self) -> io::Result> { let cwd = get_cwd!(); self.parse_dot_from(cwd) } fn parse_dot_from(&self, cwd: impl AsRef) -> io::Result> { let mut iter = self.components(); let mut has_dots = false; if let Some(first_component) = iter.next() { let mut tokens = Vec::new(); let first_is_root = match first_component { Component::RootDir => { tokens.push(MAIN_SEPARATOR.as_os_str()); true }, Component::CurDir => { has_dots = true; let cwd = cwd.as_ref(); for token in cwd.iter() { tokens.push(token); } !tokens.is_empty() && tokens[0] == MAIN_SEPARATOR.as_os_str() }, Component::ParentDir => { has_dots = true; let cwd = cwd.as_ref(); match cwd.parent() { Some(cwd_parent) => { for token in cwd_parent.iter() { tokens.push(token); } !tokens.is_empty() && tokens[0] == MAIN_SEPARATOR.as_os_str() }, None => { // don't care about `cwd` is "//" or "///" if cwd == MAIN_SEPARATOR.as_os_str() { tokens.push(MAIN_SEPARATOR.as_os_str()); true } else { false } }, } }, _ => { tokens.push(first_component.as_os_str()); false }, }; for component in iter { match component { Component::CurDir => { // may be unreachable has_dots = true; }, Component::ParentDir => { let tokens_length = tokens.len(); if tokens_length > 0 && (tokens_length != 1 || !first_is_root) { tokens.remove(tokens_length - 1); } has_dots = true; }, _ => { tokens.push(component.as_os_str()); }, } } let tokens_length = tokens.len(); debug_assert!(tokens_length > 0); let mut size = tokens.iter().fold(tokens_length - 1, |acc, &x| acc + x.len()); if first_is_root && tokens_length > 1 { size -= 1; } if has_dots || size != self.as_os_str().len() { let mut path_string = OsString::with_capacity(size); let mut iter = tokens.iter(); path_string.push(iter.next().unwrap()); if tokens_length > 1 { if !first_is_root { path_string.push(MAIN_SEPARATOR.as_os_str()); } for token in iter.take(tokens_length - 2) { path_string.push(token); path_string.push(MAIN_SEPARATOR.as_os_str()); } path_string.push(tokens[tokens_length - 1]); } let path_buf = PathBuf::from(path_string); Ok(Cow::from(path_buf)) } else { Ok(Cow::from(self)) } } else { Ok(Cow::from(self)) } } } path-dedot-3.1.1/src/unsafe_cwd.rs000064400000000000000000000013121046102023000151270ustar 00000000000000use std::{env, ops::Deref, path::PathBuf}; /// Current working directory. #[doc(hidden)] pub struct UnsafeCWD { path: Option, } impl UnsafeCWD { #[inline] pub(crate) const fn new() -> UnsafeCWD { UnsafeCWD { path: None } } #[inline] pub(crate) fn update(&mut self) { let cwd = env::current_dir().unwrap(); self.path.replace(cwd); } #[inline] #[doc(hidden)] pub fn initial(&mut self) { if self.path.is_none() { self.update(); } } } impl Deref for UnsafeCWD { type Target = PathBuf; #[inline] fn deref(&self) -> &Self::Target { self.path.as_ref().unwrap() } } path-dedot-3.1.1/src/windows.rs000064400000000000000000000303341046102023000145110ustar 00000000000000use std::{ borrow::Cow, ffi::OsString, io::{self, ErrorKind}, path::{Component, Path, PathBuf, PrefixComponent}, }; use crate::{ParseDot, MAIN_SEPARATOR}; impl ParseDot for Path { #[inline] fn parse_dot(&self) -> io::Result> { let cwd = get_cwd!(); self.parse_dot_from(&cwd) } fn parse_dot_from(&self, cwd: impl AsRef) -> io::Result> { let mut iter = self.components(); let mut has_dots = false; if let Some(first_component) = iter.next() { let mut tokens = Vec::new(); let (has_prefix, first_is_root) = match first_component { Component::Prefix(prefix) => { tokens.push(prefix.as_os_str()); if let Some(second_component) = iter.next() { match second_component { Component::RootDir => { tokens.push(MAIN_SEPARATOR.as_os_str()); (true, true) }, Component::CurDir => { // may be unreachable has_dots = true; let cwd = cwd.as_ref(); for token in cwd.iter().skip(if cwd.get_path_prefix().is_some() { 1 } else { 0 }) { tokens.push(token); } (true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str()) }, Component::ParentDir => { has_dots = true; let cwd = cwd.as_ref(); match cwd.parent() { Some(cwd_parent) => { for token in cwd_parent.iter().skip( if cwd.get_path_prefix().is_some() { 1 } else { 0 }, ) { tokens.push(token); } ( true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str(), ) }, None => { if cwd.get_path_prefix().is_some() { if cwd.is_absolute() { tokens.push(MAIN_SEPARATOR.as_os_str()); (true, true) } else { (true, false) } } else { // don't care about `cwd` is "\\" or "\\\" if cwd == MAIN_SEPARATOR.as_os_str() { tokens.push(MAIN_SEPARATOR.as_os_str()); (true, true) } else { (true, false) } } }, } }, _ => { let path_str = self.as_os_str().to_str().ok_or_else(|| { io::Error::new(ErrorKind::Other, "The path is not valid UTF-8.") })?; if path_str[first_component.as_os_str().len()..].starts_with(r".\") { has_dots = true; let out = { let cwd = cwd.as_ref(); for token in cwd.iter().skip( if cwd.get_path_prefix().is_some() { 1 } else { 0 }, ) { tokens.push(token); } ( true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str(), ) }; tokens.push(second_component.as_os_str()); out } else { tokens.push(second_component.as_os_str()); (true, false) } }, } } else { (true, false) } }, Component::RootDir => { tokens.push(MAIN_SEPARATOR.as_os_str()); (false, true) }, Component::CurDir => { has_dots = true; let cwd = cwd.as_ref(); for token in cwd.iter() { tokens.push(token); } if cwd.get_path_prefix().is_some() { (true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str()) } else { (false, !tokens.is_empty() && tokens[0] == MAIN_SEPARATOR.as_os_str()) } }, Component::ParentDir => { has_dots = true; let cwd = cwd.as_ref(); match cwd.parent() { Some(cwd_parent) => { for token in cwd_parent.iter() { tokens.push(token); } if cwd.get_path_prefix().is_some() { (true, tokens.len() > 1 && tokens[1] == MAIN_SEPARATOR.as_os_str()) } else { ( false, !tokens.is_empty() && tokens[0] == MAIN_SEPARATOR.as_os_str(), ) } }, None => match cwd.get_path_prefix() { Some(prefix) => { tokens.push(prefix.as_os_str()); if cwd.is_absolute() { tokens.push(MAIN_SEPARATOR.as_os_str()); (true, true) } else { (true, false) } }, None => { // don't care about `cwd` is "\\" or "\\\" if cwd == MAIN_SEPARATOR.as_os_str() { tokens.push(MAIN_SEPARATOR.as_os_str()); (false, true) } else { (false, false) } }, }, } }, Component::Normal(token) => { tokens.push(token); (false, false) }, }; for component in iter { match component { Component::CurDir => { // may be unreachable has_dots = true; }, Component::ParentDir => { let tokens_length = tokens.len(); if tokens_length > 0 && ((tokens_length != 1 || (!first_is_root && !has_prefix)) && (tokens_length != 2 || !(first_is_root && has_prefix))) { tokens.remove(tokens_length - 1); } has_dots = true; }, _ => { tokens.push(component.as_os_str()); }, } } let tokens_length = tokens.len(); debug_assert!(tokens_length > 0); let mut size = tokens.iter().fold(tokens_length - 1, |acc, &x| acc + x.len()); if has_prefix { if tokens_length > 1 { size -= 1; if first_is_root { if tokens_length > 2 { size -= 1; } else if tokens[0].len() == self.as_os_str().len() { // tokens_length == 2 // e.g. // `\\server\share\` -> `\\server\share\` // `\\server\share` -> `\\server\share\` should still be `\\server\share` return Ok(Cow::from(self)); } } } } else if first_is_root && tokens_length > 1 { size -= 1; } if has_dots || size != self.as_os_str().len() { let mut path_string = OsString::with_capacity(size); let mut iter = tokens.iter(); path_string.push(iter.next().unwrap()); if tokens_length > 1 { if has_prefix { if let Some(token) = iter.next() { path_string.push(token); if tokens_length > 2 { if !first_is_root { path_string.push(MAIN_SEPARATOR.as_os_str()); } for token in iter.take(tokens_length - 3) { path_string.push(token); path_string.push(MAIN_SEPARATOR.as_os_str()); } path_string.push(tokens[tokens_length - 1]); } } } else { if !first_is_root { path_string.push(MAIN_SEPARATOR.as_os_str()); } for token in iter.take(tokens_length - 2) { path_string.push(token); path_string.push(MAIN_SEPARATOR.as_os_str()); } path_string.push(tokens[tokens_length - 1]); } } let path_buf = PathBuf::from(path_string); Ok(Cow::from(path_buf)) } else { Ok(Cow::from(self)) } } else { Ok(Cow::from(self)) } } } pub trait ParsePrefix { fn get_path_prefix(&self) -> Option; } impl ParsePrefix for Path { #[inline] fn get_path_prefix(&self) -> Option { match self.components().next() { Some(Component::Prefix(prefix_component)) => Some(prefix_component), _ => None, } } } impl ParsePrefix for PathBuf { #[inline] fn get_path_prefix(&self) -> Option { self.as_path().get_path_prefix() } }