Skip to content

Commit

Permalink
Deserialize decimal inputs on BlockNumber (#254)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacogr authored Dec 28, 2020
1 parent 3638157 commit 378221a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
34 changes: 31 additions & 3 deletions client/rpc-core/src/types/block_number.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,41 @@ impl<'a> Visitor<'a> for BlockNumberVisitor {
_ if value.starts_with("0x") => u64::from_str_radix(&value[2..], 16).map(BlockNumber::Num).map_err(|e| {
Error::custom(format!("Invalid block number: {}", e))
}),
_ => {
Err(Error::custom("Invalid block number: missing 0x prefix".to_string()))
},
_ => u64::from_str_radix(&value, 10).map(BlockNumber::Num).map_err(|_| {
Error::custom("Invalid block number: non-decimal or missing 0x prefix".to_string())
}),
}
}

fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}

fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> where E: Error {
Ok(BlockNumber::Num(value))
}
}


#[cfg(test)]
mod tests {
use super::*;

fn match_block_number(block_number: BlockNumber) -> Option<u64> {
match block_number {
BlockNumber::Num(number) => Some(number),
_ => None
}
}

#[test]
fn block_number_deserialize() {
let bn_dec: BlockNumber = serde_json::from_str(r#""42""#).unwrap();
let bn_hex: BlockNumber = serde_json::from_str(r#""0x45""#).unwrap();
let bn_u64: BlockNumber = serde_json::from_str(r#"420"#).unwrap();

assert_eq!(match_block_number(bn_dec).unwrap(), 42 as u64);
assert_eq!(match_block_number(bn_hex).unwrap(), 69 as u64);
assert_eq!(match_block_number(bn_u64).unwrap(), 420 as u64);
}
}
10 changes: 7 additions & 3 deletions client/rpc-core/src/types/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ impl<'a> Visitor<'a> for IndexVisitor {
fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}

fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> where E: Error {
Ok(Index(value as usize))
}
}

#[cfg(test)]
Expand All @@ -69,9 +73,9 @@ mod tests {
use serde_json;

#[test]
fn block_number_deserialization() {
let s = r#"["0xa", "10"]"#;
fn index_deserialization() {
let s = r#"["0xa", "10", 42]"#;
let deserialized: Vec<Index> = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, vec![Index(10), Index(10)]);
assert_eq!(deserialized, vec![Index(10), Index(10), Index(42)]);
}
}

0 comments on commit 378221a

Please sign in to comment.