From 1e9705ac4de56bc7a307f48c51ae6eb838d71485 Mon Sep 17 00:00:00 2001 From: Nadav Ivgi Date: Wed, 30 Dec 2020 06:36:32 +0200 Subject: [PATCH] Make from_be_slice() enforce the length and return a Result --- src/util/uint.rs | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/src/util/uint.rs b/src/util/uint.rs index ab6c425cc7..b34d5a3772 100644 --- a/src/util/uint.rs +++ b/src/util/uint.rs @@ -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() @@ -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) @@ -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]