Skip to content

Commit

Permalink
Make from_be_slice() enforce the length and return a Result
Browse files Browse the repository at this point in the history
  • Loading branch information
shesek committed Dec 30, 2020
1 parent 908d97f commit 1e9705a
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions src/util/uint.rs
Expand Up @@ -93,12 +93,20 @@ macro_rules! construct_uint {
/// Creates big integer value from a byte array using
/// big-endian encoding
pub fn from_be_bytes(bytes: [u8; $n_words * 8]) -> $name {
Self::from_be_slice(&bytes)
Self::_from_be_slice(&bytes)
}

/// Creates big integer value from a byte slice using
/// big-endian encoding
pub fn from_be_slice(bytes: &[u8]) -> $name {
pub fn from_be_slice(bytes: &[u8]) -> Result<$name, Error> {
if bytes.len() != $n_words * 8 {
Err(Error::InvalidLength(bytes.len(), $n_words*8))
} else {
Ok(Self::_from_be_slice(bytes))
}
}

fn _from_be_slice(bytes: &[u8]) -> $name {
use super::endian::slice_to_u64_be;
let mut slice = [0u64; $n_words];
slice.iter_mut()
Expand Down Expand Up @@ -454,11 +462,8 @@ macro_rules! construct_uint {
{
let bytes = Vec::from_hex(s)
.map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self))?;
if bytes.len() != $n_words * 8 {
Err(de::Error::invalid_length(bytes.len() * 2, &self))
} else {
Ok($name::from_be_slice(&bytes[..]))
}
$name::from_be_slice(&bytes[..])
.map_err(|_| de::Error::invalid_length(bytes.len() * 2, &self))
}
}
deserializer.deserialize_str(Visitor)
Expand All @@ -470,6 +475,13 @@ macro_rules! construct_uint {
construct_uint!(Uint256, 4);
construct_uint!(Uint128, 2);

/// Uint error
#[derive(Debug)]
pub enum Error {
/// Invalid slice length
InvalidLength(usize, usize), // (expected, actual)
}

impl Uint256 {
/// Increment by 1
#[inline]
Expand Down

0 comments on commit 1e9705a

Please sign in to comment.