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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//! Returns info about current user.
//!
//! ```
//! println!("{}",user::get_user_name().unwrap())
//! ```

#[cfg(windows)]
extern crate advapi32;
#[cfg(windows)]
extern crate winapi;
#[cfg(windows)]
use winapi::winnt::{WCHAR};
#[cfg(windows)]
use winapi::minwindef::{DWORD};


#[derive(Debug)]
pub enum Error {
    IO(std::io::Error),
    Var(std::env::VarError),
}

use std::error::Error as StdError;
impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.description())
    }
}
impl std::error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::IO(ref e) => e.description(),
            Error::Var(ref e) => e.description(),
        }
    }
    fn cause(&self) -> Option<&std::error::Error> {
        match *self {
            Error::IO(ref e) => Some(e),
            Error::Var(ref e) => Some(e),
        }
    }
}
impl From<std::env::VarError> for Error {
    fn from(e: std::env::VarError) -> Error {
        Error::Var(e)
    }
}

/// Returns the name of the user running the current thread
#[cfg(windows)]
pub fn get_user_name()->Result<String, Error> {
    let mut name:[WCHAR;32767]=[0;32767];
    let mut len=[name.len() as DWORD];
    unsafe {
        let err= advapi32::GetUserNameW(name.as_mut_ptr(),len.as_mut_ptr());
        if err != 0 {
            let name = std::slice::from_raw_parts(name.as_ptr() as *const u16,len[0] as usize - 1);
            Ok(String::from_utf16(&name).unwrap())
        } else {
            Err(Error::IO(std::io::Error::last_os_error()))
        }
    }
}

/// Returns the name of the user running the current process
#[cfg(not(windows))]
pub fn get_user_name()->Result<String, Error> {
    Ok(try!(std::env::var("LOGNAME")))
}