From 65e890da15e033f08413f650c48b192f6cf5c44b Mon Sep 17 00:00:00 2001 From: cygnus9 Date: Thu, 3 Jan 2019 16:32:43 +0100 Subject: Normalize to Unix-style path separators (#102) --- src/util.rs | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/util.rs b/src/util.rs index 31637dc..414bbb2 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,3 +1,4 @@ +use std::borrow::Cow; use std::path::Path; use {raw, Session, Error}; @@ -28,22 +29,36 @@ pub trait SessionBinding<'sess>: Sized { } #[cfg(unix)] -pub fn path2bytes(p: &Path) -> Result<&[u8], Error> { +pub fn path2bytes(p: &Path) -> Result, Error> { use std::os::unix::prelude::*; use std::ffi::OsStr; let s: &OsStr = p.as_ref(); - check(s.as_bytes()) + check(Cow::Borrowed(s.as_bytes())) } #[cfg(windows)] -pub fn path2bytes(p: &Path) -> Result<&[u8], Error> { - match p.to_str() { - Some(s) => check(s.as_bytes()), - None => Err(Error::new(raw::LIBSSH2_ERROR_INVAL, - "only unicode paths on windows may be used")), - } +pub fn path2bytes(p: &Path) -> Result, Error> { + p.to_str() + .map(|s| s.as_bytes()) + .ok_or_else(|| Error::new(raw::LIBSSH2_ERROR_INVAL, + "only unicode paths on windows may be used")) + .map(|bytes| { + if bytes.contains(&b'\\') { + // Normalize to Unix-style path separators + let mut bytes = bytes.to_owned(); + for b in &mut bytes { + if *b == b'\\' { + *b = b'/'; + } + } + Cow::Owned(bytes) + } else { + Cow::Borrowed(bytes) + } + }) + .and_then(check) } -fn check(b: &[u8]) -> Result<&[u8], Error> { +fn check(b: Cow<[u8]>) -> Result, Error> { if b.iter().any(|b| *b == 0) { Err(Error::new(raw::LIBSSH2_ERROR_INVAL, "path provided contains a 0 byte")) -- cgit v1.2.3