From 7218892c722ca583297c0ebbda350bdf6f16d3ce Mon Sep 17 00:00:00 2001 From: Laurenz Date: Tue, 1 Jun 2021 12:46:01 +0200 Subject: Refactor path handling --- src/util.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'src/util.rs') diff --git a/src/util.rs b/src/util.rs index 72db4518..8a8c04b6 100644 --- a/src/util.rs +++ b/src/util.rs @@ -2,6 +2,7 @@ use std::cmp::Ordering; use std::ops::Range; +use std::path::{Component, Path, PathBuf}; /// Additional methods for slices. pub trait SliceExt { @@ -79,3 +80,28 @@ impl RangeExt for Range { } } } + +/// Additional methods for [`Path`]. +pub trait PathExt { + /// Lexically normalize a path. + fn normalize(&self) -> PathBuf; +} + +impl PathExt for Path { + fn normalize(&self) -> PathBuf { + let mut out = PathBuf::new(); + for component in self.components() { + match component { + Component::CurDir => {} + Component::ParentDir => match out.components().next_back() { + Some(Component::Normal(_)) => { + out.pop(); + } + _ => out.push(component), + }, + _ => out.push(component), + } + } + out + } +} -- cgit v1.2.3