Switch to a single-variant error type, implement standard derives

This commit is contained in:
Nadav Ivgi 2021-01-14 22:17:18 +02:00
parent 4a7cf34eeb
commit 0df86b4426
No known key found for this signature in database
GPG Key ID: 81F6104CD0F150FC
1 changed files with 16 additions and 7 deletions

View File

@ -98,9 +98,9 @@ macro_rules! construct_uint {
/// Creates big integer value from a byte slice using /// Creates big integer value from a byte slice using
/// big-endian encoding /// big-endian encoding
pub fn from_be_slice(bytes: &[u8]) -> Result<$name, Error> { pub fn from_be_slice(bytes: &[u8]) -> Result<$name, ParseLengthError> {
if bytes.len() != $n_words * 8 { if bytes.len() != $n_words * 8 {
Err(Error::InvalidLength(bytes.len(), $n_words*8)) Err(ParseLengthError { actual: bytes.len(), expected: $n_words*8 })
} else { } else {
Ok(Self::_from_be_slice(bytes)) Ok(Self::_from_be_slice(bytes))
} }
@ -493,11 +493,20 @@ macro_rules! construct_uint {
construct_uint!(Uint256, 4); construct_uint!(Uint256, 4);
construct_uint!(Uint128, 2); construct_uint!(Uint128, 2);
/// Uint error /// Invalid slice length
#[derive(Debug)] #[derive(Debug, PartialEq, PartialOrd, Clone, Copy, Hash)]
pub enum Error { /// Invalid slice length
/// Invalid slice length (actual, expected) pub struct ParseLengthError {
InvalidLength(usize, usize), /// The length of the slice de-facto
pub actual: usize,
/// The required length of the slice
pub expected: usize,
}
impl ::std::fmt::Display for ParseLengthError {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "Invalid length: got {}, expected {}", self.actual, self.expected)
}
} }
impl Uint256 { impl Uint256 {