#![doc(html_root_url = "http://alexcrichton.com/toml-rs")]
#![feature(core)]
#![deny(missing_docs)]
#![cfg_attr(test, deny(warnings))]
extern crate rustc_serialize;
use std::collections::BTreeMap;
use std::str::FromStr;
use std::string;
pub use parser::{Parser, ParserError};
pub use serialization::{Encoder, encode, encode_str};
pub use serialization::{Decoder, decode, decode_str};
pub use serialization::Error;
pub use serialization::Error::{NeedsKey, NoValue};
pub use serialization::Error::{InvalidMapKeyLocation, InvalidMapKeyType};
pub use serialization::{DecodeError, DecodeErrorKind};
pub use serialization::DecodeErrorKind::{ApplicationError, ExpectedField};
pub use serialization::DecodeErrorKind::{ExpectedMapElement, ExpectedMapKey, NoEnumVariants};
pub use serialization::DecodeErrorKind::{ExpectedType, NilTooLong};
mod parser;
mod display;
mod serialization;
#[derive(PartialEq, Clone, Debug)]
#[allow(missing_docs)]
pub enum Value {
String(String),
Integer(i64),
Float(f64),
Boolean(bool),
Datetime(String),
Array(Array),
Table(Table),
}
pub type Array = Vec<Value>;
pub type Table = BTreeMap<string::String, Value>;
impl Value {
pub fn same_type(&self, other: &Value) -> bool {
match (self, other) {
(&Value::String(..), &Value::String(..)) |
(&Value::Integer(..), &Value::Integer(..)) |
(&Value::Float(..), &Value::Float(..)) |
(&Value::Boolean(..), &Value::Boolean(..)) |
(&Value::Datetime(..), &Value::Datetime(..)) |
(&Value::Array(..), &Value::Array(..)) |
(&Value::Table(..), &Value::Table(..)) => true,
_ => false,
}
}
pub fn type_str(&self) -> &'static str {
match *self {
Value::String(..) => "string",
Value::Integer(..) => "integer",
Value::Float(..) => "float",
Value::Boolean(..) => "boolean",
Value::Datetime(..) => "datetime",
Value::Array(..) => "array",
Value::Table(..) => "table",
}
}
pub fn as_str<'a>(&'a self) -> Option<&'a str> {
match *self { Value::String(ref s) => Some(&**s), _ => None }
}
pub fn as_integer(&self) -> Option<i64> {
match *self { Value::Integer(i) => Some(i), _ => None }
}
pub fn as_float(&self) -> Option<f64> {
match *self { Value::Float(f) => Some(f), _ => None }
}
pub fn as_bool(&self) -> Option<bool> {
match *self { Value::Boolean(b) => Some(b), _ => None }
}
pub fn as_datetime<'a>(&'a self) -> Option<&'a str> {
match *self { Value::Datetime(ref s) => Some(&**s), _ => None }
}
pub fn as_slice<'a>(&'a self) -> Option<&'a [Value]> {
match *self { Value::Array(ref s) => Some(&**s), _ => None }
}
pub fn as_table<'a>(&'a self) -> Option<&'a Table> {
match *self { Value::Table(ref s) => Some(s), _ => None }
}
pub fn lookup<'a>(&'a self, path: &'a str) -> Option<&'a Value> {
let mut cur_value = self;
for key in path.split('.') {
match cur_value {
&Value::Table(ref hm) => {
match hm.get(key) {
Some(v) => cur_value = v,
None => return None
}
},
&Value::Array(ref v) => {
match key.parse::<usize>().ok() {
Some(idx) if idx < v.len() => cur_value = &v[idx],
_ => return None
}
},
_ => return None
}
};
Some(cur_value)
}
}
impl rustc_serialize::Encodable for Value {
fn encode<E>(&self, e: &mut E) -> Result<(), E::Error>
where E: rustc_serialize::Encoder
{
match *self {
Value::String(ref s) => e.emit_str(s),
Value::Integer(i) => e.emit_i64(i),
Value::Float(f) => e.emit_f64(f),
Value::Boolean(b) => e.emit_bool(b),
Value::Datetime(ref s) => e.emit_str(s),
Value::Array(ref a) => {
e.emit_seq(a.len(), |e| {
for item in a {
try!(item.encode(e));
}
Ok(())
})
}
Value::Table(ref t) => {
e.emit_map(t.len(), |e| {
for (i, (key, value)) in t.iter().enumerate() {
try!(e.emit_map_elt_key(i, |e| e.emit_str(key)));
try!(e.emit_map_elt_val(i, |e| value.encode(e)));
}
Ok(())
})
}
}
}
}
impl FromStr for Value {
type Err = Vec<ParserError>;
fn from_str(s: &str) -> Result<Value, Vec<ParserError>> {
let mut p = Parser::new(s);
match p.parse().map(Value::Table) {
Some(n) => Ok(n),
None => Err(p.errors),
}
}
}
#[cfg(test)]
mod tests {
use super::Value;
#[test]
fn lookup_valid() {
let toml = r#"
[test]
foo = "bar"
[[values]]
foo = "baz"
[[values]]
foo = "qux"
"#;
let value: Value = toml.parse().unwrap();
let test_foo = value.lookup("test.foo").unwrap();
assert_eq!(test_foo.as_str().unwrap(), "bar");
let foo1 = value.lookup("values.1.foo").unwrap();
assert_eq!(foo1.as_str().unwrap(), "qux");
assert!(value.lookup("test.bar").is_none());
assert!(value.lookup("test.foo.bar").is_none());
}
#[test]
fn lookup_invalid_index() {
let toml = r#"
[[values]]
foo = "baz"
"#;
let value: Value = toml.parse().unwrap();
let foo = value.lookup("test.foo");
assert!(foo.is_none());
let foo = value.lookup("values.100.foo");
assert!(foo.is_none());
let foo = value.lookup("values.str.foo");
assert!(foo.is_none());
}
#[test]
fn round_trip() {
let toml = r#"
[test]
foo = "bar"
[[values]]
foo = "baz"
[[values]]
foo = "qux"
"#;
let value: Value = toml.parse().unwrap();
let val2 = ::encode_str(&value).parse().unwrap();
assert_eq!(value, val2);
}
}