Skip to content

Commit ce0f5b1

Browse files
authored
Change UtunIfname sockopt type to CString (#2329)
* Implement GetCString for use with sockopt * Change UtunIfname sockopt type to CString
1 parent bb9ffeb commit ce0f5b1

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

src/sys/socket/sockopt.rs

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::sys::time::TimeVal;
55
use crate::Result;
66
use cfg_if::cfg_if;
77
use libc::{self, c_int, c_void, socklen_t};
8-
use std::ffi::{OsStr, OsString};
8+
use std::ffi::{CStr, CString, OsStr, OsString};
99
use std::mem::{self, MaybeUninit};
1010
use std::os::unix::ffi::OsStrExt;
1111
use std::os::unix::io::{AsFd, AsRawFd};
@@ -1073,8 +1073,8 @@ sockopt_impl!(
10731073
GetOnly,
10741074
libc::SYSPROTO_CONTROL,
10751075
libc::UTUN_OPT_IFNAME,
1076-
OsString,
1077-
GetOsString<[u8; libc::IFNAMSIZ]>
1076+
CString,
1077+
GetCString<[u8; libc::IFNAMSIZ]>
10781078
);
10791079

10801080
#[allow(missing_docs)]
@@ -1579,3 +1579,32 @@ impl<'a> Set<'a, OsString> for SetOsString<'a> {
15791579
}
15801580
}
15811581

1582+
/// Getter for a `CString` value.
1583+
struct GetCString<T: AsMut<[u8]>> {
1584+
len: socklen_t,
1585+
val: MaybeUninit<T>,
1586+
}
1587+
1588+
impl<T: AsMut<[u8]>> Get<CString> for GetCString<T> {
1589+
fn uninit() -> Self {
1590+
GetCString {
1591+
len: mem::size_of::<T>() as socklen_t,
1592+
val: MaybeUninit::uninit(),
1593+
}
1594+
}
1595+
1596+
fn ffi_ptr(&mut self) -> *mut c_void {
1597+
self.val.as_mut_ptr().cast()
1598+
}
1599+
1600+
fn ffi_len(&mut self) -> *mut socklen_t {
1601+
&mut self.len
1602+
}
1603+
1604+
unsafe fn assume_init(self) -> CString {
1605+
let mut v = unsafe { self.val.assume_init() };
1606+
CStr::from_bytes_until_nul(v.as_mut())
1607+
.expect("string should be null-terminated")
1608+
.to_owned()
1609+
}
1610+
}

test/sys/test_sockopt.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -856,6 +856,6 @@ fn test_utun_ifname() {
856856
let name = getsockopt(&fd, sockopt::UtunIfname)
857857
.expect("getting UTUN_OPT_IFNAME on a utun interface should succeed");
858858

859-
let expected_name = format!("utun{}\0", unit - 1);
859+
let expected_name = format!("utun{}", unit - 1);
860860
assert_eq!(name.into_string(), Ok(expected_name));
861861
}

0 commit comments

Comments
 (0)