Make NumberOrHex a common primitive. (#6321)

* Make NumberOrHex a common primitive.

* Update primitives/rpc/src/number.rs

Co-authored-by: Nikolay Volf <nikvolf@gmail.com>

Co-authored-by: Nikolay Volf <nikvolf@gmail.com>
This commit is contained in:
Sergei Shulepov
2020-06-10 17:08:15 +02:00
committed by GitHub
parent 62412ab03c
commit 3ec4844616
5 changed files with 103 additions and 60 deletions
+56 -41
View File
@@ -15,65 +15,79 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//! Chain RPC Block number type.
//! A number type that can be serialized both as a number or a string that encodes a number in a
//! string.
use serde::{Serialize, Deserialize};
use std::{convert::TryFrom, fmt::Debug};
use serde::{Serialize, Deserialize};
use sp_core::U256;
/// RPC Block number type
/// A number type that can be serialized both as a number or a string that encodes a number in a
/// string.
///
/// We allow two representations of the block number as input.
/// Either we deserialize to the type that is specified in the block type
/// or we attempt to parse given hex value.
/// We do that for consistency with the returned type, default generic header
/// serializes block number as hex to avoid overflows in JavaScript.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
/// We allow two representations of the block number as input. Either we deserialize to the type
/// that is specified in the block type or we attempt to parse given hex value.
///
/// The primary motivation for having this type is to avoid overflows when using big integers in
/// JavaScript (which we consider as an important RPC API consumer).
#[derive(Copy, Clone, Serialize, Deserialize, Debug, PartialEq)]
#[serde(untagged)]
pub enum NumberOrHex<Number> {
/// The original header number type of block.
Number(Number),
/// Hex representation of the block number.
pub enum NumberOrHex {
/// The number represented directly.
Number(u64),
/// Hex representation of the number.
Hex(U256),
}
impl<Number: TryFrom<u64> + From<u32> + Debug + PartialOrd> NumberOrHex<Number> {
/// Attempts to convert into concrete block number.
///
/// Fails in case hex number is too big.
pub fn to_number(self) -> Result<Number, String> {
let num = match self {
NumberOrHex::Number(n) => n,
NumberOrHex::Hex(h) => {
let l = h.low_u64();
if U256::from(l) != h {
return Err(format!("`{}` does not fit into u64 type; unsupported for now.", h))
} else {
Number::try_from(l)
.map_err(|_| format!("`{}` does not fit into block number type.", h))?
}
},
};
// FIXME <2329>: Database seems to limit the block number to u32 for no reason
if num > Number::from(u32::max_value()) {
return Err(format!("`{:?}` > u32::max_value(), the max block number is u32.", num))
impl NumberOrHex {
/// Converts this number into an U256.
pub fn into_u256(self) -> U256 {
match self {
NumberOrHex::Number(n) => n.into(),
NumberOrHex::Hex(h) => h,
}
Ok(num)
}
}
impl From<u64> for NumberOrHex<u64> {
impl From<u64> for NumberOrHex {
fn from(n: u64) -> Self {
NumberOrHex::Number(n)
}
}
impl<Number> From<U256> for NumberOrHex<Number> {
impl From<U256> for NumberOrHex {
fn from(n: U256) -> Self {
NumberOrHex::Hex(n)
}
}
/// An error type that signals an out-of-range conversion attempt.
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())
}
}
}
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())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -81,10 +95,11 @@ mod tests {
#[test]
fn should_serialize_and_deserialize() {
assert_deser(r#""0x1234""#, NumberOrHex::<u128>::Hex(0x1234.into()));
assert_deser(r#""0x0""#, NumberOrHex::<u64>::Hex(0.into()));
assert_deser(r#"5"#, NumberOrHex::Number(5_u64));
assert_deser(r#"10000"#, NumberOrHex::Number(10000_u32));
assert_deser(r#"0"#, NumberOrHex::Number(0_u16));
assert_deser(r#""0x1234""#, NumberOrHex::Hex(0x1234.into()));
assert_deser(r#""0x0""#, NumberOrHex::Hex(0.into()));
assert_deser(r#"5"#, NumberOrHex::Number(5));
assert_deser(r#"10000"#, NumberOrHex::Number(10000));
assert_deser(r#"0"#, NumberOrHex::Number(0));
assert_deser(r#"1000000000000"#, NumberOrHex::Number(1000000000000));
}
}