Skip to content

Commit

Permalink
core/net: IpAddr*::as_octets()
Browse files Browse the repository at this point in the history
Adds `const` `Ip*Addr::as_octets` methods providing reference access to
`Ip*Addr` octets contents.

See rust-lang/libs-team#535 for accepted ACP
with a more detailed justification.
  • Loading branch information
mammothbane committed Feb 19, 2025
1 parent a9730c3 commit 8fb8885
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions library/core/src/net/ip_addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,28 @@ impl IpAddr {
IpAddr::V6(v6) => v6.to_canonical(),
}
}

/// Returns the eight-bit integers this address consists of as a slice.
///
/// # Examples
///
/// ```
/// #![feature(ip_as_octets)]
///
/// use std::net::{Ipv4Addr, Ipv6Addr, IpAddr};
///
/// assert_eq!(IpAddr::V4(Ipv4Addr::LOCALHOST).as_octets(), &[127, 0, 0, 1]);
/// assert_eq!(IpAddr::V6(Ipv6Addr::LOCALHOST).as_octets(),
/// &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
/// ```
#[unstable(feature = "ip_as_octets", issue = "137259")]
#[inline]
pub const fn as_octets(&self) -> &[u8] {
match self {
IpAddr::V4(ip) => ip.as_octets().as_slice(),
IpAddr::V6(ip) => ip.as_octets().as_slice(),
}
}
}

impl Ipv4Addr {
Expand Down Expand Up @@ -616,6 +638,25 @@ impl Ipv4Addr {
Ipv4Addr { octets }
}

/// Returns the four eight-bit integers that make up this address
/// as a slice.
///
/// # Examples
///
/// ```
/// #![feature(ip_as_octets)]
///
/// use std::net::Ipv4Addr;
///
/// let addr = Ipv4Addr::new(127, 0, 0, 1);
/// assert_eq!(addr.as_octets(), &[127, 0, 0, 1]);
/// ```
#[unstable(feature = "ip_as_octets", issue = "137259")]
#[inline]
pub const fn as_octets(&self) -> &[u8; 4] {
&self.octets
}

/// Returns [`true`] for the special 'unspecified' address (`0.0.0.0`).
///
/// This property is defined in _UNIX Network Programming, Second Edition_,
Expand Down Expand Up @@ -2001,6 +2042,25 @@ impl Ipv6Addr {
pub const fn from_octets(octets: [u8; 16]) -> Ipv6Addr {
Ipv6Addr { octets }
}

/// Returns the sixteen eight-bit integers the IPv6 address consists of
/// as a slice.
///
/// # Examples
///
/// ```
/// #![feature(ip_as_octets)]
///
/// use std::net::Ipv6Addr;
///
/// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).as_octets(),
/// &[255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
/// ```
#[unstable(feature = "ip_as_octets", issue = "137259")]
#[inline]
pub const fn as_octets(&self) -> &[u8; 16] {
&self.octets
}
}

/// Writes an Ipv6Addr, conforming to the canonical style described by
Expand Down

0 comments on commit 8fb8885

Please sign in to comment.