Skip to content

Commit

Permalink
more accurate json test
Browse files Browse the repository at this point in the history
  • Loading branch information
Geal committed Feb 12, 2018
1 parent 233ce7c commit 4db765c
Showing 1 changed file with 14 additions and 36 deletions.
50 changes: 14 additions & 36 deletions tests/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
#[macro_use]
extern crate nom;

use nom::{digit, alphanumeric};
use nom::{digit, is_alphanumeric, alphanumeric, space, recognize_float};

use std::str::{self, FromStr};
use std::collections::HashMap;
Expand All @@ -16,38 +16,16 @@ pub enum JsonValue {
Object(HashMap<String, JsonValue>),
}

// FIXME: since we already parsed a serie of digits and dots,
// we know it is correct UTF-8. no need to use from_utf8 to
// verify it is correct
// FIXME: use alt_complete (implement ws for alt_complete)
named!(unsigned_float <f32>, map_res!(
map_res!(
recognize!(
alt_complete!(
delimited!(digit, tag!("."), opt!(complete!(digit))) |
delimited!(opt!(digit), tag!("."), digit) |
digit
)
),
str::from_utf8
),
FromStr::from_str
));
named!(float<f32>, map!(
pair!(
opt!(alt!(tag!("+") | tag!("-"))),
unsigned_float
),
|(sign, value): (Option<&[u8]>, f32)| {
sign.and_then(|s| if s[0] == (b'-') { Some(-1f32) } else { None }).unwrap_or(1f32) * value
}
));
named!(float<f32>,
flat_map!(recognize_float, parse_to!(f32))
);

//FIXME: verify how json strings are formatted
named!(string<&str>,
delimited!(
tag!("\""),
map_res!(escaped!(call!(alphanumeric), '\\', is_a!("\"n\\")), str::from_utf8),
//map_res!(escaped!(call!(alphanumeric), '\\', is_a!("\"n\\")), str::from_utf8),
map_res!(escaped!(take_while1!(is_alphanumeric), '\\', one_of!("\"n\\")), str::from_utf8),
tag!("\"")
)
);
Expand Down Expand Up @@ -94,10 +72,10 @@ named!(hash< HashMap<String,JsonValue> >,
named!(value<JsonValue>,
ws!(
alt!(
hash => { |h| JsonValue::Object(h) } |
array => { |v| JsonValue::Array(v) } |
string => { |s| JsonValue::Str(String::from(s)) } |
float => { |num| JsonValue::Num(num) }
dbg_dmp!(hash) => { |h| JsonValue::Object(h) } |
dbg_dmp!(array) => { |v| JsonValue::Array(v) } |
dbg_dmp!(string) => { |s| JsonValue::Str(String::from(s)) } |
dbg_dmp!(float) => { |num| JsonValue::Num(num) }
)
)
);
Expand All @@ -108,10 +86,10 @@ named!(value<JsonValue>,
fn hash_test() {
let test = &b" { \"a\"\t: 42,
\"b\": \"x\"
}";
}\0";

//FIXME: top level value must be an object?
println!("{:?}", value(&test[..]));
println!("{:?}", value(&test[..]).unwrap());
//assert!(false);
}

Expand All @@ -121,9 +99,9 @@ fn parse_example_test() {
\"b\": [ \"x\", \"y\", 12 ] ,
\"c\": { \"hello\" : \"world\"
}
}";
}\0";

//FIXME: top level value must be an object?
println!("{:?}", value(&test[..]));
println!("{:?}", value(&test[..]).unwrap());
//assert!(false);
}

0 comments on commit 4db765c

Please sign in to comment.