Add exhaustive From<T> impls for Value

This commit is contained in:
Sergio Benitez 2017-06-18 03:05:22 -07:00
parent 5c523f14d5
commit f936fcfb13

View file

@ -1,6 +1,7 @@
//! Definition of a TOML value //! Definition of a TOML value
use std::collections::BTreeMap; use std::collections::{BTreeMap, HashMap};
use std::hash::Hash;
use std::fmt; use std::fmt;
use std::ops; use std::ops;
use std::str::FromStr; use std::str::FromStr;
@ -219,47 +220,62 @@ impl<I> ops::IndexMut<I> for Value where I: Index {
} }
} }
impl From<String> for Value { impl<'a> From<&'a str> for Value {
fn from(val: String) -> Value { #[inline]
Value::String(val) fn from(val: &'a str) -> Value {
Value::String(val.to_string())
} }
} }
impl From<i64> for Value { impl<V: Into<Value>> From<Vec<V>> for Value {
fn from(val: i64) -> Value { fn from(val: Vec<V>) -> Value {
Value::Integer(val) Value::Array(val.into_iter().map(|v| v.into()).collect())
} }
} }
impl From<f64> for Value { impl<S: Into<String>, V: Into<Value>> From<BTreeMap<S, V>> for Value {
fn from(val: f64) -> Value { fn from(val: BTreeMap<S, V>) -> Value {
Value::Float(val) let table = val.into_iter()
.map(|(s, v)| (s.into(), v.into()))
.collect();
Value::Table(table)
} }
} }
impl From<bool> for Value { impl<S: Into<String> + Hash + Eq, V: Into<Value>> From<HashMap<S, V>> for Value {
fn from(val: bool) -> Value { fn from(val: HashMap<S, V>) -> Value {
Value::Boolean(val) let table = val.into_iter()
.map(|(s, v)| (s.into(), v.into()))
.collect();
Value::Table(table)
} }
} }
impl From<Array> for Value { macro_rules! impl_into_value {
fn from(val: Array) -> Value { ($variant:ident : $T:ty) => (impl_into_value!($variant: $T,););
Value::Array(val) ($variant:ident : $T:ty, $($extra:tt)*) => (
} impl From<$T> for Value {
#[inline]
fn from(val: $T) -> Value {
Value::$variant(val $($extra)*)
}
}
)
} }
impl From<Table> for Value { impl_into_value!(String: String);
fn from(val: Table) -> Value { impl_into_value!(Integer: i64);
Value::Table(val) impl_into_value!(Integer: isize, as i64);
} impl_into_value!(Integer: i32, as i64);
} impl_into_value!(Integer: i8, as i64);
impl_into_value!(Integer: u8, as i64);
impl From<Datetime> for Value { impl_into_value!(Integer: u32, as i64);
fn from(val: Datetime) -> Value { impl_into_value!(Float: f64);
Value::Datetime(val) impl_into_value!(Float: f32, as f64);
} impl_into_value!(Boolean: bool);
} impl_into_value!(Datetime: Datetime);
/// Types that can be used to index a `toml::Value` /// Types that can be used to index a `toml::Value`
/// ///