30 lines
888 B
Rust
Raw Normal View History

2022-01-10 21:30:36 +01:00
use crate::error::Result;
2021-04-27 00:36:46 +02:00
use simple_error::simple_error;
2021-12-25 06:22:13 +01:00
/// Extracts the the last `n` bytes of a slice. n being the blocksize.
2021-04-27 00:36:46 +02:00
pub fn extract_last_block(data: &[u8], blocksize: usize) -> Result<&[u8]> {
if data.len() % blocksize != 0 {
2021-12-26 02:33:05 +01:00
return Err(simple_error!(
"Data is not compatible with blocksize: data(length): {}, blocksize: {}.",
data.len(),
blocksize
)
.into());
2021-04-27 00:36:46 +02:00
}
Ok(&data[(data.len() - blocksize)..])
}
2021-12-25 06:22:13 +01:00
/// Takes a given input and zero pads it to a multiple of blocksize
pub fn expand_to_blocksize(data: &mut [u8], blocksize: usize) -> Result<Vec<u8>> {
let diff = data.len() % blocksize;
2021-04-27 00:36:46 +02:00
2021-12-25 06:22:13 +01:00
if diff == 0 {
return Ok(data.to_vec());
} else {
let mut buf = vec![0 as u8; data.len() + blocksize - diff];
buf[..data.len()].copy_from_slice(data);
Ok(buf)
2021-04-27 00:36:46 +02:00
}
2021-12-26 02:33:05 +01:00
}