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

Hash Ipv*Addr as an integer #128946

Merged
merged 3 commits into from
Aug 15, 2024
Merged
Changes from 1 commit
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
21 changes: 19 additions & 2 deletions library/core/src/net/ip_addr.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use super::display_buffer::DisplayBuffer;
use crate::cmp::Ordering;
use crate::fmt::{self, Write};
use crate::hash::{Hash, Hasher};
use crate::iter;
use crate::mem::transmute;
use crate::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
Expand Down Expand Up @@ -67,12 +68,20 @@ pub enum IpAddr {
/// assert!("0000000.0.0.0".parse::<Ipv4Addr>().is_err()); // first octet is a zero in octal
/// assert!("0xcb.0x0.0x71.0x00".parse::<Ipv4Addr>().is_err()); // all octets are in hex
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
#[derive(Copy, Clone, PartialEq, Eq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Ipv4Addr {
octets: [u8; 4],
}

impl Hash for Ipv4Addr {
fn hash<H: Hasher>(&self, state: &mut H) {
// Hashers are often more efficient at hashing a fixed-width integer
// than a bytestring, so convert before hashing.
u32::from_le_bytes(self.octets).hash(state);
orlp marked this conversation as resolved.
Show resolved Hide resolved
}
}

/// An IPv6 address.
///
/// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291].
Expand Down Expand Up @@ -149,12 +158,20 @@ pub struct Ipv4Addr {
/// assert_eq!("::1".parse(), Ok(localhost));
/// assert_eq!(localhost.is_loopback(), true);
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
#[derive(Copy, Clone, PartialEq, Eq)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Ipv6Addr {
octets: [u8; 16],
}

impl Hash for Ipv6Addr {
fn hash<H: Hasher>(&self, state: &mut H) {
// Hashers are often more efficient at hashing a fixed-width integer
// than a bytestring, so convert before hashing.
u128::from_le_bytes(self.octets).hash(state);
}
}

/// Scope of an [IPv6 multicast address] as defined in [IETF RFC 7346 section 2].
///
/// # Stability Guarantees
Expand Down
Loading