Skip to content

Commit 56d758b

Browse files
yhx-12243daniel-abramov
authored andcommitted
fix(Utf8Bytes): hash consistency for Borrow + Hash traits
1 parent bb7a58a commit 56d758b

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

src/protocol/frame/utf8.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use core::str;
33
use std::fmt::Display;
44

55
/// Utf8 payload.
6-
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
6+
#[derive(Debug, Default, Clone, Eq, PartialEq)]
77
pub struct Utf8Bytes(Bytes);
88

99
impl Utf8Bytes {
@@ -78,6 +78,12 @@ impl std::borrow::Borrow<str> for Utf8Bytes {
7878
}
7979
}
8080

81+
impl core::hash::Hash for Utf8Bytes {
82+
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
83+
self.as_str().hash(state)
84+
}
85+
}
86+
8187
impl PartialOrd for Utf8Bytes {
8288
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
8389
Some(self.cmp(other))
@@ -169,3 +175,20 @@ impl From<Utf8Bytes> for Bytes {
169175
bytes
170176
}
171177
}
178+
179+
#[cfg(test)]
180+
mod tests {
181+
use super::*;
182+
183+
use std::{
184+
borrow::Borrow,
185+
hash::{BuildHasher, RandomState},
186+
};
187+
188+
#[test]
189+
fn hash_consistency() {
190+
let bytes = Utf8Bytes::from_static("hash_consistency");
191+
let hasher = RandomState::new();
192+
assert_eq!(hasher.hash_one::<&str>(bytes.borrow()), hasher.hash_one(bytes));
193+
}
194+
}

0 commit comments

Comments
 (0)