Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Commit

Permalink
implement more convertion on NumberOrHex (#7682)
Browse files Browse the repository at this point in the history
  • Loading branch information
gui1117 authored Dec 8, 2020
1 parent ec55d65 commit 163412d
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions primitives/rpc/src/number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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()
}
}

Expand Down

0 comments on commit 163412d

Please sign in to comment.