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
This commit is contained in:
Tobin C. Harding 2023-06-20 04:21:28 +10:00
parent 12e014e288
commit 96784b9cfa
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
2 changed files with 20 additions and 13 deletions

View File

@ -17,9 +17,9 @@ pub(crate) const BLOCK_SIZE: usize = 128;
/// Engine to compute SHA512 hash function. /// Engine to compute SHA512 hash function.
#[derive(Clone)] #[derive(Clone)]
pub struct HashEngine { pub struct HashEngine {
pub(crate) h: [u64; 8], h: [u64; 8],
pub(crate) length: usize, length: usize,
pub(crate) buffer: [u8; BLOCK_SIZE], buffer: [u8; BLOCK_SIZE],
} }
impl Default for HashEngine { 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 { impl crate::HashEngine for HashEngine {
type MidState = [u8; 64]; type MidState = [u8; 64];

View File

@ -11,7 +11,6 @@ use core::ops::Index;
use core::slice::SliceIndex; use core::slice::SliceIndex;
use core::str; use core::str;
use crate::sha512::BLOCK_SIZE;
use crate::{sha512, FromSliceError}; use crate::{sha512, FromSliceError};
/// Engine to compute SHA512/256 hash function. /// Engine to compute SHA512/256 hash function.
@ -26,14 +25,7 @@ pub struct HashEngine(sha512::HashEngine);
impl Default for HashEngine { impl Default for HashEngine {
#[rustfmt::skip] #[rustfmt::skip]
fn default() -> Self { fn default() -> Self {
HashEngine(sha512::HashEngine { HashEngine(sha512::HashEngine::sha512_256())
h: [
0x22312194fc2bf72c, 0x9f555fa3c84c64c2, 0x2393b86b6f53b151, 0x963877195940eabd,
0x96283ee2a88effe3, 0xbe5e1e2553863992, 0x2b0199fc2c85b8aa, 0x0eb72ddc81c52ca2,
],
length: 0,
buffer: [0; BLOCK_SIZE],
})
} }
} }
@ -44,7 +36,7 @@ impl crate::HashEngine for HashEngine {
const BLOCK_SIZE: usize = sha512::BLOCK_SIZE; 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); } fn input(&mut self, inp: &[u8]) { self.0.input(inp); }
} }