unix.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. use std::str::raw::from_c_str;
  2. use std::ptr::read;
  3. mod c {
  4. #![allow(non_camel_case_types)]
  5. extern crate libc;
  6. use self::libc::{
  7. c_char,
  8. c_int,
  9. uid_t,
  10. time_t
  11. };
  12. pub struct c_passwd {
  13. pub pw_name: *c_char, // login name
  14. pub pw_passwd: *c_char,
  15. pub pw_uid: c_int, // user ID
  16. pub pw_gid: c_int, // group ID
  17. pub pw_change: time_t,
  18. pub pw_class: *c_char,
  19. pub pw_gecos: *c_char, // full name
  20. pub pw_dir: *c_char, // login dir
  21. pub pw_shell: *c_char, // login shell
  22. pub pw_expire: time_t // password expiry time
  23. }
  24. pub struct c_group {
  25. pub gr_name: *c_char // group name
  26. }
  27. extern {
  28. pub fn getpwuid(uid: c_int) -> *c_passwd;
  29. pub fn getgrgid(gid: uid_t) -> *c_group;
  30. }
  31. }
  32. pub fn get_user_name(uid: i32) -> Option<~str> {
  33. let pw = unsafe { c::getpwuid(uid) };
  34. if pw.is_not_null() {
  35. return unsafe { Some(from_c_str(read(pw).pw_name)) };
  36. }
  37. else {
  38. return None;
  39. }
  40. }
  41. pub fn get_group_name(gid: u32) -> Option<~str> {
  42. let gr = unsafe { c::getgrgid(gid) };
  43. if gr.is_not_null() {
  44. return unsafe { Some(from_c_str(read(gr).gr_name)) };
  45. }
  46. else {
  47. return None;
  48. }
  49. }