From 67ae602e2a502a79d2459f10622d4340152a795c Mon Sep 17 00:00:00 2001 From: Nadav Ivgi Date: Wed, 30 Dec 2020 05:26:50 +0200 Subject: [PATCH] Implement Uint::from_be_slice() Needed because Rust 1.29 does not easily allow converting from a slice into an array. --- src/util/uint.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/util/uint.rs b/src/util/uint.rs index 16592727..fa7ebd58 100644 --- a/src/util/uint.rs +++ b/src/util/uint.rs @@ -90,9 +90,23 @@ macro_rules! construct_uint { } } - /// Creates big integer value from a byte slice array using + /// 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) + } + + /// Creates big integer value from a byte slice using + /// big-endian encoding + 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() @@ -420,6 +434,13 @@ macro_rules! construct_uint { construct_uint!(Uint256, 4); construct_uint!(Uint128, 2); +/// Uint error +#[derive(Debug)] +pub enum Error { + /// Invalid slice length (actual, expected) + InvalidLength(usize, usize), +} + impl Uint256 { /// Increment by 1 #[inline]