Skip to content

Commit

Permalink
Change gethostname to use a buffer of MaybeUninit values
Browse files Browse the repository at this point in the history
  • Loading branch information
nathaniel-daniel committed Jun 15, 2022
1 parent 01a5927 commit 87b7bb3
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
(#[1703](https://github.com/nix-rust/nix/pull/1703))
- Added `ptrace::read_user` and `ptrace::write_user` for Linux.
(#[1697](https://github.com/nix-rust/nix/pull/1697))
- Changed `gethostname` to use a buffer of `MaybeUninit` values.
(#[1745](https://github.com/nix-rust/nix/pull/1745))

### Changed

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ call:
pub unsafe extern fn gethostname(name: *mut c_char, len: size_t) -> c_int;
// nix api (returns a nix::Result<CStr>)
pub fn gethostname<'a>(buffer: &'a mut [u8]) -> Result<&'a CStr>;
pub fn gethostname<'a>(buffer: &'a mut [mem::MaybeUninit<u8>]) -> Result<&'a CStr>;
```

## Supported Platforms
Expand Down
11 changes: 7 additions & 4 deletions src/unistd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -993,20 +993,23 @@ pub fn sethostname<S: AsRef<OsStr>>(name: S) -> Result<()> {
///
/// ```no_run
/// use nix::unistd;
/// use std::mem;
///
/// let mut buf = [0u8; 64];
/// let mut buf = [mem::MaybeUninit::uninit(); 64];
/// let hostname_cstr = unistd::gethostname(&mut buf).expect("Failed getting hostname");
/// let hostname = hostname_cstr.to_str().expect("Hostname wasn't valid UTF-8");
/// println!("Hostname: {}", hostname);
/// ```
pub fn gethostname(buffer: &mut [u8]) -> Result<&CStr> {
pub fn gethostname(buffer: &mut [mem::MaybeUninit<u8>]) -> Result<&CStr> {
let ptr = buffer.as_mut_ptr() as *mut c_char;
let len = buffer.len() as size_t;

let res = unsafe { libc::gethostname(ptr, len) };
Errno::result(res).map(|_| {
buffer[len - 1] = 0; // ensure always null-terminated
unsafe { CStr::from_ptr(buffer.as_ptr() as *const c_char) }
unsafe {
buffer[len - 1].as_mut_ptr().write(0); // ensure always null-terminated
CStr::from_ptr(buffer.as_ptr() as *const c_char)
}
})
}
}
Expand Down

0 comments on commit 87b7bb3

Please sign in to comment.