Skip to content

Commit ce0ab19

Browse files
authored
block-buffer: add try_new method (#799)
try_new creates BlockBuffer or returns an error.
1 parent 1cc82d5 commit ce0ab19

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

block-buffer/src/lib.rs

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
pub use generic_array;
1010

11-
use core::{marker::PhantomData, slice};
11+
use core::{fmt, marker::PhantomData, slice};
1212
use generic_array::{
1313
typenum::{IsLess, Le, NonZero, U256},
1414
ArrayLength, GenericArray,
@@ -40,6 +40,16 @@ pub type EagerBuffer<B> = BlockBuffer<B, Eager>;
4040
/// Lazy block buffer.
4141
pub type LazyBuffer<B> = BlockBuffer<B, Lazy>;
4242

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+
4353
/// Buffer for block processing of data.
4454
#[derive(Debug)]
4555
pub struct BlockBuffer<BlockSize, Kind>
@@ -95,15 +105,25 @@ where
95105
/// If slice length is not valid for used buffer kind.
96106
#[inline(always)]
97107
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> {
98116
let pos = buf.len();
99-
assert!(Kind::invariant(pos, BlockSize::USIZE));
117+
if !Kind::invariant(pos, BlockSize::USIZE) {
118+
return Err(Error);
119+
}
100120
let mut buffer = Block::<BlockSize>::default();
101121
buffer[..pos].copy_from_slice(buf);
102-
Self {
122+
Ok(Self {
103123
buffer,
104124
pos: pos as u8,
105125
_pd: PhantomData,
106-
}
126+
})
107127
}
108128

109129
/// Digest data in `input` in blocks of size `BlockSize` using

block-buffer/tests/mod.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,3 +186,11 @@ fn test_eager_paddings() {
186186
[0x42, 0xff, 0x10, 0x11],
187187
);
188188
}
189+
190+
#[test]
191+
fn test_try_new() {
192+
assert!(EagerBuffer::<U4>::try_new(&[0; 3]).is_ok());
193+
assert!(EagerBuffer::<U4>::try_new(&[0; 4]).is_err());
194+
assert!(LazyBuffer::<U4>::try_new(&[0; 4]).is_ok());
195+
assert!(LazyBuffer::<U4>::try_new(&[0; 5]).is_err());
196+
}

0 commit comments

Comments
 (0)