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

Use system error codes

This commit is contained in:
Danilo Bargen 2015-09-18 11:51:59 +02:00
parent 0e7223cfb0
commit 3e1c6e7e71
3 changed files with 11 additions and 5 deletions

View file

@ -7,6 +7,7 @@
* file that was distributed with this source code.
*/
use std::io::{Result, Error};
use ::libc;
use self::c_types::{c_passwd, getpwuid};
@ -16,14 +17,14 @@ extern {
pub fn geteuid() -> libc::uid_t;
}
pub unsafe fn getusername() -> Result<String, String> {
pub unsafe fn getusername() -> Result<String> {
// Get effective user id
let uid = geteuid();
// Try to find username for uid
let passwd: *const c_passwd = getpwuid(uid);
if passwd.is_null() {
return Err(format!("cannot find name for user ID {}", uid))
return Err(Error::last_os_error())
}
// Extract username from passwd struct

View file

@ -10,6 +10,8 @@
extern crate winapi;
extern crate advapi32;
use std::io::{Result, Error};
#[path = "../../common/wide.rs"] #[macro_use] mod wide;
use std::mem;
@ -18,11 +20,11 @@ use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use self::wide::FromWide;
pub unsafe fn getusername() -> Result<String, String> {
pub unsafe fn getusername() -> Result<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 {
return Err("failed to get username".to_string())
return Err(Error::last_os_error())
}
let username = String::from_wide(&buffer[..len as usize - 1]);
Ok(username)

View file

@ -56,7 +56,10 @@ pub fn exec() {
unsafe {
match platform::getusername() {
Ok(username) => println!("{}", username),
Err(msg) => crash!(libc::EXIT_FAILURE, "{}", msg),
Err(err) => match err.raw_os_error() {
Some(0) | None => crash!(1, "failed to get username"),
Some(_) => crash!(1, "failed to get username: {}", err),
}
}
}
}