Skip to content

Commit f90033e

Browse files
committed
ptsname_r now returns a lossily-converted string in the event of bad UTF
1 parent a2165e6 commit f90033e

File tree

2 files changed

+13
-11
lines changed

2 files changed

+13
-11
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ This project adheres to [Semantic Versioning](https://semver.org/).
4646
(#[1440](https://github.com/nix-rust/nix/pull/1440))
4747
- Minimum supported Rust version is now 1.41.0.
4848
([#1440](https://github.com/nix-rust/nix/pull/1440))
49+
- `ptsname_r` now returns a lossily-converted string in the event of bad UTF,
50+
just like `ptsname`.
51+
([#1446](https://github.com/nix-rust/nix/pull/1446))
4952
- Errno aliases are now associated consts on `Errno`, instead of consts in the
5053
`errno` module.
5154
(#[1452](https://github.com/nix-rust/nix/pull/1452))

src/pty.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -190,18 +190,17 @@ pub unsafe fn ptsname(fd: &PtyMaster) -> Result<String> {
190190
#[cfg(any(target_os = "android", target_os = "linux"))]
191191
#[inline]
192192
pub fn ptsname_r(fd: &PtyMaster) -> Result<String> {
193-
let mut name_buf = vec![0u8; 64];
194-
let name_buf_ptr = name_buf.as_mut_ptr() as *mut libc::c_char;
195-
if unsafe { libc::ptsname_r(fd.as_raw_fd(), name_buf_ptr, name_buf.capacity()) } != 0 {
196-
return Err(Error::last());
197-
}
198-
199-
// Find the first null-character terminating this string. This is guaranteed to succeed if the
200-
// return value of `libc::ptsname_r` is 0.
201-
let null_index = name_buf.iter().position(|c| *c == b'\0').unwrap();
202-
name_buf.truncate(null_index);
193+
let mut name_buf = Vec::<libc::c_char>::with_capacity(64);
194+
let name_buf_ptr = name_buf.as_mut_ptr();
195+
let cname = unsafe {
196+
let cap = name_buf.capacity();
197+
if libc::ptsname_r(fd.as_raw_fd(), name_buf_ptr, cap) != 0 {
198+
return Err(Error::last());
199+
}
200+
CStr::from_ptr(name_buf.as_ptr())
201+
};
203202

204-
let name = String::from_utf8(name_buf)?;
203+
let name = cname.to_string_lossy().into_owned();
205204
Ok(name)
206205
}
207206

0 commit comments

Comments
 (0)