use crate::error::Result;
use simple_error::simple_error;

/// Extracts the the last `n` bytes of a slice. n being the blocksize.
pub fn extract_last_block(data: &[u8], blocksize: usize) -> Result<&[u8]> {
    if data.len() % blocksize != 0 {
        return Err(simple_error!(
            "Data is not compatible with blocksize: data(length): {}, blocksize: {}.",
            data.len(),
            blocksize
        )
        .into());
    }

    Ok(&data[(data.len() - blocksize)..])
}

/// 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;

    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)
    }
}