Skip to content

Commit 2a8b3fb

Browse files
author
Gleb Pomykalov
committed
Use CStr::from_ptr in alg_type and alg_name functions
1 parent 6afcc62 commit 2a8b3fb

File tree

2 files changed

+10
-16
lines changed

2 files changed

+10
-16
lines changed

src/sys/socket/addr.rs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1033,9 +1033,10 @@ pub mod netlink {
10331033

10341034
#[cfg(any(target_os = "android", target_os = "linux"))]
10351035
pub mod alg {
1036-
use libc::{AF_ALG, sockaddr_alg};
1036+
use libc::{AF_ALG, sockaddr_alg, c_char};
10371037
use std::{fmt, mem, str};
10381038
use std::hash::{Hash, Hasher};
1039+
use std::ffi::CStr;
10391040

10401041
#[derive(Copy, Clone)]
10411042
pub struct AlgAddr(pub sockaddr_alg);
@@ -1058,13 +1059,6 @@ pub mod alg {
10581059
}
10591060
}
10601061

1061-
fn to_str(bytes: &[u8]) -> &str {
1062-
let nul_position = bytes.iter()
1063-
.position(|&c| c == b'\0')
1064-
.unwrap_or(bytes.len());
1065-
unsafe { str::from_utf8_unchecked(&bytes[0..nul_position]) }
1066-
}
1067-
10681062
impl AlgAddr {
10691063
pub fn new(alg_type: &str, alg_name: &str) -> AlgAddr {
10701064
let mut addr: sockaddr_alg = unsafe { mem::zeroed() };
@@ -1076,20 +1070,20 @@ pub mod alg {
10761070
}
10771071

10781072

1079-
pub fn alg_type(&self) -> &str {
1080-
to_str(&self.0.salg_type)
1073+
pub fn alg_type(&self) -> &CStr {
1074+
unsafe { CStr::from_ptr(self.0.salg_type.as_ptr() as *const c_char) }
10811075
}
10821076

1083-
pub fn alg_name(&self) -> &str {
1084-
to_str(&self.0.salg_name)
1077+
pub fn alg_name(&self) -> &CStr {
1078+
unsafe { CStr::from_ptr(self.0.salg_name.as_ptr() as *const c_char) }
10851079
}
10861080
}
10871081

10881082
impl fmt::Display for AlgAddr {
10891083
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10901084
write!(f, "type: {} alg: {}",
1091-
self.alg_name(),
1092-
self.alg_type())
1085+
self.alg_name().to_string_lossy(),
1086+
self.alg_type().to_string_lossy())
10931087
}
10941088
}
10951089

test/sys/test_socket.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -217,8 +217,8 @@ pub fn test_af_alg_cipher() {
217217
bind(sock, &sockaddr).expect("bind failed");
218218

219219
if let SockAddr::Alg(alg) = sockaddr {
220-
assert_eq!(alg.alg_name(), alg_name);
221-
assert_eq!(alg.alg_type(), alg_type);
220+
assert_eq!(alg.alg_name().to_string_lossy(), alg_name);
221+
assert_eq!(alg.alg_type().to_string_lossy(), alg_type);
222222
} else {
223223
panic!("unexpected SockAddr");
224224
}

0 commit comments

Comments
 (0)