Skip to content

Commit 2e34ac3

Browse files
committed
Hash Ipv*Addr as an integer
1 parent b8b61e1 commit 2e34ac3

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

Diff for: core/src/net/ip_addr.rs

+19-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use super::display_buffer::DisplayBuffer;
22
use crate::cmp::Ordering;
33
use crate::fmt::{self, Write};
4+
use crate::hash::{Hash, Hasher};
45
use crate::iter;
56
use crate::mem::transmute;
67
use crate::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
@@ -67,12 +68,20 @@ pub enum IpAddr {
6768
/// assert!("0000000.0.0.0".parse::<Ipv4Addr>().is_err()); // first octet is a zero in octal
6869
/// assert!("0xcb.0x0.0x71.0x00".parse::<Ipv4Addr>().is_err()); // all octets are in hex
6970
/// ```
70-
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
71+
#[derive(Copy, Clone, PartialEq, Eq)]
7172
#[stable(feature = "rust1", since = "1.0.0")]
7273
pub struct Ipv4Addr {
7374
octets: [u8; 4],
7475
}
7576

77+
impl Hash for Ipv4Addr {
78+
fn hash<H: Hasher>(&self, state: &mut H) {
79+
// Hashers are often more efficient at hashing a fixed-width integer
80+
// than a bytestring, so convert before hashing.
81+
u32::from_le_bytes(self.octets).hash(state);
82+
}
83+
}
84+
7685
/// An IPv6 address.
7786
///
7887
/// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291].
@@ -149,12 +158,20 @@ pub struct Ipv4Addr {
149158
/// assert_eq!("::1".parse(), Ok(localhost));
150159
/// assert_eq!(localhost.is_loopback(), true);
151160
/// ```
152-
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
161+
#[derive(Copy, Clone, PartialEq, Eq)]
153162
#[stable(feature = "rust1", since = "1.0.0")]
154163
pub struct Ipv6Addr {
155164
octets: [u8; 16],
156165
}
157166

167+
impl Hash for Ipv6Addr {
168+
fn hash<H: Hasher>(&self, state: &mut H) {
169+
// Hashers are often more efficient at hashing a fixed-width integer
170+
// than a bytestring, so convert before hashing.
171+
u128::from_le_bytes(self.octets).hash(state);
172+
}
173+
}
174+
158175
/// Scope of an [IPv6 multicast address] as defined in [IETF RFC 7346 section 2].
159176
///
160177
/// # Stability Guarantees

0 commit comments

Comments
 (0)