Skip to content

block-buffer: add try_new method #799

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions block-buffer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

pub use generic_array;

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

/// Block buffer error.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct Error;

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str("Block buffer error")
}
}

/// Buffer for block processing of data.
#[derive(Debug)]
pub struct BlockBuffer<BlockSize, Kind>
Expand Down Expand Up @@ -95,15 +105,25 @@ where
/// If slice length is not valid for used buffer kind.
#[inline(always)]
pub fn new(buf: &[u8]) -> Self {
Self::try_new(buf).unwrap()
}

/// Create new buffer from slice.
///
/// Returns an error if slice length is not valid for used buffer kind.
#[inline(always)]
pub fn try_new(buf: &[u8]) -> Result<Self, Error> {
let pos = buf.len();
assert!(Kind::invariant(pos, BlockSize::USIZE));
if !Kind::invariant(pos, BlockSize::USIZE) {
return Err(Error);
}
let mut buffer = Block::<BlockSize>::default();
buffer[..pos].copy_from_slice(buf);
Self {
Ok(Self {
buffer,
pos: pos as u8,
_pd: PhantomData,
}
})
}

/// Digest data in `input` in blocks of size `BlockSize` using
Expand Down
8 changes: 8 additions & 0 deletions block-buffer/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,11 @@ fn test_eager_paddings() {
[0x42, 0xff, 0x10, 0x11],
);
}

#[test]
fn test_try_new() {
assert!(EagerBuffer::<U4>::try_new(&[0; 3]).is_ok());
assert!(EagerBuffer::<U4>::try_new(&[0; 4]).is_err());
assert!(LazyBuffer::<U4>::try_new(&[0; 4]).is_ok());
assert!(LazyBuffer::<U4>::try_new(&[0; 5]).is_err());
}