Implement FieldPath::walk()
This commit is contained in:
parent
012ca4a427
commit
0dc88877c6
2 changed files with 41 additions and 3 deletions
|
@ -1,11 +1,40 @@
|
|||
use std::fmt::{Display, Formatter};
|
||||
use std::fmt::Error as FmtError;
|
||||
|
||||
#[derive(Debug)]
|
||||
use toml::Value;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FieldPathElement {
|
||||
name: String
|
||||
}
|
||||
|
||||
impl FieldPathElement {
|
||||
|
||||
pub fn new(name: String) -> FieldPathElement {
|
||||
FieldPathElement { name: name }
|
||||
}
|
||||
|
||||
pub fn apply(&self, value: Value) -> Option<Value> {
|
||||
use std::str::FromStr;
|
||||
use std::ops::Index;
|
||||
|
||||
match value {
|
||||
Value::Table(t) => {
|
||||
t.get(&self.name).map(|a| a.clone())
|
||||
},
|
||||
|
||||
Value::Array(a) => {
|
||||
usize::from_str(&self.name[..])
|
||||
.ok()
|
||||
.and_then(|i| Some(a[i].clone()))
|
||||
},
|
||||
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Display for FieldPathElement {
|
||||
|
||||
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
|
||||
|
|
|
@ -20,7 +20,9 @@ pub struct FieldPath {
|
|||
impl FieldPath {
|
||||
|
||||
pub fn new(elements: Vec<FieldPathElement>) -> FieldPath {
|
||||
unimplemented!()
|
||||
FieldPath {
|
||||
elements: elements,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compile(source: String) -> Result<FieldPath, FieldPathParsingError> {
|
||||
|
@ -28,7 +30,14 @@ impl FieldPath {
|
|||
}
|
||||
|
||||
pub fn walk(&self, e: &EntryHeader) -> Option<Value> {
|
||||
unimplemented!()
|
||||
let init_val : Value = Value::Table(e.toml().clone());
|
||||
|
||||
self.elements
|
||||
.clone()
|
||||
.into_iter()
|
||||
.fold(Some(init_val), |acc: Option<Value>, token: FieldPathElement| {
|
||||
acc.and_then(|element| token.apply(element))
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue