use super::*;

pub fn calc(bytes: &[u8]) -> Result<u128, CalcError> {
    let mut res = 0;

    if bytes.len() == 0 {
        Ok(0)
    } else if bytes.len() > 16 {
        Err(CalcError::new(format!(
            "expected bytes.len() ({}) to be under 17 or equals to 16",
            bytes.len()
        )))
    } else {
        for i in 0..bytes.len() {
            res |= (bytes[i] as u128) << ((i * 8) as u128);
        }

        Ok(res)
    }
}

pub unsafe fn calc_large(bytes: &[u8]) -> Result<ethnum::u256, CalcError> {
    let mut res = ethnum::u256::new(0);

    if bytes.len() == 0 {
        Ok(ethnum::u256::new(0))
    } else if bytes.len() >= 32 {
        Err(CalcError::new(format!(
            "expected bytes.len() ({}) to be under 32",
            bytes.len()
        )))
    } else {
        for i in 0..bytes.len() {
            res |= ethnum::u256::new(bytes[i] as u128) << ethnum::u256::new((i * 8) as u128);
        }

        Ok(res)
    }
}

pub type CalcError = Error;
