Check if a Path has a trailing slash without allocation

Viewed 90

I need to check if a Path has a trailing slash:

Solution 1

fn has_trailing_slash(p: &Path) -> bool {
    p.to_string_lossy().as_bytes().last() == Some(&b'/')
}

Problem: this function implies a potential allocation (to_string_lossy()).

Solution 2

fn has_trailing_slash_unix(p: &Path) -> bool {
    use std::os::unix::ffi::OsStrExt;
    p.as_os_str().as_bytes().last() == Some(&b'/')
}

Problem: the method as_bytes() provided by the trait OsStrExt is only implemented for Unix and WASI, not for Windows.

Question

Is it possible to perform this simple check on a Path:

  • without useless allocation;
  • with a full compatibility on all platforms, including Windows?
0 Answers
Related