summaryrefslogtreecommitdiff
path: root/src/util.rs
blob: 31637dc38a2465cf2d0b76df9db575fcf29a0ac1 (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
50
51
52
53
use std::path::Path;

use {raw, Session, Error};

#[doc(hidden)]
pub trait Binding: Sized {
    type Raw;

    unsafe fn from_raw(raw: Self::Raw) -> Self;
    fn raw(&self) -> Self::Raw;
}

#[doc(hidden)]
pub trait SessionBinding<'sess>: Sized {
    type Raw;

    unsafe fn from_raw(sess: &'sess Session, raw: *mut Self::Raw) -> Self;
    fn raw(&self) -> *mut Self::Raw;

    unsafe fn from_raw_opt(sess: &'sess Session, raw: *mut Self::Raw)
                           -> Result<Self, Error> {
        if raw.is_null() {
            Err(Error::last_error(sess).unwrap_or_else(Error::unknown))
        } else {
            Ok(SessionBinding::from_raw(sess, raw))
        }
    }
}

#[cfg(unix)]
pub fn path2bytes(p: &Path) -> Result<&[u8], Error> {
    use std::os::unix::prelude::*;
    use std::ffi::OsStr;
    let s: &OsStr = p.as_ref();
    check(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")),
    }
}

fn check(b: &[u8]) -> Result<&[u8], Error> {
    if b.iter().any(|b| *b == 0) {
        Err(Error::new(raw::LIBSSH2_ERROR_INVAL,
                       "path provided contains a 0 byte"))
    } else {
        Ok(b)
    }
}