diff --git a/library/std/src/env.rs b/library/std/src/env.rs index 1f0ced5d0fd0d..56564a251038b 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -456,6 +456,9 @@ pub struct SplitPaths<'a> { /// On most Unix platforms, the separator is `:` and on Windows it is `;`. This /// also performs unquoting on Windows. /// +/// On Unix systems an empty path corresponds to the current working directory +/// and on Windows systems an empty path is disregarded. +/// /// [`join_paths`] can be used to recombine elements. /// /// # Panics diff --git a/library/std/src/sys/pal/windows/os.rs b/library/std/src/sys/pal/windows/os.rs index 3eb6ec8278401..2638e02d02de3 100644 --- a/library/std/src/sys/pal/windows/os.rs +++ b/library/std/src/sys/pal/windows/os.rs @@ -45,7 +45,7 @@ impl<'a> Iterator for SplitPaths<'a> { let mut in_progress = Vec::new(); let mut in_quote = false; - for b in self.data.by_ref() { + for b in self.data.by_ref().skip_while(|&b| b == ';' as u16) { if b == '"' as u16 { in_quote = !in_quote; } else if b == ';' as u16 && !in_quote { diff --git a/library/std/tests/path.rs b/library/std/tests/path.rs index 4094b7acd8749..f9d3c448ec833 100644 --- a/library/std/tests/path.rs +++ b/library/std/tests/path.rs @@ -2577,3 +2577,48 @@ fn test_trim_trailing_sep() { assert_eq!(Path::new("c:..\\\\").trim_trailing_sep().as_os_str(), OsStr::new("c:..")); } } + +// Test: Empty PATH paths +// This test checks how `split_paths` handles empty segments. +// On Unix it should be an empty `Path` and on Windows it should disregard the segment. +#[test] +fn test_only_separators() { + use std::env::split_paths; + #[cfg(unix)] + { + assert_eq!(split_paths("").collect::>(), vec![PathBuf::new(); 1]); + assert_eq!(split_paths(":").collect::>(), vec![PathBuf::new(); 2]); + assert_eq!(split_paths("::").collect::>(), vec![PathBuf::new(); 3]); + + assert_eq!( + split_paths("a::").collect::>(), + vec![PathBuf::from("a"), PathBuf::from(""), PathBuf::from("")] + ); + assert_eq!( + split_paths("a::b").collect::>(), + vec![PathBuf::from("a"), PathBuf::from(""), PathBuf::from("b")] + ); + assert_eq!( + split_paths("::b").collect::>(), + vec![PathBuf::from(""), PathBuf::from(""), PathBuf::from("b")] + ); + assert_eq!( + split_paths(":a:").collect::>(), + vec![PathBuf::from(""), PathBuf::from("a"), PathBuf::from("")] + ); + } + #[cfg(windows)] + { + assert_eq!(split_paths("").collect::>(), vec![]); + assert_eq!(split_paths(";").collect::>(), vec![]); + assert_eq!(split_paths(";;").collect::>(), vec![]); + + assert_eq!(split_paths("a;;").collect::>(), vec![PathBuf::from("a")]); + assert_eq!( + split_paths("a;;b").collect::>(), + vec![PathBuf::from("a"), PathBuf::from("b")] + ); + assert_eq!(split_paths(";;b").collect::>(), vec![PathBuf::from("b")]); + assert_eq!(split_paths(";a;").collect::>(), vec![PathBuf::from("a")]); + } +}