Skip to content

Commit

Permalink
preserve trailing slash on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
rhysd committed Jul 3, 2022
1 parent 424c83c commit d7d9481
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
31 changes: 29 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,33 @@ use std::borrow::Cow;
use std::ffi::OsStr;
use std::path::{Path, PathBuf, MAIN_SEPARATOR};

#[cfg(target_os = "windows")]
mod windows {
use super::*;
use std::io::{self, Write};

#[derive(Default)]
struct EndsWithMainSep(bool);

impl io::Write for EndsWithMainSep {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0 = buf.ends_with(&[MAIN_SEPARATOR as u8]);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}

// Workaround for Windows. There is no way to extract raw byte sequence from `OsStr` (in `Path`).
// And `OsStr::to_string_lossy` may cause extra heap allocation.
pub fn ends_with_main_sep(p: &Path) -> bool {
let mut w = EndsWithMainSep::default();
write!(&mut w, "{}", p.display()).unwrap();
w.0
}
}

fn str_to_path(s: &str, sep: char) -> Cow<'_, Path> {
let mut buf = String::new();

Expand Down Expand Up @@ -155,7 +182,7 @@ impl PathExt for Path {
buf.push('/');
}

if buf != "/" && buf.ends_with('/') {
if !windows::ends_with_main_sep(self) && buf != "/" && buf.ends_with('/') {
buf.pop(); // Pop last '/'
}

Expand Down Expand Up @@ -204,7 +231,7 @@ impl PathExt for Path {
buf.push('/');
}

if buf != "/" && buf.ends_with('/') {
if !windows::ends_with_main_sep(self) && buf != "/" && buf.ends_with('/') {
buf.pop(); // Pop last '/'
}

Expand Down
8 changes: 4 additions & 4 deletions src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ lazy_static! {
("//", "/"),
("foo", "foo"),
("/foo", "/foo"),
("foo/", "foo"),
("/foo/", "/foo"),
("foo/", "foo/"),
("/foo/", "/foo/"),
("./foo", "./foo"),
("../foo", "../foo"),
("foo/.", "foo/."),
Expand Down Expand Up @@ -116,8 +116,8 @@ lazy_static! {
"/",
"foo",
"/foo",
"foo",
"/foo",
"foo/",
"/foo/",
"./foo",
"../foo",
"foo/..",
Expand Down

0 comments on commit d7d9481

Please sign in to comment.