1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-08-03 06:27:45 +00:00

Return Result<String, String> from getusername

This commit is contained in:
Danilo Bargen 2015-09-18 10:40:28 +02:00
parent fe0a49f7a4
commit a8f9b40674
3 changed files with 11 additions and 7 deletions

View file

@ -16,9 +16,10 @@ extern {
pub fn geteuid() -> libc::uid_t;
}
pub unsafe fn getusername() -> String {
pub unsafe fn getusername() -> Result<String, String> {
let passwd: *const c_passwd = getpwuid(geteuid());
let pw_name: *const libc::c_char = (*passwd).pw_name;
String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string()
let username = String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string();
Ok(username)
}

View file

@ -18,11 +18,12 @@ use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use self::wide::FromWide;
pub unsafe fn getusername() -> String {
pub unsafe fn getusername() -> Result<String, String> {
let mut buffer: [winapi::WCHAR; winapi::UNLEN as usize + 1] = mem::uninitialized();
let mut len = buffer.len() as winapi::DWORD;
if advapi32::GetUserNameW(buffer.as_mut_ptr(), &mut len) == 0 {
crash!(1, "failed to get username");
return Err("failed to get username".to_string())
}
String::from_wide(&buffer[..len as usize - 1])
let username = String::from_wide(&buffer[..len as usize - 1]);
Ok(username)
}

View file

@ -54,7 +54,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
pub fn exec() {
unsafe {
let username = platform::getusername();
println!("{}", username);
match platform::getusername() {
Ok(username) => println!("{}", username),
Err(msg) => crash!(libc::EXIT_FAILURE, "{}", msg),
}
}
}