Implement FieldPath::walk()

This commit is contained in:
Matthias Beyer 2016-02-02 15:53:49 +01:00
parent 012ca4a427
commit 0dc88877c6
2 changed files with 41 additions and 3 deletions

View File

@ -1,11 +1,40 @@
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use std::fmt::Error as FmtError; use std::fmt::Error as FmtError;
#[derive(Debug)] use toml::Value;
#[derive(Clone, Debug)]
pub struct FieldPathElement { pub struct FieldPathElement {
name: String 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 { impl Display for FieldPathElement {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> { fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {

View File

@ -20,7 +20,9 @@ pub struct FieldPath {
impl FieldPath { impl FieldPath {
pub fn new(elements: Vec<FieldPathElement>) -> FieldPath { pub fn new(elements: Vec<FieldPathElement>) -> FieldPath {
unimplemented!() FieldPath {
elements: elements,
}
} }
pub fn compile(source: String) -> Result<FieldPath, FieldPathParsingError> { pub fn compile(source: String) -> Result<FieldPath, FieldPathParsingError> {
@ -28,7 +30,14 @@ impl FieldPath {
} }
pub fn walk(&self, e: &EntryHeader) -> Option<Value> { 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))
})
} }
} }