Rewrite Value::lookup to not require an allocation

This commit is contained in:
Erick Tryzelaar
2015-05-18 22:19:30 -07:00
parent 5fe85128c2
commit 50cac7f985
2 changed files with 19 additions and 4 deletions
+10 -4
View File
@@ -37,8 +37,8 @@ impl Value {
/// Otherwise, it will return the `Value` associated with the final key.
pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Value>{
let mut target = self;
for key in keys.iter() {
match target.find(*key) {
for key in keys {
match target.find(key) {
Some(t) => { target = t; },
None => return None
}
@@ -58,8 +58,14 @@ impl Value {
/// assert!(obj.lookup("x.a").unwrap() == &Value::U64(1));
/// ```
pub fn lookup<'a>(&'a self, path: &'a str) -> Option<&'a Value> {
let paths = path.split('.').collect::<Vec<&str>>();
self.find_path(&paths)
let mut target = self;
for key in path.split('.') {
match target.find(key) {
Some(t) => { target = t; },
None => return None
}
}
Some(target)
}
/// If the `Value` is an Object, performs a depth-first search until
+9
View File
@@ -1066,6 +1066,15 @@ fn test_missing_fmt_renamed_field() {
assert_eq!(value, Foo { x: Some(5) });
}
#[test]
fn test_find_path() {
let obj: Value = json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();
assert!(obj.find_path(&["x", "a"]).unwrap() == &Value::U64(1));
assert!(obj.find_path(&["y"]).unwrap() == &Value::U64(2));
assert!(obj.find_path(&["z"]).is_none());
}
#[test]
fn test_lookup() {
let obj: Value = json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();