Skip to content

Commit 80b2572

Browse files
committed
Misc internal optimizations
* Make ipv4addr_to_libc const * Use mem::transmute in ipv4addr_to_libc and ipv6addr_to_libc Fixes #1687 Fixes #1688
1 parent fbebb21 commit 80b2572

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ libc = { git = "https://github.com/rust-lang/libc", rev = "cc19b6f0801", feature
3131
bitflags = "1.1"
3232
cfg-if = "1.0"
3333
pin-utils = { version = "0.1.0", optional = true }
34+
static_assertions = "1"
3435

3536
[target.'cfg(not(target_os = "redox"))'.dependencies]
3637
memoffset = { version = "0.6.3", optional = true }

src/sys/socket/addr.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,23 +40,22 @@ use std::{fmt, mem, net, ptr, slice};
4040

4141
/// Convert a std::net::Ipv4Addr into the libc form.
4242
#[cfg(feature = "net")]
43-
pub(crate) fn ipv4addr_to_libc(addr: net::Ipv4Addr) -> libc::in_addr {
44-
let octets = addr.octets();
45-
libc::in_addr {
46-
s_addr: u32::to_be(
47-
((octets[0] as u32) << 24)
48-
| ((octets[1] as u32) << 16)
49-
| ((octets[2] as u32) << 8)
50-
| (octets[3] as u32),
51-
),
43+
pub(crate) const fn ipv4addr_to_libc(addr: net::Ipv4Addr) -> libc::in_addr {
44+
static_assertions::assert_eq_size!(net::Ipv4Addr, libc::in_addr);
45+
// Safe because both types have the same memory layout, and no fancy Drop
46+
// impls.
47+
unsafe {
48+
mem::transmute(addr)
5249
}
5350
}
5451

5552
/// Convert a std::net::Ipv6Addr into the libc form.
5653
#[cfg(feature = "net")]
5754
pub(crate) const fn ipv6addr_to_libc(addr: &net::Ipv6Addr) -> libc::in6_addr {
58-
libc::in6_addr {
59-
s6_addr: addr.octets(),
55+
static_assertions::assert_eq_size!(net::Ipv6Addr, libc::in6_addr);
56+
// Safe because both are Newtype wrappers around the same libc type
57+
unsafe {
58+
mem::transmute(*addr)
6059
}
6160
}
6261

0 commit comments

Comments
 (0)