mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-06-17 20:51:02 +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.
|
/// Otherwise, it will return the `Value` associated with the final key.
|
||||||
pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Value>{
|
pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Value>{
|
||||||
let mut target = self;
|
let mut target = self;
|
||||||
for key in keys.iter() {
|
for key in keys {
|
||||||
match target.find(*key) {
|
match target.find(key) {
|
||||||
Some(t) => { target = t; },
|
Some(t) => { target = t; },
|
||||||
None => return None
|
None => return None
|
||||||
}
|
}
|
||||||
@@ -58,8 +58,14 @@ impl Value {
|
|||||||
/// assert!(obj.lookup("x.a").unwrap() == &Value::U64(1));
|
/// assert!(obj.lookup("x.a").unwrap() == &Value::U64(1));
|
||||||
/// ```
|
/// ```
|
||||||
pub fn lookup<'a>(&'a self, path: &'a str) -> Option<&'a Value> {
|
pub fn lookup<'a>(&'a self, path: &'a str) -> Option<&'a Value> {
|
||||||
let paths = path.split('.').collect::<Vec<&str>>();
|
let mut target = self;
|
||||||
self.find_path(&paths)
|
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
|
/// 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) });
|
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]
|
#[test]
|
||||||
fn test_lookup() {
|
fn test_lookup() {
|
||||||
let obj: Value = json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();
|
let obj: Value = json::from_str(r#"{"x": {"a": 1}, "y": 2}"#).unwrap();
|
||||||
|
|||||||
Reference in New Issue
Block a user