Skip to content

Commit

Permalink
Implements as_number() for serde_json::Value
Browse files Browse the repository at this point in the history
  • Loading branch information
tailhook committed Sep 11, 2017
1 parent ba37973 commit 0f31455
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::usize;
use serde_json::Value;

use {DataError, Variable, Var, Context, Template, RenderError, Pos, Output};
use {Number};

pub const TRUE: &'static &'static str = &"true";
pub const FALSE: &'static &'static str = &"false";
Expand Down Expand Up @@ -54,13 +55,28 @@ impl<'render> Variable<'render> for Value {
use serde_json::Value::*;
match *self {
Number(ref val)
if val.as_u64() .map(|x| x <= usize::MAX as u64).unwrap_or(false)
if val.as_u64().map(|x| x <= usize::MAX as u64).unwrap_or(false)
=> Ok(val.as_u64().unwrap() as usize),
// TODO(tailhook) try use float too
// TODO(tailhook) show out of range int error
_ => Err(DataError::IntKeyUnsupported(self.typename())),
}
}
fn as_number(&self) -> Result<Number, DataError> {
use serde_json::Value::*;
match *self {
Number(ref val) if val.is_u64() => {
Ok(val.as_u64().unwrap().into())
}
Number(ref val) if val.is_i64() => {
Ok(val.as_i64().unwrap().into())
}
Number(ref val) if val.is_f64() => {
Ok(val.as_f64().unwrap().into())
}
_ => Err(DataError::NumberUnsupported(self.typename())),
}
}
fn output(&self) -> Result<Output, DataError> {
use serde_json::Value::*;
match *self {
Expand Down
18 changes: 18 additions & 0 deletions src/tests/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,24 @@ fn attr() {
"2 + 73");
}

#[test]
#[cfg(feature="json")]
fn sum_json() {
assert_eq!(
render_json("{{ x.a + x.b }}",
r#"{"x": {"a": 2, "b": 73}}"#),
"75");
}

#[test]
#[cfg(feature="json")]
fn prod_json() {
assert_eq!(
render_json("{{ x.a * x.b }}",
r#"{"x": {"a": 2, "b": 73}}"#),
"146");
}

#[test]
#[cfg(feature="json")]
fn item() {
Expand Down

0 comments on commit 0f31455

Please sign in to comment.