Removed all but one unsafe call from the hasher.

This commit is contained in:
Nathan Vegdahl 2020-02-24 12:50:18 +09:00
parent c38c83a8b5
commit dc9b3dd5c3

View File

@ -55,10 +55,7 @@ impl LedHash256 {
while !data.is_empty() { while !data.is_empty() {
if self.buf_length >= BLOCK_SIZE { if self.buf_length >= BLOCK_SIZE {
// Process the filled buffer // Process the filled buffer
let (a, b, c) = unsafe { self.buf.align_to::<u64>() }; self.mix_buffer_into_state();
debug_assert!(a.is_empty());
debug_assert!(c.is_empty());
mix(&mut self.state[..], b);
self.buf_length = 0; self.buf_length = 0;
} else { } else {
// Fill the buffer. // Fill the buffer.
@ -74,30 +71,30 @@ impl LedHash256 {
pub fn finish(mut self) -> [u8; BLOCK_SIZE] { pub fn finish(mut self) -> [u8; BLOCK_SIZE] {
// Hash the remaining bytes if there are any. // Hash the remaining bytes if there are any.
if self.buf_length > 0 { if self.buf_length > 0 {
// Pad with zero.
for i in (&mut self.buf[self.buf_length..]).iter_mut() { for i in (&mut self.buf[self.buf_length..]).iter_mut() {
*i = 0; *i = 0;
} }
self.mix_buffer_into_state();
// Process.
let (a, b, c) = unsafe { self.buf.align_to::<u64>() };
debug_assert!(a.is_empty());
debug_assert!(c.is_empty());
mix(&mut self.state[..], b);
self.buf_length = 0; self.buf_length = 0;
} }
// Hash the message length, in bits. // Hash the message length, in bits.
mix(&mut self.state[..], &[self.message_length * 8, 0, 0, 0]); mix(&mut self.state[..], &[self.message_length * 8, 0, 0, 0]);
// Convert to little endian. // Get the digest as a byte array and return it.
self.state[0] = self.state[0].to_le(); let mut result = [0u8; BLOCK_SIZE];
self.state[1] = self.state[1].to_le(); result[0..8].copy_from_slice(&self.state[0].to_le_bytes());
self.state[2] = self.state[2].to_le(); result[8..16].copy_from_slice(&self.state[1].to_le_bytes());
self.state[3] = self.state[3].to_le(); result[16..24].copy_from_slice(&self.state[2].to_le_bytes());
result[24..32].copy_from_slice(&self.state[3].to_le_bytes());
return result;
}
// Return the result. fn mix_buffer_into_state(&mut self) {
unsafe { std::mem::transmute(self.state) } let (a, b, c) = unsafe { self.buf.align_to::<u64>() };
debug_assert!(a.is_empty());
debug_assert!(c.is_empty());
mix(&mut self.state[..], b);
} }
} }