From 68cae57f16c8b6176fbd9e9283ee9babd9ad00fc Mon Sep 17 00:00:00 2001 From: Tom Alexander Date: Mon, 23 Oct 2023 22:50:43 -0400 Subject: [PATCH] Add a function to get the shared portion of a path. --- src/blog_post/convert.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/blog_post/convert.rs b/src/blog_post/convert.rs index 8a03dd6..63a9fa2 100644 --- a/src/blog_post/convert.rs +++ b/src/blog_post/convert.rs @@ -1,3 +1,4 @@ +use std::path::Component; use std::path::Path; use std::path::PathBuf; @@ -92,6 +93,17 @@ fn count_shared_steps, B: AsRef>(left: A, right: B) -> usiz .unwrap_or_else(|| left.components().count()) } +#[allow(dead_code)] +fn get_shared_steps<'a>(left: &'a Path, right: &'a Path) -> impl Iterator> { + let foo: Vec> = left + .components() + .zip(right.components()) + .take_while(|(l, r)| l == r) + .map(|(l, _r)| l) + .collect(); + foo.into_iter() +} + #[cfg(test)] mod tests { use super::*; @@ -106,4 +118,29 @@ mod tests { 2 ); } + + #[test] + fn test_get_shared_steps() { + assert_eq!( + get_shared_steps(Path::new(""), Path::new("")).collect::(), + PathBuf::from("") + ); + assert_eq!( + get_shared_steps(Path::new("foo.txt"), Path::new("foo.txt")).collect::(), + PathBuf::from("foo.txt") + ); + assert_eq!( + get_shared_steps(Path::new("cat/foo.txt"), Path::new("dog/foo.txt")) + .collect::(), + PathBuf::from("") + ); + assert_eq!( + get_shared_steps( + Path::new("foo/bar/baz/lorem.txt"), + Path::new("foo/bar/ipsum/dolar.txt") + ) + .collect::(), + PathBuf::from("foo/bar") + ); + } }