Skip to content

Commit 5cb34b4

Browse files
jturner314-nrleldruin
authored andcommitted
Add missing unsafe to murmur3::Hasher::push
This commit adds the `unsafe` keyword to the private `murmur3::Hasher::push` function and associated comments, since the function will result in a buffer overflow if `self.index.usize() + buf.len() > 4`. This change makes no difference to the public API or runtime behavior, but it clarifies the safety requirements of the function.
1 parent e9eea55 commit 5cb34b4

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/murmur3.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,10 @@ impl From<usize> for Index {
5151
}
5252

5353
impl Hasher {
54-
fn push(&mut self, buf: &[u8]) {
54+
/// # Safety
55+
///
56+
/// The caller must ensure that `self.index.usize() + buf.len() <= 4`.
57+
unsafe fn push(&mut self, buf: &[u8]) {
5558
let start = self.index.usize();
5659
let len = buf.len();
5760
// NOTE(unsafe) avoid calling `memcpy` on a 0-3 byte copy
@@ -127,10 +130,13 @@ impl core::hash::Hasher for Hasher {
127130
self.processed += len as u32;
128131

129132
let body = if self.index == Index::_0 {
133+
// CASE 1
130134
bytes
131135
} else {
132136
let index = self.index.usize();
133137
if len + index >= 4 {
138+
// CASE 2
139+
134140
// we can complete a block using the data left in the buffer
135141
// NOTE(unsafe) avoid panicking branch (`slice_index_len_fail`)
136142
// let (head, body) = bytes.split_at(4 - index);
@@ -154,6 +160,7 @@ impl core::hash::Hasher for Hasher {
154160

155161
body
156162
} else {
163+
// CASE 3
157164
bytes
158165
}
159166
};
@@ -163,7 +170,12 @@ impl core::hash::Hasher for Hasher {
163170
self.state
164171
.process_block(unsafe { &*(block.as_ptr() as *const _) });
165172
} else {
166-
self.push(block);
173+
// NOTE(unsafe) In this branch, `block.len() < 4`. For CASE 1 and CASE 2 above,
174+
// `self.index.usize()` will be 0 here, so `self.index.usize() + block.len() < 4`.
175+
// The condition for CASE 3 ensures that `self.index.usize() + bytes.len() < 4`.
176+
unsafe {
177+
self.push(block);
178+
}
167179
}
168180
}
169181

0 commit comments

Comments
 (0)