Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

libcore/net: IpAddr::as_octets() #136609

Merged
merged 1 commit into from
Feb 21, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading