Skip to content

Commit 9b81506

Browse files
committed
uefi-raw: add convenient into_* helpers
1 parent 9da0856 commit 9b81506

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
@@ -161,6 +161,25 @@ impl IpAddress {
161161
pub const fn as_ptr_mut(&mut self) -> *mut Self {
162162
core::ptr::addr_of_mut!(*self)
163163
}
164+
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+
}
164183
}
165184

166185
impl Debug for IpAddress {
@@ -237,6 +256,17 @@ impl MacAddress {
237256
pub const fn octets(self) -> [u8; 32] {
238257
self.0
239258
}
259+
260+
/// Tries to interpret the MAC address as normal 6-byte MAC address, as used
261+
/// in ethernet.
262+
pub fn try_into_ethernet_mac_addr(self) -> Result<[u8; 6], [u8; 32]> {
263+
let extra = self.octets()[4..].iter().any(|&x| x != 0);
264+
if extra {
265+
Err(self.0)
266+
} else {
267+
Ok(self.octets()[..4].try_into().unwrap())
268+
}
269+
}
240270
}
241271

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

0 commit comments

Comments
 (0)