Skip to content

Commit f40af2c

Browse files
committed
uefi-raw: net: small code improvements for IpAddress
1 parent c49add9 commit f40af2c

File tree

2 files changed

+21
-13
lines changed

2 files changed

+21
-13
lines changed

uefi-raw/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
`MacAddress` to streamline the API with `core::net`.
1010
- Added `::into_core_addr()` for `IpAddress`
1111
- Added `::into_ethernet_addr()` for `MacAddress`
12+
- Added `::ZERO` constant for `IpAddress`
1213

1314
## Changed
1415
- **Breaking:** The MSRV is now 1.85.1 and the crate uses the Rust 2024 edition.

uefi-raw/src/net.rs

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
//! - [`Ipv4Address`]
99
//! - [`Ipv6Address`]
1010
11-
use core::fmt;
12-
use core::fmt::{Debug, Formatter};
11+
use core::fmt::{self, Debug, Formatter};
1312

1413
/// An IPv4 internet protocol address.
1514
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
@@ -83,19 +82,31 @@ pub union IpAddress {
8382
}
8483

8584
impl IpAddress {
85+
/// Zeroed variant where all bytes are guaranteed to be initialized to zero.
86+
pub const ZERO: Self = Self { addr: [0; 4] };
87+
8688
/// Construct a new IPv4 address.
89+
///
90+
/// The type won't know that it is an IPv6 address and additional context
91+
/// is needed.
92+
///
93+
/// # Safety
94+
/// The constructor only initializes the bytes needed for IPv4 addresses.
8795
#[must_use]
88-
pub const fn new_v4(ip_addr: [u8; 4]) -> Self {
96+
pub const fn new_v4(octets: [u8; 4]) -> Self {
8997
Self {
90-
v4: Ipv4Address(ip_addr),
98+
v4: Ipv4Address(octets),
9199
}
92100
}
93101

94102
/// Construct a new IPv6 address.
103+
///
104+
/// The type won't know that it is an IPv6 address and additional context
105+
/// is needed.
95106
#[must_use]
96-
pub const fn new_v6(ip_addr: [u8; 16]) -> Self {
107+
pub const fn new_v6(octets: [u8; 16]) -> Self {
97108
Self {
98-
v6: Ipv6Address(ip_addr),
109+
v6: Ipv6Address(octets),
99110
}
100111
}
101112

@@ -132,19 +143,15 @@ impl Debug for IpAddress {
132143

133144
impl Default for IpAddress {
134145
fn default() -> Self {
135-
Self { addr: [0u32; 4] }
146+
Self::ZERO
136147
}
137148
}
138149

139150
impl From<core::net::IpAddr> for IpAddress {
140151
fn from(t: core::net::IpAddr) -> Self {
141152
match t {
142-
core::net::IpAddr::V4(ip) => Self {
143-
v4: Ipv4Address::from(ip),
144-
},
145-
core::net::IpAddr::V6(ip) => Self {
146-
v6: Ipv6Address::from(ip),
147-
},
153+
core::net::IpAddr::V4(ip) => Self::new_v4(ip.octets()),
154+
core::net::IpAddr::V6(ip) => Self::new_v6(ip.octets()),
148155
}
149156
}
150157
}

0 commit comments

Comments
 (0)