implement more convertion on NumberOrHex (#7682)

This commit is contained in:
Guillaume Thiolliere
2020-12-08 10:10:46 +01:00
committed by GitHub
parent 588461f52a
commit f6198b4c1b
+16 -13
View File
@@ -18,7 +18,7 @@
//! A number type that can be serialized both as a number or a string that encodes a number in a
//! string.
use std::{convert::TryFrom, fmt::Debug};
use std::{convert::{TryFrom, TryInto}, fmt::Debug};
use serde::{Serialize, Deserialize};
use sp_core::U256;
@@ -67,24 +67,27 @@ pub struct TryFromIntError(pub(crate) ());
impl TryFrom<NumberOrHex> for u32 {
type Error = TryFromIntError;
fn try_from(num_or_hex: NumberOrHex) -> Result<u32, TryFromIntError> {
let num_or_hex = num_or_hex.into_u256();
if num_or_hex > U256::from(u32::max_value()) {
return Err(TryFromIntError(()));
} else {
Ok(num_or_hex.as_u32())
}
num_or_hex.into_u256().try_into().map_err(|_| TryFromIntError(()))
}
}
impl TryFrom<NumberOrHex> for u64 {
type Error = TryFromIntError;
fn try_from(num_or_hex: NumberOrHex) -> Result<u64, TryFromIntError> {
let num_or_hex = num_or_hex.into_u256();
if num_or_hex > U256::from(u64::max_value()) {
return Err(TryFromIntError(()));
} else {
Ok(num_or_hex.as_u64())
}
num_or_hex.into_u256().try_into().map_err(|_| TryFromIntError(()))
}
}
impl TryFrom<NumberOrHex> for u128 {
type Error = TryFromIntError;
fn try_from(num_or_hex: NumberOrHex) -> Result<u128, TryFromIntError> {
num_or_hex.into_u256().try_into().map_err(|_| TryFromIntError(()))
}
}
impl From<NumberOrHex> for U256 {
fn from(num_or_hex: NumberOrHex) -> U256 {
num_or_hex.into_u256()
}
}