about summary refs log tree commit diff
path: root/src/unix.rs
diff options
context:
space:
mode:
authorIrene Knapp <ireneista@irenes.space>2026-11-24 01:07:05 -0700
committerIrene Knapp <ireneista@irenes.space>2026-11-24 01:07:05 -0700
commitd0a03210efd08d2fbf61fa37e000fc1f4622b46a (patch)
tree1b1fa64fa85f4a4012816449c67c9bf5bfdf1bc3 /src/unix.rs
parenteba55e151fbe041217c929a3f8b15c77868701bb (diff)
move get_username() into a new file
Force-Push: yes
Change-Id: Ied7051c063d5c3380efb2345e6d3889fa1fbe883
Diffstat (limited to 'src/unix.rs')
-rw-r--r--src/unix.rs35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/unix.rs b/src/unix.rs
new file mode 100644
index 0000000..5561292
--- /dev/null
+++ b/src/unix.rs
@@ -0,0 +1,35 @@
+use crate::error::Result;
+
+use std::ffi::CStr;
+use std::mem::{ size_of_val, MaybeUninit };
+use std::ptr::null_mut;
+
+use libc::{ getpwuid_r, passwd };
+use rustix::io::Errno;
+use rustix::process::{ getuid, Uid };
+
+
+pub async fn get_username() -> Result<String> {
+  let uid: Uid = getuid();
+
+  let mut buffer: [i8; 512] = [0; 512];
+  let mut entry: MaybeUninit<passwd> = MaybeUninit::uninit();
+  let mut result = null_mut();
+
+  let error = unsafe {
+    getpwuid_r(uid.as_raw(),
+               &raw mut entry as *mut passwd,
+               &raw mut buffer as *mut i8,
+               size_of_val(&buffer),
+               &mut result)
+  };
+  if error != 0 {
+    return Err(Errno::from_raw_os_error(error).into());
+  }
+
+  let name = unsafe { entry.assume_init() }.pw_name;
+  let name = unsafe { CStr::from_ptr(name) };
+
+  Ok(name.to_string_lossy().into_owned())
+}
+