|
8 | 8 |
|
9 | 9 | pub use generic_array;
|
10 | 10 |
|
11 |
| -use core::{marker::PhantomData, slice}; |
| 11 | +use core::{fmt, marker::PhantomData, slice}; |
12 | 12 | use generic_array::{
|
13 | 13 | typenum::{IsLess, Le, NonZero, U256},
|
14 | 14 | ArrayLength, GenericArray,
|
@@ -40,6 +40,16 @@ pub type EagerBuffer<B> = BlockBuffer<B, Eager>;
|
40 | 40 | /// Lazy block buffer.
|
41 | 41 | pub type LazyBuffer<B> = BlockBuffer<B, Lazy>;
|
42 | 42 |
|
| 43 | +/// Block buffer error. |
| 44 | +#[derive(Copy, Clone, Eq, PartialEq, Debug)] |
| 45 | +pub struct Error; |
| 46 | + |
| 47 | +impl fmt::Display for Error { |
| 48 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { |
| 49 | + f.write_str("Block buffer error") |
| 50 | + } |
| 51 | +} |
| 52 | + |
43 | 53 | /// Buffer for block processing of data.
|
44 | 54 | #[derive(Debug)]
|
45 | 55 | pub struct BlockBuffer<BlockSize, Kind>
|
@@ -95,15 +105,25 @@ where
|
95 | 105 | /// If slice length is not valid for used buffer kind.
|
96 | 106 | #[inline(always)]
|
97 | 107 | pub fn new(buf: &[u8]) -> Self {
|
| 108 | + Self::try_new(buf).unwrap() |
| 109 | + } |
| 110 | + |
| 111 | + /// Create new buffer from slice. |
| 112 | + /// |
| 113 | + /// Returns an error if slice length is not valid for used buffer kind. |
| 114 | + #[inline(always)] |
| 115 | + pub fn try_new(buf: &[u8]) -> Result<Self, Error> { |
98 | 116 | let pos = buf.len();
|
99 |
| - assert!(Kind::invariant(pos, BlockSize::USIZE)); |
| 117 | + if !Kind::invariant(pos, BlockSize::USIZE) { |
| 118 | + return Err(Error); |
| 119 | + } |
100 | 120 | let mut buffer = Block::<BlockSize>::default();
|
101 | 121 | buffer[..pos].copy_from_slice(buf);
|
102 |
| - Self { |
| 122 | + Ok(Self { |
103 | 123 | buffer,
|
104 | 124 | pos: pos as u8,
|
105 | 125 | _pd: PhantomData,
|
106 |
| - } |
| 126 | + }) |
107 | 127 | }
|
108 | 128 |
|
109 | 129 | /// Digest data in `input` in blocks of size `BlockSize` using
|
|
0 commit comments