From 96784b9cfa6746204994c32cf9d9a1f239f3d24f Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Tue, 20 Jun 2023 04:21:28 +1000 Subject: [PATCH] Make sha512::HashEngine fields private Recently we made the hash engine fields pub crate so that `sha512_256` could construct a hash engine with different constants. We can make the code slightly cleaner by adding a pub crate constructor and making the fields private again. Idea from Kixunil: https://github.com/rust-bitcoin/rust-bitcoin/pull/1413#pullrequestreview-1197207593 --- hashes/src/sha512.rs | 21 ++++++++++++++++++--- hashes/src/sha512_256.rs | 12 ++---------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/hashes/src/sha512.rs b/hashes/src/sha512.rs index 58877c92..034b3a1a 100644 --- a/hashes/src/sha512.rs +++ b/hashes/src/sha512.rs @@ -17,9 +17,9 @@ pub(crate) const BLOCK_SIZE: usize = 128; /// Engine to compute SHA512 hash function. #[derive(Clone)] pub struct HashEngine { - pub(crate) h: [u64; 8], - pub(crate) length: usize, - pub(crate) buffer: [u8; BLOCK_SIZE], + h: [u64; 8], + length: usize, + buffer: [u8; BLOCK_SIZE], } impl Default for HashEngine { @@ -36,6 +36,21 @@ impl Default for HashEngine { } } +impl HashEngine { + /// Constructs a hash engine suitable for use inside the default `sha512_256::HashEngine`. + #[rustfmt::skip] + pub(crate) fn sha512_256() -> Self { + HashEngine { + h: [ + 0x22312194fc2bf72c, 0x9f555fa3c84c64c2, 0x2393b86b6f53b151, 0x963877195940eabd, + 0x96283ee2a88effe3, 0xbe5e1e2553863992, 0x2b0199fc2c85b8aa, 0x0eb72ddc81c52ca2, + ], + length: 0, + buffer: [0; BLOCK_SIZE], + } + } +} + impl crate::HashEngine for HashEngine { type MidState = [u8; 64]; diff --git a/hashes/src/sha512_256.rs b/hashes/src/sha512_256.rs index 6bef7bec..27d90d68 100644 --- a/hashes/src/sha512_256.rs +++ b/hashes/src/sha512_256.rs @@ -11,7 +11,6 @@ use core::ops::Index; use core::slice::SliceIndex; use core::str; -use crate::sha512::BLOCK_SIZE; use crate::{sha512, FromSliceError}; /// Engine to compute SHA512/256 hash function. @@ -26,14 +25,7 @@ pub struct HashEngine(sha512::HashEngine); impl Default for HashEngine { #[rustfmt::skip] fn default() -> Self { - HashEngine(sha512::HashEngine { - h: [ - 0x22312194fc2bf72c, 0x9f555fa3c84c64c2, 0x2393b86b6f53b151, 0x963877195940eabd, - 0x96283ee2a88effe3, 0xbe5e1e2553863992, 0x2b0199fc2c85b8aa, 0x0eb72ddc81c52ca2, - ], - length: 0, - buffer: [0; BLOCK_SIZE], - }) + HashEngine(sha512::HashEngine::sha512_256()) } } @@ -44,7 +36,7 @@ impl crate::HashEngine for HashEngine { const BLOCK_SIZE: usize = sha512::BLOCK_SIZE; - fn n_bytes_hashed(&self) -> usize { self.0.length } + fn n_bytes_hashed(&self) -> usize { self.0.n_bytes_hashed() } fn input(&mut self, inp: &[u8]) { self.0.input(inp); } }