Run cargo fmt

This commit is contained in:
Alex Crichton 2018-12-17 17:45:35 -08:00
parent b2013e4548
commit cbfc4e18f8
8 changed files with 1097 additions and 792 deletions

View file

@ -1,24 +1,24 @@
#![deny(warnings)] #![deny(warnings)]
extern crate toml;
extern crate serde_json; extern crate serde_json;
extern crate toml;
use std::fs::File;
use std::env; use std::env;
use std::fs::File;
use std::io; use std::io;
use std::io::prelude::*; use std::io::prelude::*;
use toml::Value as Toml;
use serde_json::Value as Json; use serde_json::Value as Json;
use toml::Value as Toml;
fn main() { fn main() {
let mut args = env::args(); let mut args = env::args();
let mut input = String::new(); let mut input = String::new();
if args.len() > 1 { if args.len() > 1 {
let name = args.nth(1).unwrap(); let name = args.nth(1).unwrap();
File::open(&name).and_then(|mut f| { File::open(&name)
f.read_to_string(&mut input) .and_then(|mut f| f.read_to_string(&mut input))
}).unwrap(); .unwrap();
} else { } else {
io::stdin().read_to_string(&mut input).unwrap(); io::stdin().read_to_string(&mut input).unwrap();
} }
@ -37,15 +37,14 @@ fn convert(toml: Toml) -> Json {
Toml::String(s) => Json::String(s), Toml::String(s) => Json::String(s),
Toml::Integer(i) => Json::Number(i.into()), Toml::Integer(i) => Json::Number(i.into()),
Toml::Float(f) => { Toml::Float(f) => {
let n = serde_json::Number::from_f64(f) let n = serde_json::Number::from_f64(f).expect("float infinite and nan not allowed");
.expect("float infinite and nan not allowed");
Json::Number(n) Json::Number(n)
} }
Toml::Boolean(b) => Json::Bool(b), Toml::Boolean(b) => Json::Bool(b),
Toml::Array(arr) => Json::Array(arr.into_iter().map(convert).collect()), Toml::Array(arr) => Json::Array(arr.into_iter().map(convert).collect()),
Toml::Table(table) => Json::Object(table.into_iter().map(|(k, v)| { Toml::Table(table) => {
(k, convert(v)) Json::Object(table.into_iter().map(|(k, v)| (k, convert(v))).collect())
}).collect()), }
Toml::Datetime(dt) => Json::String(dt.to_string()), Toml::Datetime(dt) => Json::String(dt.to_string()),
} }
} }

View file

@ -1,6 +1,6 @@
use std::error;
use std::fmt; use std::fmt;
use std::str::{self, FromStr}; use std::str::{self, FromStr};
use std::error;
use serde::{de, ser}; use serde::{de, ser};
@ -109,9 +109,7 @@ impl fmt::Display for Offset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
Offset::Z => write!(f, "Z"), Offset::Z => write!(f, "Z"),
Offset::Custom { hours, minutes } => { Offset::Custom { hours, minutes } => write!(f, "{:+03}:{:02}", hours, minutes),
write!(f, "{:+03}:{:02}", hours, minutes)
}
} }
} }
} }
@ -127,7 +125,7 @@ impl FromStr for Datetime {
// 0000-00-00 // 0000-00-00
// 00:00:00.00 // 00:00:00.00
if date.len() < 3 { if date.len() < 3 {
return Err(DatetimeParseError { _private: () }) return Err(DatetimeParseError { _private: () });
} }
let mut offset_allowed = true; let mut offset_allowed = true;
let mut chars = date.chars(); let mut chars = date.chars();
@ -165,19 +163,19 @@ impl FromStr for Datetime {
}; };
if date.month < 1 || date.month > 12 { if date.month < 1 || date.month > 12 {
return Err(DatetimeParseError { _private: () }) return Err(DatetimeParseError { _private: () });
} }
if date.day < 1 || date.day > 31 { if date.day < 1 || date.day > 31 {
return Err(DatetimeParseError { _private: () }) return Err(DatetimeParseError { _private: () });
} }
Some(date) Some(date)
}; };
// Next parse the "partial-time" if available // Next parse the "partial-time" if available
let partial_time = if full_date.is_some() && let partial_time = if full_date.is_some()
(chars.clone().next() == Some('T') && (chars.clone().next() == Some('T') || chars.clone().next() == Some(' '))
|| chars.clone().next() == Some(' ')) { {
chars.next(); chars.next();
true true
} else { } else {
@ -208,7 +206,7 @@ impl FromStr for Datetime {
let mut end = whole.len(); let mut end = whole.len();
for (i, byte) in whole.bytes().enumerate() { for (i, byte) in whole.bytes().enumerate() {
match byte { match byte {
b'0' ... b'9' => { b'0'...b'9' => {
if i < 9 { if i < 9 {
let p = 10_u32.pow(8 - i as u32); let p = 10_u32.pow(8 - i as u32);
nanosecond += p * (byte - b'0') as u32; nanosecond += p * (byte - b'0') as u32;
@ -221,7 +219,7 @@ impl FromStr for Datetime {
} }
} }
if end == 0 { if end == 0 {
return Err(DatetimeParseError { _private: () }) return Err(DatetimeParseError { _private: () });
} }
chars = whole[end..].chars(); chars = whole[end..].chars();
} }
@ -234,16 +232,16 @@ impl FromStr for Datetime {
}; };
if time.hour > 24 { if time.hour > 24 {
return Err(DatetimeParseError { _private: () }) return Err(DatetimeParseError { _private: () });
} }
if time.minute > 59 { if time.minute > 59 {
return Err(DatetimeParseError { _private: () }) return Err(DatetimeParseError { _private: () });
} }
if time.second > 59 { if time.second > 59 {
return Err(DatetimeParseError { _private: () }) return Err(DatetimeParseError { _private: () });
} }
if time.nanosecond > 999_999_999 { if time.nanosecond > 999_999_999 {
return Err(DatetimeParseError { _private: () }) return Err(DatetimeParseError { _private: () });
} }
Some(time) Some(time)
@ -288,7 +286,7 @@ impl FromStr for Datetime {
// Return an error if we didn't hit eof, otherwise return our parsed // Return an error if we didn't hit eof, otherwise return our parsed
// date // date
if chars.next().is_some() { if chars.next().is_some() {
return Err(DatetimeParseError { _private: () }) return Err(DatetimeParseError { _private: () });
} }
Ok(Datetime { Ok(Datetime {
@ -308,7 +306,8 @@ fn digit(chars: &mut str::Chars) -> Result<u8, DatetimeParseError> {
impl ser::Serialize for Datetime { impl ser::Serialize for Datetime {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer where
S: ser::Serializer,
{ {
use serde::ser::SerializeStruct; use serde::ser::SerializeStruct;
@ -320,7 +319,8 @@ impl ser::Serialize for Datetime {
impl<'de> de::Deserialize<'de> for Datetime { impl<'de> de::Deserialize<'de> for Datetime {
fn deserialize<D>(deserializer: D) -> Result<Datetime, D::Error> fn deserialize<D>(deserializer: D) -> Result<Datetime, D::Error>
where D: de::Deserializer<'de> where
D: de::Deserializer<'de>,
{ {
struct DatetimeVisitor; struct DatetimeVisitor;
@ -332,15 +332,15 @@ impl<'de> de::Deserialize<'de> for Datetime {
} }
fn visit_map<V>(self, mut visitor: V) -> Result<Datetime, V::Error> fn visit_map<V>(self, mut visitor: V) -> Result<Datetime, V::Error>
where V: de::MapAccess<'de> where
V: de::MapAccess<'de>,
{ {
let value = visitor.next_key::<DatetimeKey>()?; let value = visitor.next_key::<DatetimeKey>()?;
if value.is_none() { if value.is_none() {
return Err(de::Error::custom("datetime key not found")) return Err(de::Error::custom("datetime key not found"));
} }
let v: DatetimeFromString = visitor.next_value()?; let v: DatetimeFromString = visitor.next_value()?;
Ok(v.value) Ok(v.value)
} }
} }
@ -353,7 +353,8 @@ struct DatetimeKey;
impl<'de> de::Deserialize<'de> for DatetimeKey { impl<'de> de::Deserialize<'de> for DatetimeKey {
fn deserialize<D>(deserializer: D) -> Result<DatetimeKey, D::Error> fn deserialize<D>(deserializer: D) -> Result<DatetimeKey, D::Error>
where D: de::Deserializer<'de> where
D: de::Deserializer<'de>,
{ {
struct FieldVisitor; struct FieldVisitor;
@ -365,7 +366,8 @@ impl<'de> de::Deserialize<'de> for DatetimeKey {
} }
fn visit_str<E>(self, s: &str) -> Result<(), E> fn visit_str<E>(self, s: &str) -> Result<(), E>
where E: de::Error where
E: de::Error,
{ {
if s == FIELD { if s == FIELD {
Ok(()) Ok(())
@ -386,7 +388,8 @@ pub struct DatetimeFromString {
impl<'de> de::Deserialize<'de> for DatetimeFromString { impl<'de> de::Deserialize<'de> for DatetimeFromString {
fn deserialize<D>(deserializer: D) -> Result<DatetimeFromString, D::Error> fn deserialize<D>(deserializer: D) -> Result<DatetimeFromString, D::Error>
where D: de::Deserializer<'de> where
D: de::Deserializer<'de>,
{ {
struct Visitor; struct Visitor;
@ -398,7 +401,8 @@ impl<'de> de::Deserialize<'de> for DatetimeFromString {
} }
fn visit_str<E>(self, s: &str) -> Result<DatetimeFromString, E> fn visit_str<E>(self, s: &str) -> Result<DatetimeFromString, E>
where E: de::Error, where
E: de::Error,
{ {
match s.parse() { match s.parse() {
Ok(date) => Ok(DatetimeFromString { value: date }), Ok(date) => Ok(DatetimeFromString { value: date }),

567
src/de.rs

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
pub use serde::de::{Deserialize, IntoDeserializer}; pub use serde::de::{Deserialize, IntoDeserializer};
use value::{Value, Table, Array}; use value::{Array, Table, Value};
/// Construct a [`toml::Value`] from TOML syntax. /// Construct a [`toml::Value`] from TOML syntax.
/// ///
@ -424,7 +424,10 @@ pub fn push_toml(root: &mut Value, path: &[&str]) {
if !target.is_array() { if !target.is_array() {
*target = Value::Array(Array::new()); *target = Value::Array(Array::new());
} }
target.as_array_mut().unwrap().push(Value::Table(Table::new())); target
.as_array_mut()
.unwrap()
.push(Value::Table(Table::new()));
} }
fn traverse<'a>(root: &'a mut Value, path: &[&str]) -> &'a mut Value { fn traverse<'a>(root: &'a mut Value, path: &[&str]) -> &'a mut Value {

File diff suppressed because it is too large Load diff

View file

@ -78,15 +78,18 @@ impl<T> Spanned<T> {
} }
impl<'de, T> de::Deserialize<'de> for Spanned<T> impl<'de, T> de::Deserialize<'de> for Spanned<T>
where T: de::Deserialize<'de> where
T: de::Deserialize<'de>,
{ {
fn deserialize<D>(deserializer: D) -> Result<Spanned<T>, D::Error> fn deserialize<D>(deserializer: D) -> Result<Spanned<T>, D::Error>
where D: de::Deserializer<'de> where
D: de::Deserializer<'de>,
{ {
struct SpannedVisitor<T>(::std::marker::PhantomData<T>); struct SpannedVisitor<T>(::std::marker::PhantomData<T>);
impl<'de, T> de::Visitor<'de> for SpannedVisitor<T> impl<'de, T> de::Visitor<'de> for SpannedVisitor<T>
where T: de::Deserialize<'de> where
T: de::Deserialize<'de>,
{ {
type Value = Spanned<T>; type Value = Spanned<T>;
@ -95,22 +98,23 @@ impl<'de, T> de::Deserialize<'de> for Spanned<T>
} }
fn visit_map<V>(self, mut visitor: V) -> Result<Spanned<T>, V::Error> fn visit_map<V>(self, mut visitor: V) -> Result<Spanned<T>, V::Error>
where V: de::MapAccess<'de> where
V: de::MapAccess<'de>,
{ {
if visitor.next_key()? != Some(START) { if visitor.next_key()? != Some(START) {
return Err(de::Error::custom("spanned start key not found")) return Err(de::Error::custom("spanned start key not found"));
} }
let start: usize = visitor.next_value()?; let start: usize = visitor.next_value()?;
if visitor.next_key()? != Some(END) { if visitor.next_key()? != Some(END) {
return Err(de::Error::custom("spanned end key not found")) return Err(de::Error::custom("spanned end key not found"));
} }
let end: usize = visitor.next_value()?; let end: usize = visitor.next_value()?;
if visitor.next_key()? != Some(VALUE) { if visitor.next_key()? != Some(VALUE) {
return Err(de::Error::custom("spanned value key not found")) return Err(de::Error::custom("spanned value key not found"));
} }
let value: T = visitor.next_value()?; let value: T = visitor.next_value()?;
@ -118,7 +122,7 @@ impl<'de, T> de::Deserialize<'de> for Spanned<T>
Ok(Spanned { Ok(Spanned {
start: start, start: start,
end: end, end: end,
value: value value: value,
}) })
} }
} }

View file

@ -38,7 +38,11 @@ pub enum Token<'a> {
RightBracket, RightBracket,
Keylike(&'a str), Keylike(&'a str),
String { src: &'a str, val: Cow<'a, str>, multiline: bool }, String {
src: &'a str,
val: Cow<'a, str>,
multiline: bool,
},
} }
#[derive(Eq, PartialEq, Debug)] #[derive(Eq, PartialEq, Debug)]
@ -53,7 +57,11 @@ pub enum Error {
NewlineInTableKey(usize), NewlineInTableKey(usize),
MultilineStringKey(usize), MultilineStringKey(usize),
EmptyTableKey(usize), EmptyTableKey(usize),
Wanted { at: usize, expected: &'static str, found: &'static str }, Wanted {
at: usize,
expected: &'static str,
found: &'static str,
},
} }
#[derive(Clone)] #[derive(Clone)]
@ -101,10 +109,16 @@ impl<'a> Tokenizer<'a> {
Some((start, '}')) => (start, RightBrace), Some((start, '}')) => (start, RightBrace),
Some((start, '[')) => (start, LeftBracket), Some((start, '[')) => (start, LeftBracket),
Some((start, ']')) => (start, RightBracket), Some((start, ']')) => (start, RightBracket),
Some((start, '\'')) => return self.literal_string(start) Some((start, '\'')) => {
.map(|t| Some((self.step_span(start), t))), return self
Some((start, '"')) => return self.basic_string(start) .literal_string(start)
.map(|t| Some((self.step_span(start), t))), .map(|t| Some((self.step_span(start), t)))
}
Some((start, '"')) => {
return self
.basic_string(start)
.map(|t| Some((self.step_span(start), t)))
}
Some((start, ch)) if is_keylike(ch) => (start, self.keylike(start)), Some((start, ch)) if is_keylike(ch) => (start, self.keylike(start)),
Some((start, ch)) => return Err(Error::Unexpected(start, ch)), Some((start, ch)) => return Err(Error::Unexpected(start, ch)),
@ -156,13 +170,11 @@ impl<'a> Tokenizer<'a> {
}) })
} }
} }
None => { None => Err(Error::Wanted {
Err(Error::Wanted { at: self.input.len(),
at: self.input.len(), expected: expected.describe(),
expected: expected.describe(), found: "eof",
found: "eof", }),
})
}
} }
} }
@ -170,33 +182,36 @@ impl<'a> Tokenizer<'a> {
let current = self.current(); let current = self.current();
match self.next()? { match self.next()? {
Some((span, Token::Keylike(k))) => Ok((span, k.into())), Some((span, Token::Keylike(k))) => Ok((span, k.into())),
Some((span, Token::String { src, val, multiline })) => { Some((
span,
Token::String {
src,
val,
multiline,
},
)) => {
let offset = self.substr_offset(src); let offset = self.substr_offset(src);
if multiline { if multiline {
return Err(Error::MultilineStringKey(offset)) return Err(Error::MultilineStringKey(offset));
} }
if val == "" { if val == "" {
return Err(Error::EmptyTableKey(offset)) return Err(Error::EmptyTableKey(offset));
} }
match src.find('\n') { match src.find('\n') {
None => Ok((span, val)), None => Ok((span, val)),
Some(i) => Err(Error::NewlineInTableKey(offset + i)), Some(i) => Err(Error::NewlineInTableKey(offset + i)),
} }
} }
Some((_, other)) => { Some((_, other)) => Err(Error::Wanted {
Err(Error::Wanted { at: current,
at: current, expected: "a table key",
expected: "a table key", found: other.describe(),
found: other.describe(), }),
}) None => Err(Error::Wanted {
} at: self.input.len(),
None => { expected: "a table key",
Err(Error::Wanted { found: "eof",
at: self.input.len(), }),
expected: "a table key",
found: "eof",
})
}
} }
} }
@ -209,7 +224,7 @@ impl<'a> Tokenizer<'a> {
pub fn eat_comment(&mut self) -> Result<bool, Error> { pub fn eat_comment(&mut self) -> Result<bool, Error> {
if !self.eatc('#') { if !self.eatc('#') {
return Ok(false) return Ok(false);
} }
drop(self.comment_token(0)); drop(self.comment_token(0));
self.eat_newline_or_eof().map(|()| true) self.eat_newline_or_eof().map(|()| true)
@ -218,23 +233,19 @@ impl<'a> Tokenizer<'a> {
pub fn eat_newline_or_eof(&mut self) -> Result<(), Error> { pub fn eat_newline_or_eof(&mut self) -> Result<(), Error> {
let current = self.current(); let current = self.current();
match self.next()? { match self.next()? {
None | None | Some((_, Token::Newline)) => Ok(()),
Some((_, Token::Newline)) => Ok(()), Some((_, other)) => Err(Error::Wanted {
Some((_, other)) => { at: current,
Err(Error::Wanted { expected: "newline",
at: current, found: other.describe(),
expected: "newline", }),
found: other.describe(),
})
}
} }
} }
pub fn skip_to_newline(&mut self) { pub fn skip_to_newline(&mut self) {
loop { loop {
match self.one() { match self.one() {
Some((_, '\n')) | Some((_, '\n')) | None => break,
None => break,
_ => {} _ => {}
} }
} }
@ -251,7 +262,11 @@ impl<'a> Tokenizer<'a> {
} }
pub fn current(&mut self) -> usize { pub fn current(&mut self) -> usize {
self.chars.clone().next().map(|i| i.0).unwrap_or(self.input.len()) self.chars
.clone()
.next()
.map(|i| i.0)
.unwrap_or(self.input.len())
} }
pub fn input(&self) -> &'a str { pub fn input(&self) -> &'a str {
@ -268,30 +283,35 @@ impl<'a> Tokenizer<'a> {
fn comment_token(&mut self, start: usize) -> Token<'a> { fn comment_token(&mut self, start: usize) -> Token<'a> {
while let Some((_, ch)) = self.chars.clone().next() { while let Some((_, ch)) = self.chars.clone().next() {
if ch != '\t' && (ch < '\u{20}' || ch > '\u{10ffff}') { if ch != '\t' && (ch < '\u{20}' || ch > '\u{10ffff}') {
break break;
} }
self.one(); self.one();
} }
Comment(&self.input[start..self.current()]) Comment(&self.input[start..self.current()])
} }
fn read_string(&mut self, fn read_string(
delim: char, &mut self,
start: usize, delim: char,
new_ch: &mut FnMut(&mut Tokenizer, &mut MaybeString, start: usize,
bool, usize, char) new_ch: &mut FnMut(
-> Result<(), Error>) &mut Tokenizer,
-> Result<Token<'a>, Error> { &mut MaybeString,
bool,
usize,
char,
) -> Result<(), Error>,
) -> Result<Token<'a>, Error> {
let mut multiline = false; let mut multiline = false;
if self.eatc(delim) { if self.eatc(delim) {
if self.eatc(delim) { if self.eatc(delim) {
multiline = true; multiline = true;
} else { } else {
return Ok(String { return Ok(String {
src: &self.input[start..start+2], src: &self.input[start..start + 2],
val: Cow::Borrowed(""), val: Cow::Borrowed(""),
multiline: false, multiline: false,
}) });
} }
} }
let mut val = MaybeString::NotEscaped(self.current()); let mut val = MaybeString::NotEscaped(self.current());
@ -309,9 +329,9 @@ impl<'a> Tokenizer<'a> {
} else { } else {
val.push('\n'); val.push('\n');
} }
continue continue;
} else { } else {
return Err(Error::NewlineInString(i)) return Err(Error::NewlineInString(i));
} }
} }
Some((i, ch)) if ch == delim => { Some((i, ch)) if ch == delim => {
@ -319,7 +339,7 @@ impl<'a> Tokenizer<'a> {
for _ in 0..2 { for _ in 0..2 {
if !self.eatc(delim) { if !self.eatc(delim) {
val.push(delim); val.push(delim);
continue 'outer continue 'outer;
} }
} }
} }
@ -327,10 +347,10 @@ impl<'a> Tokenizer<'a> {
src: &self.input[start..self.current()], src: &self.input[start..self.current()],
val: val.into_cow(&self.input[..i]), val: val.into_cow(&self.input[..i]),
multiline: multiline, multiline: multiline,
}) });
} }
Some((i, c)) => new_ch(self, &mut val, multiline, i, c)?, Some((i, c)) => new_ch(self, &mut val, multiline, i, c)?,
None => return Err(Error::UnterminatedString(start)) None => return Err(Error::UnterminatedString(start)),
} }
} }
} }
@ -347,61 +367,56 @@ impl<'a> Tokenizer<'a> {
} }
fn basic_string(&mut self, start: usize) -> Result<Token<'a>, Error> { fn basic_string(&mut self, start: usize) -> Result<Token<'a>, Error> {
self.read_string('"', start, &mut |me, val, multi, i, ch| { self.read_string('"', start, &mut |me, val, multi, i, ch| match ch {
match ch { '\\' => {
'\\' => { val.to_owned(&me.input[..i]);
val.to_owned(&me.input[..i]); match me.chars.next() {
match me.chars.next() { Some((_, '"')) => val.push('"'),
Some((_, '"')) => val.push('"'), Some((_, '\\')) => val.push('\\'),
Some((_, '\\')) => val.push('\\'), Some((_, 'b')) => val.push('\u{8}'),
Some((_, 'b')) => val.push('\u{8}'), Some((_, 'f')) => val.push('\u{c}'),
Some((_, 'f')) => val.push('\u{c}'), Some((_, 'n')) => val.push('\n'),
Some((_, 'n')) => val.push('\n'), Some((_, 'r')) => val.push('\r'),
Some((_, 'r')) => val.push('\r'), Some((_, 't')) => val.push('\t'),
Some((_, 't')) => val.push('\t'), Some((i, c @ 'u')) | Some((i, c @ 'U')) => {
Some((i, c @ 'u')) | let len = if c == 'u' { 4 } else { 8 };
Some((i, c @ 'U')) => { val.push(me.hex(start, i, len)?);
let len = if c == 'u' {4} else {8}; }
val.push(me.hex(start, i, len)?); Some((i, c @ ' ')) | Some((i, c @ '\t')) | Some((i, c @ '\n')) if multi => {
} if c != '\n' {
Some((i, c @ ' ')) |
Some((i, c @ '\t')) |
Some((i, c @ '\n')) if multi => {
if c != '\n' {
while let Some((_, ch)) = me.chars.clone().next() {
match ch {
' ' | '\t' => {
me.chars.next();
continue
},
'\n' => {
me.chars.next();
break
},
_ => return Err(Error::InvalidEscape(i, c)),
}
}
}
while let Some((_, ch)) = me.chars.clone().next() { while let Some((_, ch)) = me.chars.clone().next() {
match ch { match ch {
' ' | '\t' | '\n' => { ' ' | '\t' => {
me.chars.next(); me.chars.next();
continue;
} }
_ => break, '\n' => {
me.chars.next();
break;
}
_ => return Err(Error::InvalidEscape(i, c)),
} }
} }
} }
Some((i, c)) => return Err(Error::InvalidEscape(i, c)), while let Some((_, ch)) = me.chars.clone().next() {
None => return Err(Error::UnterminatedString(start)), match ch {
' ' | '\t' | '\n' => {
me.chars.next();
}
_ => break,
}
}
} }
Ok(()) Some((i, c)) => return Err(Error::InvalidEscape(i, c)),
None => return Err(Error::UnterminatedString(start)),
} }
ch if '\u{20}' <= ch && ch <= '\u{10ffff}' && ch != '\u{7f}' => { Ok(())
val.push(ch);
Ok(())
}
_ => Err(Error::InvalidCharInString(i, ch))
} }
ch if '\u{20}' <= ch && ch <= '\u{10ffff}' && ch != '\u{7f}' => {
val.push(ch);
Ok(())
}
_ => Err(Error::InvalidCharInString(i, ch)),
}) })
} }
@ -424,7 +439,7 @@ impl<'a> Tokenizer<'a> {
fn keylike(&mut self, start: usize) -> Token<'a> { fn keylike(&mut self, start: usize) -> Token<'a> {
while let Some((_, ch)) = self.peek_one() { while let Some((_, ch)) = self.peek_one() {
if !is_keylike(ch) { if !is_keylike(ch) {
break break;
} }
self.one(); self.one();
} }
@ -441,8 +456,14 @@ impl<'a> Tokenizer<'a> {
/// Calculate the span of a single character. /// Calculate the span of a single character.
fn step_span(&mut self, start: usize) -> Span { fn step_span(&mut self, start: usize) -> Span {
let end = self.peek_one().map(|t| t.0).unwrap_or_else(|| self.input.len()); let end = self
Span { start: start, end: end } .peek_one()
.map(|t| t.0)
.unwrap_or_else(|| self.input.len());
Span {
start: start,
end: end,
}
} }
/// Peek one char without consuming it. /// Peek one char without consuming it.
@ -465,7 +486,7 @@ impl<'a> Iterator for CrlfFold<'a> {
let mut attempt = self.chars.clone(); let mut attempt = self.chars.clone();
if let Some((_, '\n')) = attempt.next() { if let Some((_, '\n')) = attempt.next() {
self.chars = attempt; self.chars = attempt;
return (i, '\n') return (i, '\n');
} }
} }
(i, c) (i, c)
@ -499,11 +520,11 @@ impl MaybeString {
} }
fn is_keylike(ch: char) -> bool { fn is_keylike(ch: char) -> bool {
('A' <= ch && ch <= 'Z') || ('A' <= ch && ch <= 'Z')
('a' <= ch && ch <= 'z') || || ('a' <= ch && ch <= 'z')
('0' <= ch && ch <= '9') || || ('0' <= ch && ch <= '9')
ch == '-' || || ch == '-'
ch == '_' || ch == '_'
} }
impl<'a> Token<'a> { impl<'a> Token<'a> {
@ -520,7 +541,13 @@ impl<'a> Token<'a> {
Token::LeftBrace => "a left brace", Token::LeftBrace => "a left brace",
Token::RightBracket => "a right bracket", Token::RightBracket => "a right bracket",
Token::LeftBracket => "a left bracket", Token::LeftBracket => "a left bracket",
Token::String { multiline, .. } => if multiline { "a multiline string" } else { "a string" }, Token::String { multiline, .. } => {
if multiline {
"a multiline string"
} else {
"a string"
}
}
Token::Colon => "a colon", Token::Colon => "a colon",
Token::Plus => "a plus", Token::Plus => "a plus",
} }
@ -529,8 +556,8 @@ impl<'a> Token<'a> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{Error, Token, Tokenizer};
use std::borrow::Cow; use std::borrow::Cow;
use super::{Tokenizer, Token, Error};
fn err(input: &str, err: Error) { fn err(input: &str, err: Error) {
let mut t = Tokenizer::new(input); let mut t = Tokenizer::new(input);
@ -544,11 +571,14 @@ mod tests {
fn t(input: &str, val: &str, multiline: bool) { fn t(input: &str, val: &str, multiline: bool) {
let mut t = Tokenizer::new(input); let mut t = Tokenizer::new(input);
let (_, token) = t.next().unwrap().unwrap(); let (_, token) = t.next().unwrap().unwrap();
assert_eq!(token, Token::String { assert_eq!(
src: input, token,
val: Cow::Borrowed(val), Token::String {
multiline: multiline, src: input,
}); val: Cow::Borrowed(val),
multiline: multiline,
}
);
assert!(t.next().unwrap().is_none()); assert!(t.next().unwrap().is_none());
} }
@ -567,11 +597,14 @@ mod tests {
fn t(input: &str, val: &str, multiline: bool) { fn t(input: &str, val: &str, multiline: bool) {
let mut t = Tokenizer::new(input); let mut t = Tokenizer::new(input);
let (_, token) = t.next().unwrap().unwrap(); let (_, token) = t.next().unwrap().unwrap();
assert_eq!(token, Token::String { assert_eq!(
src: input, token,
val: Cow::Borrowed(val), Token::String {
multiline: multiline, src: input,
}); val: Cow::Borrowed(val),
multiline: multiline,
}
);
assert!(t.next().unwrap().is_none()); assert!(t.next().unwrap().is_none());
} }
@ -585,7 +618,11 @@ mod tests {
t(r#""\U000A0000""#, "\u{A0000}", false); t(r#""\U000A0000""#, "\u{A0000}", false);
t(r#""\\t""#, "\\t", false); t(r#""\\t""#, "\\t", false);
t("\"\"\"\\\n\"\"\"", "", true); t("\"\"\"\\\n\"\"\"", "", true);
t("\"\"\"\\\n \t \t \\\r\n \t \n \t \r\n\"\"\"", "", true); t(
"\"\"\"\\\n \t \t \\\r\n \t \n \t \r\n\"\"\"",
"",
true,
);
t(r#""\r""#, "\r", false); t(r#""\r""#, "\r", false);
t(r#""\n""#, "\n", false); t(r#""\n""#, "\n", false);
t(r#""\b""#, "\u{8}", false); t(r#""\b""#, "\u{8}", false);
@ -636,39 +673,45 @@ mod tests {
assert_eq!(actual.len(), expected.len()); assert_eq!(actual.len(), expected.len());
} }
t(" a ", &[ t(
((0, 1), Token::Whitespace(" "), " "), " a ",
((1, 2), Token::Keylike("a"), "a"), &[
((2, 3), Token::Whitespace(" "), " "), ((0, 1), Token::Whitespace(" "), " "),
]); ((1, 2), Token::Keylike("a"), "a"),
((2, 3), Token::Whitespace(" "), " "),
],
);
t(" a\t [[]] \t [] {} , . =\n# foo \r\n#foo \n ", &[ t(
((0, 1), Token::Whitespace(" "), " "), " a\t [[]] \t [] {} , . =\n# foo \r\n#foo \n ",
((1, 2), Token::Keylike("a"), "a"), &[
((2, 4), Token::Whitespace("\t "), "\t "), ((0, 1), Token::Whitespace(" "), " "),
((4, 5), Token::LeftBracket, "["), ((1, 2), Token::Keylike("a"), "a"),
((5, 6), Token::LeftBracket, "["), ((2, 4), Token::Whitespace("\t "), "\t "),
((6, 7), Token::RightBracket, "]"), ((4, 5), Token::LeftBracket, "["),
((7, 8), Token::RightBracket, "]"), ((5, 6), Token::LeftBracket, "["),
((8, 11), Token::Whitespace(" \t "), " \t "), ((6, 7), Token::RightBracket, "]"),
((11, 12), Token::LeftBracket, "["), ((7, 8), Token::RightBracket, "]"),
((12, 13), Token::RightBracket, "]"), ((8, 11), Token::Whitespace(" \t "), " \t "),
((13, 14), Token::Whitespace(" "), " "), ((11, 12), Token::LeftBracket, "["),
((14, 15), Token::LeftBrace, "{"), ((12, 13), Token::RightBracket, "]"),
((15, 16), Token::RightBrace, "}"), ((13, 14), Token::Whitespace(" "), " "),
((16, 17), Token::Whitespace(" "), " "), ((14, 15), Token::LeftBrace, "{"),
((17, 18), Token::Comma, ","), ((15, 16), Token::RightBrace, "}"),
((18, 19), Token::Whitespace(" "), " "), ((16, 17), Token::Whitespace(" "), " "),
((19, 20), Token::Period, "."), ((17, 18), Token::Comma, ","),
((20, 21), Token::Whitespace(" "), " "), ((18, 19), Token::Whitespace(" "), " "),
((21, 22), Token::Equals, "="), ((19, 20), Token::Period, "."),
((22, 23), Token::Newline, "\n"), ((20, 21), Token::Whitespace(" "), " "),
((23, 29), Token::Comment("# foo "), "# foo "), ((21, 22), Token::Equals, "="),
((29, 31), Token::Newline, "\r\n"), ((22, 23), Token::Newline, "\n"),
((31, 36), Token::Comment("#foo "), "#foo "), ((23, 29), Token::Comment("# foo "), "# foo "),
((36, 37), Token::Newline, "\n"), ((29, 31), Token::Newline, "\r\n"),
((37, 38), Token::Whitespace(" "), " "), ((31, 36), Token::Comment("#foo "), "#foo "),
]); ((36, 37), Token::Newline, "\n"),
((37, 38), Token::Whitespace(" "), " "),
],
);
} }
#[test] #[test]

View file

@ -1,18 +1,18 @@
//! Definition of a TOML value //! Definition of a TOML value
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
use std::hash::Hash;
use std::fmt; use std::fmt;
use std::hash::Hash;
use std::ops; use std::ops;
use std::str::FromStr; use std::str::FromStr;
use std::vec; use std::vec;
use serde::ser;
use serde::de; use serde::de;
use serde::de::IntoDeserializer; use serde::de::IntoDeserializer;
use serde::ser;
pub use datetime::{Datetime, DatetimeParseError};
use datetime::{self, DatetimeFromString}; use datetime::{self, DatetimeFromString};
pub use datetime::{Datetime, DatetimeParseError};
/// Representation of a TOML value. /// Representation of a TOML value.
#[derive(PartialEq, Clone, Debug)] #[derive(PartialEq, Clone, Debug)]
@ -46,7 +46,8 @@ impl Value {
/// This conversion can fail if `T`'s implementation of `Serialize` decides to /// This conversion can fail if `T`'s implementation of `Serialize` decides to
/// fail, or if `T` contains a map with non-string keys. /// fail, or if `T` contains a map with non-string keys.
pub fn try_from<T>(value: T) -> Result<Value, ::ser::Error> pub fn try_from<T>(value: T) -> Result<Value, ::ser::Error>
where T: ser::Serialize, where
T: ser::Serialize,
{ {
value.serialize(Serializer) value.serialize(Serializer)
} }
@ -61,7 +62,8 @@ impl Value {
/// missing from the TOML map or some number is too big to fit in the expected /// missing from the TOML map or some number is too big to fit in the expected
/// primitive type. /// primitive type.
pub fn try_into<'de, T>(self) -> Result<T, ::de::Error> pub fn try_into<'de, T>(self) -> Result<T, ::de::Error>
where T: de::Deserialize<'de>, where
T: de::Deserialize<'de>,
{ {
de::Deserialize::deserialize(self) de::Deserialize::deserialize(self)
} }
@ -92,7 +94,10 @@ impl Value {
/// Extracts the integer value if it is an integer. /// Extracts the integer value if it is an integer.
pub fn as_integer(&self) -> Option<i64> { pub fn as_integer(&self) -> Option<i64> {
match *self { Value::Integer(i) => Some(i), _ => None } match *self {
Value::Integer(i) => Some(i),
_ => None,
}
} }
/// Tests whether this value is an integer. /// Tests whether this value is an integer.
@ -102,7 +107,10 @@ impl Value {
/// Extracts the float value if it is a float. /// Extracts the float value if it is a float.
pub fn as_float(&self) -> Option<f64> { pub fn as_float(&self) -> Option<f64> {
match *self { Value::Float(f) => Some(f), _ => None } match *self {
Value::Float(f) => Some(f),
_ => None,
}
} }
/// Tests whether this value is a float. /// Tests whether this value is a float.
@ -112,7 +120,10 @@ impl Value {
/// Extracts the boolean value if it is a boolean. /// Extracts the boolean value if it is a boolean.
pub fn as_bool(&self) -> Option<bool> { pub fn as_bool(&self) -> Option<bool> {
match *self { Value::Boolean(b) => Some(b), _ => None } match *self {
Value::Boolean(b) => Some(b),
_ => None,
}
} }
/// Tests whether this value is a boolean. /// Tests whether this value is a boolean.
@ -122,7 +133,10 @@ impl Value {
/// Extracts the string of this value if it is a string. /// Extracts the string of this value if it is a string.
pub fn as_str(&self) -> Option<&str> { pub fn as_str(&self) -> Option<&str> {
match *self { Value::String(ref s) => Some(&**s), _ => None } match *self {
Value::String(ref s) => Some(&**s),
_ => None,
}
} }
/// Tests if this value is a string. /// Tests if this value is a string.
@ -139,7 +153,10 @@ impl Value {
/// 1979-05-27T07:32:00Z /// 1979-05-27T07:32:00Z
/// ``` /// ```
pub fn as_datetime(&self) -> Option<&Datetime> { pub fn as_datetime(&self) -> Option<&Datetime> {
match *self { Value::Datetime(ref s) => Some(s), _ => None } match *self {
Value::Datetime(ref s) => Some(s),
_ => None,
}
} }
/// Tests whether this value is a datetime. /// Tests whether this value is a datetime.
@ -149,12 +166,18 @@ impl Value {
/// Extracts the array value if it is an array. /// Extracts the array value if it is an array.
pub fn as_array(&self) -> Option<&Vec<Value>> { pub fn as_array(&self) -> Option<&Vec<Value>> {
match *self { Value::Array(ref s) => Some(s), _ => None } match *self {
Value::Array(ref s) => Some(s),
_ => None,
}
} }
/// Extracts the array value if it is an array. /// Extracts the array value if it is an array.
pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> { pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
match *self { Value::Array(ref mut s) => Some(s), _ => None } match *self {
Value::Array(ref mut s) => Some(s),
_ => None,
}
} }
/// Tests whether this value is an array. /// Tests whether this value is an array.
@ -164,12 +187,18 @@ impl Value {
/// Extracts the table value if it is a table. /// Extracts the table value if it is a table.
pub fn as_table(&self) -> Option<&Table> { pub fn as_table(&self) -> Option<&Table> {
match *self { Value::Table(ref s) => Some(s), _ => None } match *self {
Value::Table(ref s) => Some(s),
_ => None,
}
} }
/// Extracts the table value if it is a table. /// Extracts the table value if it is a table.
pub fn as_table_mut(&mut self) -> Option<&mut Table> { pub fn as_table_mut(&mut self) -> Option<&mut Table> {
match *self { Value::Table(ref mut s) => Some(s), _ => None } match *self {
Value::Table(ref mut s) => Some(s),
_ => None,
}
} }
/// Tests whether this value is a table. /// Tests whether this value is a table.
@ -180,13 +209,13 @@ impl Value {
/// Tests whether this and another value have the same type. /// Tests whether this and another value have the same type.
pub fn same_type(&self, other: &Value) -> bool { pub fn same_type(&self, other: &Value) -> bool {
match (self, other) { match (self, other) {
(&Value::String(..), &Value::String(..)) | (&Value::String(..), &Value::String(..))
(&Value::Integer(..), &Value::Integer(..)) | | (&Value::Integer(..), &Value::Integer(..))
(&Value::Float(..), &Value::Float(..)) | | (&Value::Float(..), &Value::Float(..))
(&Value::Boolean(..), &Value::Boolean(..)) | | (&Value::Boolean(..), &Value::Boolean(..))
(&Value::Datetime(..), &Value::Datetime(..)) | | (&Value::Datetime(..), &Value::Datetime(..))
(&Value::Array(..), &Value::Array(..)) | | (&Value::Array(..), &Value::Array(..))
(&Value::Table(..), &Value::Table(..)) => true, | (&Value::Table(..), &Value::Table(..)) => true,
_ => false, _ => false,
} }
@ -206,7 +235,10 @@ impl Value {
} }
} }
impl<I> ops::Index<I> for Value where I: Index { impl<I> ops::Index<I> for Value
where
I: Index,
{
type Output = Value; type Output = Value;
fn index(&self, index: I) -> &Value { fn index(&self, index: I) -> &Value {
@ -214,7 +246,10 @@ impl<I> ops::Index<I> for Value where I: Index {
} }
} }
impl<I> ops::IndexMut<I> for Value where I: Index { impl<I> ops::IndexMut<I> for Value
where
I: Index,
{
fn index_mut(&mut self, index: I) -> &mut Value { fn index_mut(&mut self, index: I) -> &mut Value {
self.get_mut(index).expect("index not found") self.get_mut(index).expect("index not found")
} }
@ -235,9 +270,7 @@ impl<V: Into<Value>> From<Vec<V>> for Value {
impl<S: Into<String>, V: Into<Value>> From<BTreeMap<S, V>> for Value { impl<S: Into<String>, V: Into<Value>> From<BTreeMap<S, V>> for Value {
fn from(val: BTreeMap<S, V>) -> Value { fn from(val: BTreeMap<S, V>) -> Value {
let table = val.into_iter() let table = val.into_iter().map(|(s, v)| (s.into(), v.into())).collect();
.map(|(s, v)| (s.into(), v.into()))
.collect();
Value::Table(table) Value::Table(table)
} }
@ -245,9 +278,7 @@ impl<S: Into<String>, V: Into<Value>> From<BTreeMap<S, V>> for Value {
impl<S: Into<String> + Hash + Eq, V: Into<Value>> From<HashMap<S, V>> for Value { impl<S: Into<String> + Hash + Eq, V: Into<Value>> From<HashMap<S, V>> for Value {
fn from(val: HashMap<S, V>) -> Value { fn from(val: HashMap<S, V>) -> Value {
let table = val.into_iter() let table = val.into_iter().map(|(s, v)| (s.into(), v.into())).collect();
.map(|(s, v)| (s.into(), v.into()))
.collect();
Value::Table(table) Value::Table(table)
} }
@ -261,7 +292,7 @@ macro_rules! impl_into_value {
Value::$variant(val.into()) Value::$variant(val.into())
} }
} }
} };
} }
impl_into_value!(String: String); impl_into_value!(String: String);
@ -340,7 +371,10 @@ impl Index for String {
} }
} }
impl<'s, T: ?Sized> Index for &'s T where T: Index { impl<'s, T: ?Sized> Index for &'s T
where
T: Index,
{
fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> {
(**self).index(val) (**self).index(val)
} }
@ -352,7 +386,9 @@ impl<'s, T: ?Sized> Index for &'s T where T: Index {
impl fmt::Display for Value { impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
::ser::to_string(self).expect("Unable to represent value as string").fmt(f) ::ser::to_string(self)
.expect("Unable to represent value as string")
.fmt(f)
} }
} }
@ -365,7 +401,8 @@ impl FromStr for Value {
impl ser::Serialize for Value { impl ser::Serialize for Value {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: ser::Serializer where
S: ser::Serializer,
{ {
use serde::ser::SerializeMap; use serde::ser::SerializeMap;
@ -381,13 +418,20 @@ impl ser::Serialize for Value {
// Be sure to visit non-tables first (and also non // Be sure to visit non-tables first (and also non
// array-of-tables) as all keys must be emitted first. // array-of-tables) as all keys must be emitted first.
for (k, v) in t { for (k, v) in t {
if !v.is_table() && !v.is_array() || if !v.is_table() && !v.is_array()
(v.as_array().map(|a| !a.iter().any(|v| v.is_table())).unwrap_or(false)) { || (v
.as_array()
.map(|a| !a.iter().any(|v| v.is_table()))
.unwrap_or(false))
{
map.serialize_entry(k, v)?; map.serialize_entry(k, v)?;
} }
} }
for (k, v) in t { for (k, v) in t {
if v.as_array().map(|a| a.iter().any(|v| v.is_table())).unwrap_or(false) { if v.as_array()
.map(|a| a.iter().any(|v| v.is_table()))
.unwrap_or(false)
{
map.serialize_entry(k, v)?; map.serialize_entry(k, v)?;
} }
} }
@ -404,7 +448,8 @@ impl ser::Serialize for Value {
impl<'de> de::Deserialize<'de> for Value { impl<'de> de::Deserialize<'de> for Value {
fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> fn deserialize<D>(deserializer: D) -> Result<Value, D::Error>
where D: de::Deserializer<'de>, where
D: de::Deserializer<'de>,
{ {
struct ValueVisitor; struct ValueVisitor;
@ -452,13 +497,15 @@ impl<'de> de::Deserialize<'de> for Value {
} }
fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error> fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error>
where D: de::Deserializer<'de>, where
D: de::Deserializer<'de>,
{ {
de::Deserialize::deserialize(deserializer) de::Deserialize::deserialize(deserializer)
} }
fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error> fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error>
where V: de::SeqAccess<'de>, where
V: de::SeqAccess<'de>,
{ {
let mut vec = Vec::new(); let mut vec = Vec::new();
while let Some(elem) = visitor.next_element()? { while let Some(elem) = visitor.next_element()? {
@ -468,16 +515,15 @@ impl<'de> de::Deserialize<'de> for Value {
} }
fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error>
where V: de::MapAccess<'de>, where
V: de::MapAccess<'de>,
{ {
let mut key = String::new(); let mut key = String::new();
let datetime = visitor.next_key_seed(DatetimeOrTable { let datetime = visitor.next_key_seed(DatetimeOrTable { key: &mut key })?;
key: &mut key,
})?;
match datetime { match datetime {
Some(true) => { Some(true) => {
let date: DatetimeFromString = visitor.next_value()?; let date: DatetimeFromString = visitor.next_value()?;
return Ok(Value::Datetime(date.value)) return Ok(Value::Datetime(date.value));
} }
None => return Ok(Value::Table(BTreeMap::new())), None => return Ok(Value::Table(BTreeMap::new())),
Some(false) => {} Some(false) => {}
@ -487,7 +533,7 @@ impl<'de> de::Deserialize<'de> for Value {
while let Some(key) = visitor.next_key()? { while let Some(key) = visitor.next_key()? {
if map.contains_key(&key) { if map.contains_key(&key) {
let msg = format!("duplicate key: `{}`", key); let msg = format!("duplicate key: `{}`", key);
return Err(de::Error::custom(msg)) return Err(de::Error::custom(msg));
} }
map.insert(key, visitor.next_value()?); map.insert(key, visitor.next_value()?);
} }
@ -503,7 +549,8 @@ impl<'de> de::Deserializer<'de> for Value {
type Error = ::de::Error; type Error = ::de::Error;
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, ::de::Error> fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, ::de::Error>
where V: de::Visitor<'de>, where
V: de::Visitor<'de>,
{ {
match self { match self {
Value::Boolean(v) => visitor.visit_bool(v), Value::Boolean(v) => visitor.visit_bool(v),
@ -548,14 +595,18 @@ impl<'de> de::Deserializer<'de> for Value {
{ {
match self { match self {
Value::String(variant) => visitor.visit_enum(variant.into_deserializer()), Value::String(variant) => visitor.visit_enum(variant.into_deserializer()),
_ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"string only")), _ => Err(de::Error::invalid_type(
de::Unexpected::UnitVariant,
&"string only",
)),
} }
} }
// `None` is interpreted as a missing field so be sure to implement `Some` // `None` is interpreted as a missing field so be sure to implement `Some`
// as a present field. // as a present field.
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, ::de::Error> fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, ::de::Error>
where V: de::Visitor<'de>, where
V: de::Visitor<'de>,
{ {
visitor.visit_some(self) visitor.visit_some(self)
} }
@ -563,9 +614,10 @@ impl<'de> de::Deserializer<'de> for Value {
fn deserialize_newtype_struct<V>( fn deserialize_newtype_struct<V>(
self, self,
_name: &'static str, _name: &'static str,
visitor: V visitor: V,
) -> Result<V::Value, ::de::Error> ) -> Result<V::Value, ::de::Error>
where V: de::Visitor<'de> where
V: de::Visitor<'de>,
{ {
visitor.visit_newtype_struct(self) visitor.visit_newtype_struct(self)
} }
@ -592,9 +644,9 @@ impl SeqDeserializer {
impl<'de> de::SeqAccess<'de> for SeqDeserializer { impl<'de> de::SeqAccess<'de> for SeqDeserializer {
type Error = ::de::Error; type Error = ::de::Error;
fn next_element_seed<T>(&mut self, seed: T) fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, ::de::Error>
-> Result<Option<T::Value>, ::de::Error> where
where T: de::DeserializeSeed<'de>, T: de::DeserializeSeed<'de>,
{ {
match self.iter.next() { match self.iter.next() {
Some(value) => seed.deserialize(value).map(Some), Some(value) => seed.deserialize(value).map(Some),
@ -628,7 +680,8 @@ impl<'de> de::MapAccess<'de> for MapDeserializer {
type Error = ::de::Error; type Error = ::de::Error;
fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, ::de::Error> fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, ::de::Error>
where T: de::DeserializeSeed<'de>, where
T: de::DeserializeSeed<'de>,
{ {
match self.iter.next() { match self.iter.next() {
Some((key, value)) => { Some((key, value)) => {
@ -640,7 +693,8 @@ impl<'de> de::MapAccess<'de> for MapDeserializer {
} }
fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, ::de::Error> fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, ::de::Error>
where T: de::DeserializeSeed<'de>, where
T: de::DeserializeSeed<'de>,
{ {
let (key, res) = match self.value.take() { let (key, res) = match self.value.take() {
Some((key, value)) => (key, seed.deserialize(value)), Some((key, value)) => (key, seed.deserialize(value)),
@ -749,35 +803,39 @@ impl ser::Serializer for Serializer {
Err(::ser::Error::UnsupportedType) Err(::ser::Error::UnsupportedType)
} }
fn serialize_unit_struct(self, _name: &'static str) fn serialize_unit_struct(self, _name: &'static str) -> Result<Value, ::ser::Error> {
-> Result<Value, ::ser::Error> {
Err(::ser::Error::UnsupportedType) Err(::ser::Error::UnsupportedType)
} }
fn serialize_unit_variant(self, fn serialize_unit_variant(
_name: &'static str, self,
_variant_index: u32, _name: &'static str,
_variant: &'static str) _variant_index: u32,
-> Result<Value, ::ser::Error> { _variant: &'static str,
) -> Result<Value, ::ser::Error> {
self.serialize_str(_variant) self.serialize_str(_variant)
} }
fn serialize_newtype_struct<T: ?Sized>(self, fn serialize_newtype_struct<T: ?Sized>(
_name: &'static str, self,
value: &T) _name: &'static str,
-> Result<Value, ::ser::Error> value: &T,
where T: ser::Serialize, ) -> Result<Value, ::ser::Error>
where
T: ser::Serialize,
{ {
value.serialize(self) value.serialize(self)
} }
fn serialize_newtype_variant<T: ?Sized>(self, fn serialize_newtype_variant<T: ?Sized>(
_name: &'static str, self,
_variant_index: u32, _name: &'static str,
_variant: &'static str, _variant_index: u32,
_value: &T) _variant: &'static str,
-> Result<Value, ::ser::Error> _value: &T,
where T: ser::Serialize, ) -> Result<Value, ::ser::Error>
where
T: ser::Serialize,
{ {
Err(::ser::Error::UnsupportedType) Err(::ser::Error::UnsupportedType)
} }
@ -787,16 +845,15 @@ impl ser::Serializer for Serializer {
} }
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, ::ser::Error> fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, ::ser::Error>
where T: ser::Serialize, where
T: ser::Serialize,
{ {
value.serialize(self) value.serialize(self)
} }
fn serialize_seq(self, len: Option<usize>) fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, ::ser::Error> {
-> Result<Self::SerializeSeq, ::ser::Error>
{
Ok(SerializeVec { Ok(SerializeVec {
vec: Vec::with_capacity(len.unwrap_or(0)) vec: Vec::with_capacity(len.unwrap_or(0)),
}) })
} }
@ -804,42 +861,46 @@ impl ser::Serializer for Serializer {
self.serialize_seq(Some(len)) self.serialize_seq(Some(len))
} }
fn serialize_tuple_struct(self, _name: &'static str, len: usize) fn serialize_tuple_struct(
-> Result<Self::SerializeTupleStruct, ::ser::Error> { self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, ::ser::Error> {
self.serialize_seq(Some(len)) self.serialize_seq(Some(len))
} }
fn serialize_tuple_variant(self, fn serialize_tuple_variant(
_name: &'static str, self,
_variant_index: u32, _name: &'static str,
_variant: &'static str, _variant_index: u32,
len: usize) _variant: &'static str,
-> Result<Self::SerializeTupleVariant, ::ser::Error> len: usize,
{ ) -> Result<Self::SerializeTupleVariant, ::ser::Error> {
self.serialize_seq(Some(len)) self.serialize_seq(Some(len))
} }
fn serialize_map(self, _len: Option<usize>) fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, ::ser::Error> {
-> Result<Self::SerializeMap, ::ser::Error>
{
Ok(SerializeMap { Ok(SerializeMap {
map: BTreeMap::new(), map: BTreeMap::new(),
next_key: None, next_key: None,
}) })
} }
fn serialize_struct(self, _name: &'static str, len: usize) fn serialize_struct(
-> Result<Self::SerializeStruct, ::ser::Error> { self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeStruct, ::ser::Error> {
self.serialize_map(Some(len)) self.serialize_map(Some(len))
} }
fn serialize_struct_variant(self, fn serialize_struct_variant(
_name: &'static str, self,
_variant_index: u32, _name: &'static str,
_variant: &'static str, _variant_index: u32,
_len: usize) _variant: &'static str,
-> Result<Self::SerializeStructVariant, ::ser::Error> _len: usize,
{ ) -> Result<Self::SerializeStructVariant, ::ser::Error> {
Err(::ser::Error::UnsupportedType) Err(::ser::Error::UnsupportedType)
} }
} }
@ -858,7 +919,8 @@ impl ser::SerializeSeq for SerializeVec {
type Error = ::ser::Error; type Error = ::ser::Error;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error> fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error>
where T: ser::Serialize where
T: ser::Serialize,
{ {
self.vec.push(Value::try_from(value)?); self.vec.push(Value::try_from(value)?);
Ok(()) Ok(())
@ -874,7 +936,8 @@ impl ser::SerializeTuple for SerializeVec {
type Error = ::ser::Error; type Error = ::ser::Error;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error> fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error>
where T: ser::Serialize where
T: ser::Serialize,
{ {
ser::SerializeSeq::serialize_element(self, value) ser::SerializeSeq::serialize_element(self, value)
} }
@ -889,7 +952,8 @@ impl ser::SerializeTupleStruct for SerializeVec {
type Error = ::ser::Error; type Error = ::ser::Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error> fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error>
where T: ser::Serialize where
T: ser::Serialize,
{ {
ser::SerializeSeq::serialize_element(self, value) ser::SerializeSeq::serialize_element(self, value)
} }
@ -904,7 +968,8 @@ impl ser::SerializeTupleVariant for SerializeVec {
type Error = ::ser::Error; type Error = ::ser::Error;
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error> fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error>
where T: ser::Serialize where
T: ser::Serialize,
{ {
ser::SerializeSeq::serialize_element(self, value) ser::SerializeSeq::serialize_element(self, value)
} }
@ -919,7 +984,8 @@ impl ser::SerializeMap for SerializeMap {
type Error = ::ser::Error; type Error = ::ser::Error;
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), ::ser::Error> fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), ::ser::Error>
where T: ser::Serialize where
T: ser::Serialize,
{ {
match Value::try_from(key)? { match Value::try_from(key)? {
Value::String(s) => self.next_key = Some(s), Value::String(s) => self.next_key = Some(s),
@ -929,12 +995,15 @@ impl ser::SerializeMap for SerializeMap {
} }
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error> fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error>
where T: ser::Serialize where
T: ser::Serialize,
{ {
let key = self.next_key.take(); let key = self.next_key.take();
let key = key.expect("serialize_value called before serialize_key"); let key = key.expect("serialize_value called before serialize_key");
match Value::try_from(value) { match Value::try_from(value) {
Ok(value) => { self.map.insert(key, value); } Ok(value) => {
self.map.insert(key, value);
}
Err(::ser::Error::UnsupportedNone) => {} Err(::ser::Error::UnsupportedNone) => {}
Err(e) => return Err(e), Err(e) => return Err(e),
} }
@ -950,8 +1019,13 @@ impl ser::SerializeStruct for SerializeMap {
type Ok = Value; type Ok = Value;
type Error = ::ser::Error; type Error = ::ser::Error;
fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), ::ser::Error> fn serialize_field<T: ?Sized>(
where T: ser::Serialize &mut self,
key: &'static str,
value: &T,
) -> Result<(), ::ser::Error>
where
T: ser::Serialize,
{ {
ser::SerializeMap::serialize_key(self, key)?; ser::SerializeMap::serialize_key(self, key)?;
ser::SerializeMap::serialize_value(self, value) ser::SerializeMap::serialize_value(self, value)
@ -970,7 +1044,8 @@ impl<'a, 'de> de::DeserializeSeed<'de> for DatetimeOrTable<'a> {
type Value = bool; type Value = bool;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where D: de::Deserializer<'de> where
D: de::Deserializer<'de>,
{ {
deserializer.deserialize_any(self) deserializer.deserialize_any(self)
} }
@ -984,7 +1059,8 @@ impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> {
} }
fn visit_str<E>(self, s: &str) -> Result<bool, E> fn visit_str<E>(self, s: &str) -> Result<bool, E>
where E: de::Error, where
E: de::Error,
{ {
if s == datetime::FIELD { if s == datetime::FIELD {
Ok(true) Ok(true)
@ -995,7 +1071,8 @@ impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> {
} }
fn visit_string<E>(self, s: String) -> Result<bool, E> fn visit_string<E>(self, s: String) -> Result<bool, E>
where E: de::Error, where
E: de::Error,
{ {
if s == datetime::FIELD { if s == datetime::FIELD {
Ok(true) Ok(true)