Skip to content

Commit cb4dfcb

Browse files
committed
uefi-raw: add convenient into_* helper
1 parent b3edd38 commit cb4dfcb

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

uefi-raw/CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
- `[u8; 32]` --> `MacAddress`
2020
- `[u8; 4]` --> `Ipv4Address`, `IpAddress`
2121
- `[u8; 16]` <--> `Ipv6Address`, `IpAddress`
22+
- Added `::into_std_ip_addr()` for `IpAddress`
23+
- Added `::try_into_ethernet_mac_addr()` for `MacAddress`
2224

2325
## Changed
2426
- The documentation for UEFI protocols has been streamlined and improved.

uefi-raw/src/net.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,25 @@ impl IpAddress {
162162
core::ptr::addr_of_mut!(*self)
163163
}
164164

165+
/// Transforms this EFI type to the Rust standard library's type.
166+
///
167+
/// # Arguments
168+
/// - `is_ipv6`: Whether the internal data should be interpreted as IPv6 or
169+
/// IPv4 address.
170+
///
171+
/// # Safety
172+
/// Callers must be sure that all underlying bytes were initialized.
173+
#[must_use]
174+
pub unsafe fn into_std_ip_addr(self, is_ipv6: bool) -> StdIpAddr {
175+
if is_ipv6 {
176+
// SAFETY: Caller assumes that the underlying data is initialized.
177+
StdIpAddr::V6(StdIpv6Addr::from(unsafe { self.v6.octets() }))
178+
} else {
179+
// SAFETY: Caller assumes that the underlying data is initialized.
180+
StdIpAddr::V4(StdIpv4Addr::from(unsafe { self.v4.octets() }))
181+
}
182+
}
183+
165184
/// Returns the octets of the union. Without additional context, it is not
166185
/// clear whether the octets represent an IPv4 or IPv6 address.
167186
///
@@ -247,6 +266,17 @@ impl MacAddress {
247266
pub const fn octets(self) -> [u8; 32] {
248267
self.0
249268
}
269+
270+
/// Tries to interpret the MAC address as normal 6-byte MAC address, as used
271+
/// in ethernet.
272+
pub fn try_into_ethernet_mac_addr(self) -> Result<[u8; 6], [u8; 32]> {
273+
let extra = self.octets()[4..].iter().any(|&x| x != 0);
274+
if extra {
275+
Err(self.0)
276+
} else {
277+
Ok(self.octets()[..4].try_into().unwrap())
278+
}
279+
}
250280
}
251281

252282
// Normal/typical MAC addresses, such as in Ethernet.

0 commit comments

Comments
 (0)