Skip to content

Commit 356ecce

Browse files
Change gethostname to use a buffer of MaybeUninit values
1 parent 0922fd9 commit 356ecce

File tree

3 files changed

+10
-5
lines changed

3 files changed

+10
-5
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
3232
(#[1713](https://github.com/nix-rust/nix/pull/1713))
3333
- `nix::poll::ppoll`: `sigmask` parameter is now optional.
3434
(#[1739](https://github.com/nix-rust/nix/pull/1739))
35+
- Changed `gethostname` to use a buffer of `MaybeUninit` values.
36+
(#[1745](https://github.com/nix-rust/nix/pull/1745))
3537

3638
### Fixed
3739

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ call:
2525
pub unsafe extern fn gethostname(name: *mut c_char, len: size_t) -> c_int;
2626
2727
// nix api (returns a nix::Result<CStr>)
28-
pub fn gethostname<'a>(buffer: &'a mut [u8]) -> Result<&'a CStr>;
28+
pub fn gethostname<'a>(buffer: &'a mut [mem::MaybeUninit<u8>]) -> Result<&'a CStr>;
2929
```
3030

3131
## Supported Platforms

src/unistd.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1005,20 +1005,23 @@ pub fn sethostname<S: AsRef<OsStr>>(name: S) -> Result<()> {
10051005
///
10061006
/// ```no_run
10071007
/// use nix::unistd;
1008+
/// use std::mem;
10081009
///
1009-
/// let mut buf = [0u8; 64];
1010+
/// let mut buf = [mem::MaybeUninit::uninit(); 64];
10101011
/// let hostname_cstr = unistd::gethostname(&mut buf).expect("Failed getting hostname");
10111012
/// let hostname = hostname_cstr.to_str().expect("Hostname wasn't valid UTF-8");
10121013
/// println!("Hostname: {}", hostname);
10131014
/// ```
1014-
pub fn gethostname(buffer: &mut [u8]) -> Result<&CStr> {
1015+
pub fn gethostname(buffer: &mut [mem::MaybeUninit<u8>]) -> Result<&CStr> {
10151016
let ptr = buffer.as_mut_ptr() as *mut c_char;
10161017
let len = buffer.len() as size_t;
10171018

10181019
let res = unsafe { libc::gethostname(ptr, len) };
10191020
Errno::result(res).map(|_| {
1020-
buffer[len - 1] = 0; // ensure always null-terminated
1021-
unsafe { CStr::from_ptr(buffer.as_ptr() as *const c_char) }
1021+
unsafe {
1022+
buffer[len - 1].as_mut_ptr().write(0); // ensure always null-terminated
1023+
CStr::from_ptr(buffer.as_ptr() as *const c_char)
1024+
}
10221025
})
10231026
}
10241027
}

0 commit comments

Comments
 (0)