summaryrefslogtreecommitdiff
path: root/src/util.rs
blob: 258aa59c89fb2d14e46a02865a3f15c03e3acf36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use std::borrow::Cow;
use std::path::Path;

use {raw, Error, ErrorCode};

#[cfg(unix)]
pub fn path2bytes(p: &Path) -> Result<Cow<[u8]>, Error> {
    use std::ffi::OsStr;
    use std::os::unix::prelude::*;
    let s: &OsStr = p.as_ref();
    check(Cow::Borrowed(s.as_bytes()))
}
#[cfg(windows)]
pub fn path2bytes(p: &Path) -> Result<Cow<[u8]>, Error> {
    p.to_str()
        .map(|s| s.as_bytes())
        .ok_or_else(|| {
            Error::new(
                ErrorCode::Session(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: Cow<[u8]>) -> Result<Cow<[u8]>, Error> {
    if b.iter().any(|b| *b == 0) {
        Err(Error::new(
            ErrorCode::Session(raw::LIBSSH2_ERROR_INVAL),
            "path provided contains a 0 byte",
        ))
    } else {
        Ok(b)
    }
}