Skip to content

Commit

Permalink
Merge #1872
Browse files Browse the repository at this point in the history
1872: Misc internal optimizations r=rtzoeller a=asomers

* Make ipv4addr_to_libc const
* Use mem::transmute in ipv4addr_to_libc and ipv6addr_to_libc

Fixes #1687
Fixes #1688

Co-authored-by: Alan Somers <asomers@gmail.com>
  • Loading branch information
bors[bot] and asomers committed Nov 19, 2022
2 parents d649e4f + 80b2572 commit 2ad2f48
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 11 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ libc = { git = "https://github.com/rust-lang/libc", rev = "cc19b6f0801", feature
bitflags = "1.1"
cfg-if = "1.0"
pin-utils = { version = "0.1.0", optional = true }
static_assertions = "1"

[target.'cfg(not(target_os = "redox"))'.dependencies]
memoffset = { version = "0.6.3", optional = true }
Expand Down
21 changes: 10 additions & 11 deletions src/sys/socket/addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,22 @@ use std::{fmt, mem, net, ptr, slice};

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

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

Expand Down

0 comments on commit 2ad2f48

Please sign in to comment.