mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-04-29 03:47:55 +00:00
Rewrite Value::lookup to not require an allocation
This commit is contained in:
+10
-4
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user