From c1a369f44762045e65989caa9491e153d1f358e6 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 17 Dec 2018 17:45:35 -0800 Subject: Run `cargo fmt` --- src/datetime.rs | 56 +++--- src/de.rs | 567 +++++++++++++++++++++++++++++++++----------------------- src/macros.rs | 7 +- src/ser.rs | 560 +++++++++++++++++++++++++++++++------------------------ src/spanned.rs | 20 +- src/tokens.rs | 359 +++++++++++++++++++---------------- src/value.rs | 301 +++++++++++++++++++----------- 7 files changed, 1088 insertions(+), 782 deletions(-) (limited to 'src') diff --git a/src/datetime.rs b/src/datetime.rs index 3678f58..363160b 100644 --- a/src/datetime.rs +++ b/src/datetime.rs @@ -1,6 +1,6 @@ +use std::error; use std::fmt; use std::str::{self, FromStr}; -use std::error; use serde::{de, ser}; @@ -109,9 +109,7 @@ impl fmt::Display for Offset { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Offset::Z => write!(f, "Z"), - Offset::Custom { hours, minutes } => { - write!(f, "{:+03}:{:02}", hours, minutes) - } + Offset::Custom { hours, minutes } => write!(f, "{:+03}:{:02}", hours, minutes), } } } @@ -127,7 +125,7 @@ impl FromStr for Datetime { // 0000-00-00 // 00:00:00.00 if date.len() < 3 { - return Err(DatetimeParseError { _private: () }) + return Err(DatetimeParseError { _private: () }); } let mut offset_allowed = true; let mut chars = date.chars(); @@ -165,19 +163,19 @@ impl FromStr for Datetime { }; if date.month < 1 || date.month > 12 { - return Err(DatetimeParseError { _private: () }) + return Err(DatetimeParseError { _private: () }); } if date.day < 1 || date.day > 31 { - return Err(DatetimeParseError { _private: () }) + return Err(DatetimeParseError { _private: () }); } Some(date) }; // Next parse the "partial-time" if available - let partial_time = if full_date.is_some() && - (chars.clone().next() == Some('T') - || chars.clone().next() == Some(' ')) { + let partial_time = if full_date.is_some() + && (chars.clone().next() == Some('T') || chars.clone().next() == Some(' ')) + { chars.next(); true } else { @@ -208,7 +206,7 @@ impl FromStr for Datetime { let mut end = whole.len(); for (i, byte) in whole.bytes().enumerate() { match byte { - b'0' ... b'9' => { + b'0'...b'9' => { if i < 9 { let p = 10_u32.pow(8 - i as u32); nanosecond += p * (byte - b'0') as u32; @@ -221,7 +219,7 @@ impl FromStr for Datetime { } } if end == 0 { - return Err(DatetimeParseError { _private: () }) + return Err(DatetimeParseError { _private: () }); } chars = whole[end..].chars(); } @@ -234,16 +232,16 @@ impl FromStr for Datetime { }; if time.hour > 24 { - return Err(DatetimeParseError { _private: () }) + return Err(DatetimeParseError { _private: () }); } if time.minute > 59 { - return Err(DatetimeParseError { _private: () }) + return Err(DatetimeParseError { _private: () }); } if time.second > 59 { - return Err(DatetimeParseError { _private: () }) + return Err(DatetimeParseError { _private: () }); } if time.nanosecond > 999_999_999 { - return Err(DatetimeParseError { _private: () }) + return Err(DatetimeParseError { _private: () }); } Some(time) @@ -288,7 +286,7 @@ impl FromStr for Datetime { // Return an error if we didn't hit eof, otherwise return our parsed // date if chars.next().is_some() { - return Err(DatetimeParseError { _private: () }) + return Err(DatetimeParseError { _private: () }); } Ok(Datetime { @@ -308,7 +306,8 @@ fn digit(chars: &mut str::Chars) -> Result { impl ser::Serialize for Datetime { fn serialize(&self, serializer: S) -> Result - where S: ser::Serializer + where + S: ser::Serializer, { use serde::ser::SerializeStruct; @@ -320,7 +319,8 @@ impl ser::Serialize for Datetime { impl<'de> de::Deserialize<'de> for Datetime { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct DatetimeVisitor; @@ -332,15 +332,15 @@ impl<'de> de::Deserialize<'de> for Datetime { } fn visit_map(self, mut visitor: V) -> Result - where V: de::MapAccess<'de> + where + V: de::MapAccess<'de>, { let value = visitor.next_key::()?; 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()?; Ok(v.value) - } } @@ -353,7 +353,8 @@ struct DatetimeKey; impl<'de> de::Deserialize<'de> for DatetimeKey { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct FieldVisitor; @@ -365,7 +366,8 @@ impl<'de> de::Deserialize<'de> for DatetimeKey { } fn visit_str(self, s: &str) -> Result<(), E> - where E: de::Error + where + E: de::Error, { if s == FIELD { Ok(()) @@ -386,7 +388,8 @@ pub struct DatetimeFromString { impl<'de> de::Deserialize<'de> for DatetimeFromString { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; @@ -398,7 +401,8 @@ impl<'de> de::Deserialize<'de> for DatetimeFromString { } fn visit_str(self, s: &str) -> Result - where E: de::Error, + where + E: de::Error, { match s.parse() { Ok(date) => Ok(DatetimeFromString { value: date }), diff --git a/src/de.rs b/src/de.rs index 9334cd3..5f04027 100644 --- a/src/de.rs +++ b/src/de.rs @@ -12,19 +12,20 @@ use std::str; use std::vec; use serde::de; -use serde::de::IntoDeserializer; use serde::de::value::BorrowedStrDeserializer; +use serde::de::IntoDeserializer; -use tokens::{Tokenizer, Token, Error as TokenError, Span}; use datetime; use spanned; +use tokens::{Error as TokenError, Span, Token, Tokenizer}; /// Deserializes a byte slice into a type. /// /// This function will attempt to interpret `bytes` as UTF-8 data and then /// deserialize `T` from the TOML document provided. pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result - where T: de::Deserialize<'de>, +where + T: de::Deserialize<'de>, { match str::from_utf8(bytes) { Ok(s) => from_str(s), @@ -68,7 +69,8 @@ pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result /// } /// ``` pub fn from_str<'de, T>(s: &'de str) -> Result - where T: de::Deserialize<'de>, +where + T: de::Deserialize<'de>, { let mut d = Deserializer::new(s); let ret = T::deserialize(&mut d)?; @@ -203,9 +205,9 @@ impl<'de, 'b> de::Deserializer<'de> for &'b mut Deserializer<'de> { type Error = Error; fn deserialize_any(self, visitor: V) -> Result - where V: de::Visitor<'de>, + where + V: de::Visitor<'de>, { - let mut tables = self.tables()?; visitor.visit_map(MapVisitor { @@ -226,9 +228,10 @@ impl<'de, 'b> de::Deserializer<'de> for &'b mut Deserializer<'de> { self, _name: &'static str, _variants: &'static [&'static str], - visitor: V + visitor: V, ) -> Result - where V: de::Visitor<'de> + where + V: de::Visitor<'de>, { let (value, name) = self.string_or_table()?; match value.e { @@ -292,10 +295,11 @@ impl<'de, 'b> de::MapAccess<'de> for MapVisitor<'de, 'b> { type Error = Error; fn next_key_seed(&mut self, seed: K) -> Result, Error> - where K: de::DeserializeSeed<'de>, + where + K: de::DeserializeSeed<'de>, { if self.cur_parent == self.max || self.cur == self.max { - return Ok(None) + return Ok(None); } loop { @@ -303,20 +307,24 @@ impl<'de, 'b> de::MapAccess<'de> for MapVisitor<'de, 'b> { if let Some((key, value)) = self.values.next() { let ret = seed.deserialize(StrDeserializer::new(key.clone()))?; self.next_value = Some((key, value)); - return Ok(Some(ret)) + return Ok(Some(ret)); } let next_table = { let prefix = &self.tables[self.cur_parent].header[..self.depth]; - self.tables[self.cur..self.max].iter().enumerate().find(|&(_, t)| { - if t.values.is_none() { - return false - } - match t.header.get(..self.depth) { - Some(header) => header == prefix, - None => false, - } - }).map(|(i, _)| i + self.cur) + self.tables[self.cur..self.max] + .iter() + .enumerate() + .find(|&(_, t)| { + if t.values.is_none() { + return false; + } + match t.header.get(..self.depth) { + Some(header) => header == prefix, + None => false, + } + }) + .map(|(i, _)| i + self.cur) }; let pos = match next_table { @@ -327,11 +335,12 @@ impl<'de, 'b> de::MapAccess<'de> for MapVisitor<'de, 'b> { // Test to see if we're duplicating our parent's table, and if so // then this is an error in the toml format - if self.cur_parent != pos && - self.tables[self.cur_parent].header == self.tables[pos].header { + if self.cur_parent != pos + && self.tables[self.cur_parent].header == self.tables[pos].header + { let at = self.tables[pos].at; let name = self.tables[pos].header.join("."); - return Err(self.de.error(at, ErrorKind::DuplicateTable(name))) + return Err(self.de.error(at, ErrorKind::DuplicateTable(name))); } let table = &mut self.tables[pos]; @@ -342,42 +351,47 @@ impl<'de, 'b> de::MapAccess<'de> for MapVisitor<'de, 'b> { if self.depth != table.header.len() { let key = &table.header[self.depth]; let key = seed.deserialize(StrDeserializer::new(key.clone()))?; - return Ok(Some(key)) + return Ok(Some(key)); } // Rule out cases like: // // [[foo.bar]] // [[foo]] - if table.array { + if table.array { let kind = ErrorKind::RedefineAsArray; - return Err(self.de.error(table.at, kind)) + return Err(self.de.error(table.at, kind)); } - self.values = table.values.take().expect("Unable to read table values").into_iter(); + self.values = table + .values + .take() + .expect("Unable to read table values") + .into_iter(); } } fn next_value_seed(&mut self, seed: V) -> Result - where V: de::DeserializeSeed<'de>, + where + V: de::DeserializeSeed<'de>, { if let Some((k, v)) = self.next_value.take() { match seed.deserialize(ValueDeserializer::new(v)) { Ok(v) => return Ok(v), Err(mut e) => { e.add_key_context(&k); - return Err(e) + return Err(e); } } } - let array = self.tables[self.cur].array && - self.depth == self.tables[self.cur].header.len() - 1; + let array = + self.tables[self.cur].array && self.depth == self.tables[self.cur].header.len() - 1; self.cur += 1; let res = seed.deserialize(MapVisitor { values: Vec::new().into_iter(), next_value: None, - depth: self.depth + if array {0} else {1}, + depth: self.depth + if array { 0 } else { 1 }, cur_parent: self.cur - 1, cur: 0, max: self.max, @@ -396,26 +410,30 @@ impl<'de, 'b> de::SeqAccess<'de> for MapVisitor<'de, 'b> { type Error = Error; fn next_element_seed(&mut self, seed: K) -> Result, Error> - where K: de::DeserializeSeed<'de>, + where + K: de::DeserializeSeed<'de>, { assert!(self.next_value.is_none()); assert!(self.values.next().is_none()); if self.cur_parent == self.max { - return Ok(None) + return Ok(None); } let next = self.tables[..self.max] .iter() .enumerate() .skip(self.cur_parent + 1) - .find(|&(_, table)| { - table.array && table.header == self.tables[self.cur_parent].header - }).map(|p| p.0) + .find(|&(_, table)| table.array && table.header == self.tables[self.cur_parent].header) + .map(|p| p.0) .unwrap_or(self.max); let ret = seed.deserialize(MapVisitor { - values: self.tables[self.cur_parent].values.take().expect("Unable to read table values").into_iter(), + values: self.tables[self.cur_parent] + .values + .take() + .expect("Unable to read table values") + .into_iter(), next_value: None, depth: self.depth + 1, cur_parent: self.cur_parent, @@ -434,9 +452,10 @@ impl<'de, 'b> de::Deserializer<'de> for MapVisitor<'de, 'b> { type Error = Error; fn deserialize_any(self, visitor: V) -> Result - where V: de::Visitor<'de>, + where + V: de::Visitor<'de>, { - if self.array { + if self.array { visitor.visit_seq(self) } else { visitor.visit_map(self) @@ -446,7 +465,8 @@ impl<'de, 'b> de::Deserializer<'de> for MapVisitor<'de, 'b> { // `None` is interpreted as a missing field so be sure to implement `Some` // as a present field. fn deserialize_option(self, visitor: V) -> Result - where V: de::Visitor<'de>, + where + V: de::Visitor<'de>, { visitor.visit_some(self) } @@ -454,9 +474,10 @@ impl<'de, 'b> de::Deserializer<'de> for MapVisitor<'de, 'b> { fn deserialize_newtype_struct( self, _name: &'static str, - visitor: V + visitor: V, ) -> Result - where V: de::Visitor<'de> + where + V: de::Visitor<'de>, { visitor.visit_newtype_struct(self) } @@ -474,9 +495,7 @@ struct StrDeserializer<'a> { impl<'a> StrDeserializer<'a> { fn new(key: Cow<'a, str>) -> StrDeserializer<'a> { - StrDeserializer { - key: key, - } + StrDeserializer { key: key } } } @@ -484,7 +503,8 @@ impl<'de> de::Deserializer<'de> for StrDeserializer<'de> { type Error = Error; fn deserialize_any(self, visitor: V) -> Result - where V: de::Visitor<'de>, + where + V: de::Visitor<'de>, { match self.key { Cow::Borrowed(s) => visitor.visit_borrowed_str(s), @@ -522,7 +542,8 @@ impl<'de> de::Deserializer<'de> for ValueDeserializer<'de> { type Error = Error; fn deserialize_any(self, visitor: V) -> Result - where V: de::Visitor<'de>, + where + V: de::Visitor<'de>, { match self.value.e { E::Integer(i) => visitor.visit_i64(i), @@ -549,25 +570,29 @@ impl<'de> de::Deserializer<'de> for ValueDeserializer<'de> { } } - fn deserialize_struct(self, - name: &'static str, - fields: &'static [&'static str], - visitor: V) -> Result - where V: de::Visitor<'de>, + fn deserialize_struct( + self, + name: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: de::Visitor<'de>, { if name == datetime::NAME && fields == &[datetime::FIELD] { if let E::Datetime(s) = self.value.e { return visitor.visit_map(DatetimeDeserializer { date: s, visited: false, - }) + }); } } if self.validate_struct_keys { match &self.value.e { &E::InlineTable(ref values) | &E::DottedTable(ref values) => { - let extra_fields = values.iter() + let extra_fields = values + .iter() .filter_map(|key_value| { let (ref key, ref _val) = *key_value; if !fields.contains(&&(**key)) { @@ -580,7 +605,10 @@ impl<'de> de::Deserializer<'de> for ValueDeserializer<'de> { if !extra_fields.is_empty() { return Err(Error::from_kind(ErrorKind::UnexpectedKeys { - keys: extra_fields.iter().map(|k| k.to_string()).collect::>(), + keys: extra_fields + .iter() + .map(|k| k.to_string()) + .collect::>(), available: fields, })); } @@ -606,7 +634,8 @@ impl<'de> de::Deserializer<'de> for ValueDeserializer<'de> { // `None` is interpreted as a missing field so be sure to implement `Some` // as a present field. fn deserialize_option(self, visitor: V) -> Result - where V: de::Visitor<'de>, + where + V: de::Visitor<'de>, { visitor.visit_some(self) } @@ -615,9 +644,10 @@ impl<'de> de::Deserializer<'de> for ValueDeserializer<'de> { self, _name: &'static str, _variants: &'static [&'static str], - visitor: V + visitor: V, ) -> Result - where V: de::Visitor<'de> + where + V: de::Visitor<'de>, { match self.value.e { E::String(val) => visitor.visit_enum(val.into_deserializer()), @@ -648,9 +678,10 @@ impl<'de> de::Deserializer<'de> for ValueDeserializer<'de> { fn deserialize_newtype_struct( self, _name: &'static str, - visitor: V + visitor: V, ) -> Result - where V: de::Visitor<'de> + where + V: de::Visitor<'de>, { visitor.visit_newtype_struct(self) } @@ -684,11 +715,14 @@ impl<'de> de::MapAccess<'de> for SpannedDeserializer<'de> { K: de::DeserializeSeed<'de>, { if self.start.is_some() { - seed.deserialize(BorrowedStrDeserializer::new(spanned::START)).map(Some) + seed.deserialize(BorrowedStrDeserializer::new(spanned::START)) + .map(Some) } else if self.end.is_some() { - seed.deserialize(BorrowedStrDeserializer::new(spanned::END)).map(Some) + seed.deserialize(BorrowedStrDeserializer::new(spanned::END)) + .map(Some) } else if self.value.is_some() { - seed.deserialize(BorrowedStrDeserializer::new(spanned::VALUE)).map(Some) + seed.deserialize(BorrowedStrDeserializer::new(spanned::VALUE)) + .map(Some) } else { Ok(None) } @@ -700,7 +734,7 @@ impl<'de> de::MapAccess<'de> for SpannedDeserializer<'de> { { if let Some(start) = self.start.take() { seed.deserialize(start.into_deserializer()) - } else if let Some(end) = self.end.take() { + } else if let Some(end) = self.end.take() { seed.deserialize(end.into_deserializer()) } else if let Some(value) = self.value.take() { seed.deserialize(value.into_deserializer()) @@ -719,17 +753,19 @@ impl<'de> de::MapAccess<'de> for DatetimeDeserializer<'de> { type Error = Error; fn next_key_seed(&mut self, seed: K) -> Result, Error> - where K: de::DeserializeSeed<'de>, + where + K: de::DeserializeSeed<'de>, { if self.visited { - return Ok(None) + return Ok(None); } self.visited = true; seed.deserialize(DatetimeFieldDeserializer).map(Some) } fn next_value_seed(&mut self, seed: V) -> Result - where V: de::DeserializeSeed<'de>, + where + V: de::DeserializeSeed<'de>, { seed.deserialize(StrDeserializer::new(self.date.into())) } @@ -741,7 +777,8 @@ impl<'de> de::Deserializer<'de> for DatetimeFieldDeserializer { type Error = Error; fn deserialize_any(self, visitor: V) -> Result - where V: de::Visitor<'de>, + where + V: de::Visitor<'de>, { visitor.visit_borrowed_str(datetime::FIELD) } @@ -781,7 +818,8 @@ impl<'de> de::MapAccess<'de> for InlineTableDeserializer<'de> { type Error = Error; fn next_key_seed(&mut self, seed: K) -> Result, Error> - where K: de::DeserializeSeed<'de>, + where + K: de::DeserializeSeed<'de>, { let (key, value) = match self.values.next() { Some(pair) => pair, @@ -792,7 +830,8 @@ impl<'de> de::MapAccess<'de> for InlineTableDeserializer<'de> { } fn next_value_seed(&mut self, seed: V) -> Result - where V: de::DeserializeSeed<'de>, + where + V: de::DeserializeSeed<'de>, { let value = self.next_value.take().expect("Unable to read table values"); seed.deserialize(ValueDeserializer::new(value)) @@ -998,12 +1037,12 @@ impl<'a> Deserializer<'a> { loop { self.eat_whitespace()?; if self.eat_comment()? { - continue + continue; } if self.eat(Token::Newline)? { - continue + continue; } - break + break; } match self.peek()? { @@ -1017,9 +1056,7 @@ impl<'a> Deserializer<'a> { let start = self.tokens.current(); self.expect(Token::LeftBracket)?; let array = self.eat(Token::LeftBracket)?; - let ret = Header::new(self.tokens.clone(), - array, - self.require_newline_after_table); + let ret = Header::new(self.tokens.clone(), array, self.require_newline_after_table); if self.require_newline_after_table { self.tokens.skip_to_newline(); } else { @@ -1029,16 +1066,19 @@ impl<'a> Deserializer<'a> { if array { self.eat(Token::RightBracket)?; } - break + break; } - Some((_, Token::Newline)) | - None => break, + Some((_, Token::Newline)) | None => break, _ => {} } } self.eat_whitespace()?; } - Ok(Line::Table { at: start, header: ret, array: array }) + Ok(Line::Table { + at: start, + header: ret, + array: array, + }) } fn key_value(&mut self) -> Result, Error> { @@ -1059,58 +1099,66 @@ impl<'a> Deserializer<'a> { fn value(&mut self) -> Result, Error> { let at = self.tokens.current(); let value = match self.next()? { - Some((Span { start, end }, Token::String { val, .. })) => { - Value { e: E::String(val), start: start, end: end } - } - Some((Span { start, end }, Token::Keylike("true"))) => { - Value { e: E::Boolean(true), start: start, end: end } - } - Some((Span { start, end }, Token::Keylike("false"))) => { - Value { e: E::Boolean(false), start: start, end: end } - } + Some((Span { start, end }, Token::String { val, .. })) => Value { + e: E::String(val), + start: start, + end: end, + }, + Some((Span { start, end }, Token::Keylike("true"))) => Value { + e: E::Boolean(true), + start: start, + end: end, + }, + Some((Span { start, end }, Token::Keylike("false"))) => Value { + e: E::Boolean(false), + start: start, + end: end, + }, Some((span, Token::Keylike(key))) => self.number_or_date(span, key)?, Some((span, Token::Plus)) => self.number_leading_plus(span)?, Some((Span { start, .. }, Token::LeftBrace)) => { self.inline_table().map(|(Span { end, .. }, table)| Value { e: E::InlineTable(table), start: start, - end: end + end: end, })? } Some((Span { start, .. }, Token::LeftBracket)) => { self.array().map(|(Span { end, .. }, array)| Value { e: E::Array(array), start: start, - end: end + end: end, })? } Some(token) => { - return Err(self.error(at, ErrorKind::Wanted { - expected: "a value", - found: token.1.describe(), - })) + return Err(self.error( + at, + ErrorKind::Wanted { + expected: "a value", + found: token.1.describe(), + }, + )) } None => return Err(self.eof()), }; Ok(value) } - fn number_or_date(&mut self, span: Span, s: &'a str) - -> Result, Error> - { - if s.contains('T') || (s.len() > 1 && s[1..].contains('-')) && - !s.contains("e-") { - self.datetime(span, s, false).map(|(Span { start, end }, d)| Value { - e: E::Datetime(d), - start: start, - end: end - }) + fn number_or_date(&mut self, span: Span, s: &'a str) -> Result, Error> { + if s.contains('T') || (s.len() > 1 && s[1..].contains('-')) && !s.contains("e-") { + self.datetime(span, s, false) + .map(|(Span { start, end }, d)| Value { + e: E::Datetime(d), + start: start, + end: end, + }) } else if self.eat(Token::Colon)? { - self.datetime(span, s, true).map(|(Span { start, end }, d)| Value { - e: E::Datetime(d), - start: start, - end: end - }) + self.datetime(span, s, true) + .map(|(Span { start, end }, d)| Value { + e: E::Datetime(d), + start: start, + end: end, + }) } else { self.number(span, s) } @@ -1166,7 +1214,11 @@ impl<'a> Deserializer<'a> { } fn number(&mut self, Span { start, end }: Span, s: &'a str) -> Result, Error> { - let to_integer = |f| Value { e: E::Integer(f), start: start, end: end }; + let to_integer = |f| Value { + e: E::Integer(f), + start: start, + end: end, + }; if s.starts_with("0x") { self.integer(&s[2..], 16).map(to_integer) } else if s.starts_with("0o") { @@ -1174,25 +1226,47 @@ impl<'a> Deserializer<'a> { } else if s.starts_with("0b") { self.integer(&s[2..], 2).map(to_integer) } else if s.contains('e') || s.contains('E') { - self.float(s, None).map(|f| Value { e: E::Float(f), start: start, end: end }) + self.float(s, None).map(|f| Value { + e: E::Float(f), + start: start, + end: end, + }) } else if self.eat(Token::Period)? { let at = self.tokens.current(); match self.next()? { Some((Span { start, end }, Token::Keylike(after))) => { self.float(s, Some(after)).map(|f| Value { - e: E::Float(f), start: start, end: end + e: E::Float(f), + start: start, + end: end, }) } _ => Err(self.error(at, ErrorKind::NumberInvalid)), } } else if s == "inf" { - Ok(Value { e: E::Float(f64::INFINITY), start: start, end: end }) + Ok(Value { + e: E::Float(f64::INFINITY), + start: start, + end: end, + }) } else if s == "-inf" { - Ok(Value { e: E::Float(f64::NEG_INFINITY), start: start, end: end }) + Ok(Value { + e: E::Float(f64::NEG_INFINITY), + start: start, + end: end, + }) } else if s == "nan" { - Ok(Value { e: E::Float(f64::NAN), start: start, end: end }) + Ok(Value { + e: E::Float(f64::NAN), + start: start, + end: end, + }) } else if s == "-nan" { - Ok(Value { e: E::Float(-f64::NAN), start: start, end: end }) + Ok(Value { + e: E::Float(-f64::NAN), + start: start, + end: end, + }) } else { self.integer(s, 10).map(to_integer) } @@ -1201,9 +1275,13 @@ impl<'a> Deserializer<'a> { fn number_leading_plus(&mut self, Span { start, .. }: Span) -> Result, Error> { let start_token = self.tokens.current(); match self.next()? { - Some((Span { end, .. }, Token::Keylike(s))) => { - self.number(Span { start: start, end: end }, s) - }, + Some((Span { end, .. }, Token::Keylike(s))) => self.number( + Span { + start: start, + end: end, + }, + s, + ), _ => Err(self.error(start_token, ErrorKind::NumberInvalid)), } } @@ -1214,7 +1292,7 @@ impl<'a> Deserializer<'a> { let (prefix, suffix) = self.parse_integer(s, allow_sign, allow_leading_zeros, radix)?; let start = self.tokens.substr_offset(s); if suffix != "" { - return Err(self.error(start, ErrorKind::NumberInvalid)) + return Err(self.error(start, ErrorKind::NumberInvalid)); } i64::from_str_radix(&prefix.replace("_", "").trim_left_matches('+'), radix) .map_err(|_e| self.error(start, ErrorKind::NumberInvalid)) @@ -1236,7 +1314,7 @@ impl<'a> Deserializer<'a> { for (i, c) in s.char_indices() { let at = i + start; if i == 0 && (c == '+' || c == '-') && allow_sign { - continue + continue; } if c == '0' && first { @@ -1257,20 +1335,19 @@ impl<'a> Deserializer<'a> { first = false; } if first || underscore { - return Err(self.error(start, ErrorKind::NumberInvalid)) + return Err(self.error(start, ErrorKind::NumberInvalid)); } Ok((&s[..end], &s[end..])) } - fn float(&mut self, s: &'a str, after_decimal: Option<&'a str>) - -> Result { + fn float(&mut self, s: &'a str, after_decimal: Option<&'a str>) -> Result { let (integral, mut suffix) = self.parse_integer(s, true, false, 10)?; let start = self.tokens.substr_offset(integral); let mut fraction = None; if let Some(after) = after_decimal { if suffix != "" { - return Err(self.error(start, ErrorKind::NumberInvalid)) + return Err(self.error(start, ErrorKind::NumberInvalid)); } let (a, b) = self.parse_integer(after, false, true, 10)?; fraction = Some(a); @@ -1282,24 +1359,23 @@ impl<'a> Deserializer<'a> { let (a, b) = if suffix.len() == 1 { self.eat(Token::Plus)?; match self.next()? { - Some((_, Token::Keylike(s))) => { - self.parse_integer(s, false, false, 10)? - } + Some((_, Token::Keylike(s))) => self.parse_integer(s, false, false, 10)?, _ => return Err(self.error(start, ErrorKind::NumberInvalid)), } } else { self.parse_integer(&suffix[1..], true, false, 10)? }; if b != "" { - return Err(self.error(start, ErrorKind::NumberInvalid)) + return Err(self.error(start, ErrorKind::NumberInvalid)); } exponent = Some(a); } - let mut number = integral.trim_left_matches('+') - .chars() - .filter(|c| *c != '_') - .collect::(); + let mut number = integral + .trim_left_matches('+') + .chars() + .filter(|c| *c != '_') + .collect::(); if let Some(fraction) = fraction { number.push_str("."); number.extend(fraction.chars().filter(|c| *c != '_')); @@ -1308,19 +1384,24 @@ impl<'a> Deserializer<'a> { number.push_str("E"); number.extend(exponent.chars().filter(|c| *c != '_')); } - number.parse().map_err(|_e| { - self.error(start, ErrorKind::NumberInvalid) - }).and_then(|n: f64| { - if n.is_finite() { - Ok(n) - } else { - Err(self.error(start, ErrorKind::NumberInvalid)) - } - }) + number + .parse() + .map_err(|_e| self.error(start, ErrorKind::NumberInvalid)) + .and_then(|n: f64| { + if n.is_finite() { + Ok(n) + } else { + Err(self.error(start, ErrorKind::NumberInvalid)) + } + }) } - fn datetime(&mut self, mut span: Span, date: &'a str, colon_eaten: bool) - -> Result<(Span, &'a str), Error> { + fn datetime( + &mut self, + mut span: Span, + date: &'a str, + colon_eaten: bool, + ) -> Result<(Span, &'a str), Error> { let start = self.tokens.substr_offset(date); // Check for space separated date and time. @@ -1328,8 +1409,8 @@ impl<'a> Deserializer<'a> { if let Ok(Some((_, Token::Whitespace(" ")))) = lookahead.next() { // Check if hour follows. if let Ok(Some((_, Token::Keylike(_)))) = lookahead.next() { - self.next()?; // skip space - self.next()?; // skip keylike hour + self.next()?; // skip space + self.next()?; // skip keylike hour } } @@ -1344,7 +1425,7 @@ impl<'a> Deserializer<'a> { match self.next()? { Some((Span { end, .. }, Token::Keylike(_))) => { span.end = end; - }, + } _ => return Err(self.error(start, ErrorKind::DateInvalid)), } // Fractional seconds @@ -1352,7 +1433,7 @@ impl<'a> Deserializer<'a> { match self.next()? { Some((Span { end, .. }, Token::Keylike(_))) => { span.end = end; - }, + } _ => return Err(self.error(start, ErrorKind::DateInvalid)), } } @@ -1362,7 +1443,7 @@ impl<'a> Deserializer<'a> { match self.next()? { Some((Span { end, .. }, Token::Keylike(_))) => { span.end = end; - }, + } _ => return Err(self.error(start, ErrorKind::DateInvalid)), } } @@ -1370,7 +1451,7 @@ impl<'a> Deserializer<'a> { match self.next()? { Some((Span { end, .. }, Token::Keylike(_))) => { span.end = end; - }, + } _ => return Err(self.error(start, ErrorKind::DateInvalid)), } } @@ -1386,7 +1467,7 @@ impl<'a> Deserializer<'a> { let mut ret = Vec::new(); self.eat_whitespace()?; if let Some(span) = self.eat_spanned(Token::RightBrace)? { - return Ok((span, ret)) + return Ok((span, ret)); } loop { let key = self.dotted_key()?; @@ -1398,7 +1479,7 @@ impl<'a> Deserializer<'a> { self.eat_whitespace()?; if let Some(span) = self.eat_spanned(Token::RightBrace)? { - return Ok((span, ret)) + return Ok((span, ret)); } self.expect(Token::Comma)?; self.eat_whitespace()?; @@ -1414,7 +1495,7 @@ impl<'a> Deserializer<'a> { loop { me.eat_whitespace()?; if !me.eat(Token::Newline)? && !me.eat_comment()? { - break + break; } } Ok(()) @@ -1423,19 +1504,19 @@ impl<'a> Deserializer<'a> { loop { intermediate(self)?; if let Some(span) = self.eat_spanned(Token::RightBracket)? { - return Ok((span, ret)) + return Ok((span, ret)); } let at = self.tokens.current(); let value = self.value()?; if let Some(last) = ret.last() { if !value.same_type(last) { - return Err(self.error(at, ErrorKind::MixedArrayType)) + return Err(self.error(at, ErrorKind::MixedArrayType)); } } ret.push(value); intermediate(self)?; if !self.eat(Token::Comma)? { - break + break; } } intermediate(self)?; @@ -1444,7 +1525,10 @@ impl<'a> Deserializer<'a> { } fn table_key(&mut self) -> Result, Error> { - self.tokens.table_key().map(|t| t.1).map_err(|e| self.token_error(e)) + self.tokens + .table_key() + .map(|t| t.1) + .map_err(|e| self.token_error(e)) } fn dotted_key(&mut self) -> Result>, Error> { @@ -1483,7 +1567,13 @@ impl<'a> Deserializer<'a> { return Ok(()); } match values.iter_mut().find(|&&mut (ref k, _)| *k == key) { - Some(&mut (_, Value { e: E::DottedTable(ref mut v), .. })) => { + Some(&mut ( + _, + Value { + e: E::DottedTable(ref mut v), + .. + }, + )) => { return self.add_dotted_key(key_parts, value, v); } Some(&mut (_, Value { start, .. })) => { @@ -1499,14 +1589,23 @@ impl<'a> Deserializer<'a> { }; values.push((key, table_values)); let last_i = values.len() - 1; - if let (_, Value { e: E::DottedTable(ref mut v), .. }) = values[last_i] { + if let ( + _, + Value { + e: E::DottedTable(ref mut v), + .. + }, + ) = values[last_i] + { self.add_dotted_key(key_parts, value, v)?; } Ok(()) } fn eat_whitespace(&mut self) -> Result<(), Error> { - self.tokens.eat_whitespace().map_err(|e| self.token_error(e)) + self.tokens + .eat_whitespace() + .map_err(|e| self.token_error(e)) } fn eat_comment(&mut self) -> Result { @@ -1514,7 +1613,9 @@ impl<'a> Deserializer<'a> { } fn eat_newline_or_eof(&mut self) -> Result<(), Error> { - self.tokens.eat_newline_or_eof().map_err(|e| self.token_error(e)) + self.tokens + .eat_newline_or_eof() + .map_err(|e| self.token_error(e)) } fn eat(&mut self, expected: Token<'a>) -> Result { @@ -1522,15 +1623,21 @@ impl<'a> Deserializer<'a> { } fn eat_spanned(&mut self, expected: Token<'a>) -> Result, Error> { - self.tokens.eat_spanned(expected).map_err(|e| self.token_error(e)) + self.tokens + .eat_spanned(expected) + .map_err(|e| self.token_error(e)) } fn expect(&mut self, expected: Token<'a>) -> Result<(), Error> { - self.tokens.expect(expected).map_err(|e| self.token_error(e)) + self.tokens + .expect(expected) + .map_err(|e| self.token_error(e)) } fn expect_spanned(&mut self, expected: Token<'a>) -> Result { - self.tokens.expect_spanned(expected).map_err(|e| self.token_error(e)) + self.tokens + .expect_spanned(expected) + .map_err(|e| self.token_error(e)) } fn next(&mut self) -> Result)>, Error> { @@ -1550,36 +1657,28 @@ impl<'a> Deserializer<'a> { TokenError::InvalidCharInString(at, ch) => { self.error(at, ErrorKind::InvalidCharInString(ch)) } - TokenError::InvalidEscape(at, ch) => { - self.error(at, ErrorKind::InvalidEscape(ch)) - } + TokenError::InvalidEscape(at, ch) => self.error(at, ErrorKind::InvalidEscape(ch)), TokenError::InvalidEscapeValue(at, v) => { self.error(at, ErrorKind::InvalidEscapeValue(v)) } - TokenError::InvalidHexEscape(at, ch) => { - self.error(at, ErrorKind::InvalidHexEscape(ch)) - } - TokenError::NewlineInString(at) => { - self.error(at, ErrorKind::NewlineInString) - } - TokenError::Unexpected(at, ch) => { - self.error(at, ErrorKind::Unexpected(ch)) - } - TokenError::UnterminatedString(at) => { - self.error(at, ErrorKind::UnterminatedString) - } - TokenError::NewlineInTableKey(at) => { - self.error(at, ErrorKind::NewlineInTableKey) - } - TokenError::Wanted { at, expected, found } => { - self.error(at, ErrorKind::Wanted { expected: expected, found: found }) - } - TokenError::EmptyTableKey(at) => { - self.error(at, ErrorKind::EmptyTableKey) - } - TokenError::MultilineStringKey(at) => { - self.error(at, ErrorKind::MultilineStringKey) - } + TokenError::InvalidHexEscape(at, ch) => self.error(at, ErrorKind::InvalidHexEscape(ch)), + TokenError::NewlineInString(at) => self.error(at, ErrorKind::NewlineInString), + TokenError::Unexpected(at, ch) => self.error(at, ErrorKind::Unexpected(ch)), + TokenError::UnterminatedString(at) => self.error(at, ErrorKind::UnterminatedString), + TokenError::NewlineInTableKey(at) => self.error(at, ErrorKind::NewlineInTableKey), + TokenError::Wanted { + at, + expected, + found, + } => self.error( + at, + ErrorKind::Wanted { + expected: expected, + found: found, + }, + ), + TokenError::EmptyTableKey(at) => self.error(at, ErrorKind::EmptyTableKey), + TokenError::MultilineStringKey(at) => self.error(at, ErrorKind::MultilineStringKey), } } @@ -1598,7 +1697,7 @@ impl<'a> Deserializer<'a> { let mut cur = 0; for (i, line) in self.input.lines().enumerate() { if cur + line.len() + 1 > offset { - return (i, offset - cur) + return (i, offset - cur); } cur += line.len() + 1; } @@ -1650,26 +1749,28 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.inner.kind { ErrorKind::UnexpectedEof => "unexpected eof encountered".fmt(f)?, - ErrorKind::InvalidCharInString(c) => { - write!(f, "invalid character in string: `{}`", - c.escape_default().collect::())? - } - ErrorKind::InvalidEscape(c) => { - write!(f, "invalid escape character in string: `{}`", - c.escape_default().collect::())? - } - ErrorKind::InvalidHexEscape(c) => { - write!(f, "invalid hex escape character in string: `{}`", - c.escape_default().collect::())? - } - ErrorKind::InvalidEscapeValue(c) => { - write!(f, "invalid escape value: `{}`", c)? - } + ErrorKind::InvalidCharInString(c) => write!( + f, + "invalid character in string: `{}`", + c.escape_default().collect::() + )?, + ErrorKind::InvalidEscape(c) => write!( + f, + "invalid escape character in string: `{}`", + c.escape_default().collect::() + )?, + ErrorKind::InvalidHexEscape(c) => write!( + f, + "invalid hex escape character in string: `{}`", + c.escape_default().collect::() + )?, + ErrorKind::InvalidEscapeValue(c) => write!(f, "invalid escape value: `{}`", c)?, ErrorKind::NewlineInString => "newline in string found".fmt(f)?, - ErrorKind::Unexpected(ch) => { - write!(f, "unexpected character found: `{}`", - ch.escape_default().collect::())? - } + ErrorKind::Unexpected(ch) => write!( + f, + "unexpected character found: `{}`", + ch.escape_default().collect::() + )?, ErrorKind::UnterminatedString => "unterminated string".fmt(f)?, ErrorKind::NewlineInTableKey => "found newline in table key".fmt(f)?, ErrorKind::Wanted { expected, found } => { @@ -1694,14 +1795,14 @@ impl fmt::Display for Error { ErrorKind::DottedKeyInvalidType => { "dotted key attempted to extend non-table type".fmt(f)? } - ErrorKind::UnexpectedKeys { ref keys, available } => { - write!( - f, - "unexpected keys in table: `{:?}`, available keys: `{:?}`", - keys, - available - )? - } + ErrorKind::UnexpectedKeys { + ref keys, + available, + } => write!( + f, + "unexpected keys in table: `{:?}`, available keys: `{:?}`", + keys, available + )?, ErrorKind::__Nonexhaustive => panic!(), } @@ -1762,7 +1863,11 @@ impl de::Error for Error { } enum Line<'a> { - Table { at: usize, header: Header<'a>, array: bool }, + Table { + at: usize, + header: Header<'a>, + array: bool, + }, KeyValue(Vec>, Value<'a>), } @@ -1774,9 +1879,7 @@ struct Header<'a> { } impl<'a> Header<'a> { - fn new(tokens: Tokenizer<'a>, - array: bool, - require_newline_after_table: bool) -> Header<'a> { + fn new(tokens: Tokenizer<'a>, array: bool, require_newline_after_table: bool) -> Header<'a> { Header { first: true, array: array, @@ -1846,13 +1949,13 @@ impl<'a> E<'a> { impl<'a> Value<'a> { fn same_type(&self, other: &Value<'a>) -> bool { match (&self.e, &other.e) { - (&E::String(..), &E::String(..)) | - (&E::Integer(..), &E::Integer(..)) | - (&E::Float(..), &E::Float(..)) | - (&E::Boolean(..), &E::Boolean(..)) | - (&E::Datetime(..), &E::Datetime(..)) | - (&E::Array(..), &E::Array(..)) | - (&E::InlineTable(..), &E::InlineTable(..)) => true, + (&E::String(..), &E::String(..)) + | (&E::Integer(..), &E::Integer(..)) + | (&E::Float(..), &E::Float(..)) + | (&E::Boolean(..), &E::Boolean(..)) + | (&E::Datetime(..), &E::Datetime(..)) + | (&E::Array(..), &E::Array(..)) + | (&E::InlineTable(..), &E::InlineTable(..)) => true, (&E::DottedTable(..), &E::DottedTable(..)) => true, _ => false, diff --git a/src/macros.rs b/src/macros.rs index b4c7b22..8b76591 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -1,6 +1,6 @@ pub use serde::de::{Deserialize, IntoDeserializer}; -use value::{Value, Table, Array}; +use value::{Array, Table, Value}; /// Construct a [`toml::Value`] from TOML syntax. /// @@ -424,7 +424,10 @@ pub fn push_toml(root: &mut Value, path: &[&str]) { if !target.is_array() { *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 { diff --git a/src/ser.rs b/src/ser.rs index e1fe1a2..60e5b50 100644 --- a/src/ser.rs +++ b/src/ser.rs @@ -32,8 +32,8 @@ use std::fmt::{self, Write}; use std::marker; use std::rc::Rc; -use serde::ser; use datetime; +use serde::ser; /// Serialize the given data structure as a TOML byte vector. /// @@ -41,7 +41,8 @@ use datetime; /// fail, if `T` contains a map with non-string keys, or if `T` attempts to /// serialize an unsupported datatype such as an enum, tuple, or tuple struct. pub fn to_vec(value: &T) -> Result, Error> - where T: ser::Serialize, +where + T: ser::Serialize, { to_string(value).map(|e| e.into_bytes()) } @@ -87,7 +88,8 @@ pub fn to_vec(value: &T) -> Result, Error> /// } /// ``` pub fn to_string(value: &T) -> Result - where T: ser::Serialize, +where + T: ser::Serialize, { let mut dst = String::with_capacity(128); value.serialize(&mut Serializer::new(&mut dst))?; @@ -99,7 +101,8 @@ pub fn to_string(value: &T) -> Result /// This is identical to `to_string` except the output string has a more /// "pretty" output. See `Serializer::pretty` for more details. pub fn to_string_pretty(value: &T) -> Result - where T: ser::Serialize, +where + T: ser::Serialize, { let mut dst = String::with_capacity(128); value.serialize(&mut Serializer::pretty(&mut dst))?; @@ -177,9 +180,7 @@ struct StringSettings { impl StringSettings { fn pretty() -> StringSettings { - StringSettings { - literal: true, - } + StringSettings { literal: true } } } @@ -239,7 +240,7 @@ pub enum SerializeTable<'a: 'b, 'b> { key: String, first: Cell, table_emitted: Cell, - } + }, } impl<'a> Serializer<'a> { @@ -333,13 +334,13 @@ impl<'a> Serializer<'a> { /// """ /// ``` pub fn pretty_string_literal(&mut self, value: bool) -> &mut Self { - let use_default = if let &mut Some(ref mut s) = &mut Rc::get_mut(&mut self.settings) - .unwrap().string { - s.literal = value; - false - } else { - true - }; + let use_default = + if let &mut Some(ref mut s) = &mut Rc::get_mut(&mut self.settings).unwrap().string { + s.literal = value; + false + } else { + true + }; if use_default { let mut string = StringSettings::pretty(); @@ -389,13 +390,13 @@ impl<'a> Serializer<'a> { /// /// See `Serializer::pretty_array` for more details. pub fn pretty_array_indent(&mut self, value: usize) -> &mut Self { - let use_default = if let &mut Some(ref mut a) = &mut Rc::get_mut(&mut self.settings) - .unwrap().array { - a.indent = value; - false - } else { - true - }; + let use_default = + if let &mut Some(ref mut a) = &mut Rc::get_mut(&mut self.settings).unwrap().array { + a.indent = value; + false + } else { + true + }; if use_default { let mut array = ArraySettings::pretty(); @@ -409,13 +410,13 @@ impl<'a> Serializer<'a> { /// /// See `Serializer::pretty_array` for more details. pub fn pretty_array_trailing_comma(&mut self, value: bool) -> &mut Self { - let use_default = if let &mut Some(ref mut a) = &mut Rc::get_mut(&mut self.settings) - .unwrap().array { - a.trailing_comma = value; - false - } else { - true - }; + let use_default = + if let &mut Some(ref mut a) = &mut Rc::get_mut(&mut self.settings).unwrap().array { + a.trailing_comma = value; + false + } else { + true + }; if use_default { let mut array = ArraySettings::pretty(); @@ -425,9 +426,7 @@ impl<'a> Serializer<'a> { self } - fn display(&mut self, - t: T, - type_: &'static str) -> Result<(), Error> { + fn display(&mut self, t: T, type_: &'static str) -> Result<(), Error> { self.emit_key(type_)?; drop(write!(self.dst, "{}", t)); if let State::Table { .. } = self.state { @@ -446,16 +445,26 @@ impl<'a> Serializer<'a> { fn _emit_key(&mut self, state: &State) -> Result<(), Error> { match *state { State::End => Ok(()), - State::Array { parent, first, type_, len } => { + State::Array { + parent, + first, + type_, + len, + } => { assert!(type_.get().is_some()); if first.get() { self._emit_key(parent)?; } self.emit_array(first, len) } - State::Table { parent, first, table_emitted, key } => { + State::Table { + parent, + first, + table_emitted, + key, + } => { if table_emitted.get() { - return Err(Error::ValueAfterTable) + return Err(Error::ValueAfterTable); } if first.get() { self.emit_table_header(parent)?; @@ -476,7 +485,7 @@ impl<'a> Serializer<'a> { } else { self.dst.push_str(", ") } - }, + } (_, &Some(ref a)) => { if first.get() { self.dst.push_str("[\n") @@ -486,7 +495,7 @@ impl<'a> Serializer<'a> { for _ in 0..a.indent { self.dst.push_str(" "); } - }, + } } Ok(()) } @@ -498,7 +507,7 @@ impl<'a> Serializer<'a> { }; if let Some(prev) = prev.get() { if prev != type_ { - return Err(Error::ArrayMixedType) + return Err(Error::ArrayMixedType); } } else { prev.set(Some(type_)); @@ -507,14 +516,9 @@ impl<'a> Serializer<'a> { } fn escape_key(&mut self, key: &str) -> Result<(), Error> { - let ok = key.chars().all(|c| { - match c { - 'a' ... 'z' | - 'A' ... 'Z' | - '0' ... '9' | - '-' | '_' => true, - _ => false, - } + let ok = key.chars().all(|c| match c { + 'a'...'z' | 'A'...'Z' | '0'...'9' | '-' | '_' => true, + _ => false, }); if ok { drop(write!(self.dst, "{}", key)); @@ -570,7 +574,7 @@ impl<'a> Serializer<'a> { found_singles = 0 } match ch { - '\t' => {}, + '\t' => {} '\n' => ty = Type::NewlineTripple, // note that the following are invalid: \b \f \r c if c < '\u{1f}' => can_be_pretty = false, // Invalid control character @@ -606,8 +610,9 @@ impl<'a> Serializer<'a> { let repr = if !is_key && self.settings.string.is_some() { match (&self.settings.string, do_pretty(value)) { - (&Some(StringSettings { literal: false, .. }), Repr::Literal(_, ty)) => - Repr::Std(ty), + (&Some(StringSettings { literal: false, .. }), Repr::Literal(_, ty)) => { + Repr::Std(ty) + } (_, r @ _) => r, } } else { @@ -626,26 +631,23 @@ impl<'a> Serializer<'a> { Type::OnelineSingle => self.dst.push('\''), _ => self.dst.push_str("'''"), } - }, + } Repr::Std(ty) => { match ty { - Type::NewlineTripple => self.dst.push_str("\"\"\"\n"), + Type::NewlineTripple => self.dst.push_str("\"\"\"\n"), // note: OnelineTripple can happen if do_pretty wants to do // '''it's one line''' // but settings.string.literal == false - Type::OnelineSingle | - Type::OnelineTripple => self.dst.push('"'), + Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'), } for ch in value.chars() { match ch { '\u{8}' => self.dst.push_str("\\b"), '\u{9}' => self.dst.push_str("\\t"), - '\u{a}' => { - match ty { - Type::NewlineTripple => self.dst.push('\n'), - Type::OnelineSingle => self.dst.push_str("\\n"), - _ => unreachable!(), - } + '\u{a}' => match ty { + Type::NewlineTripple => self.dst.push('\n'), + Type::OnelineSingle => self.dst.push_str("\\n"), + _ => unreachable!(), }, '\u{c}' => self.dst.push_str("\\f"), '\u{d}' => self.dst.push_str("\\r"), @@ -656,10 +658,10 @@ impl<'a> Serializer<'a> { } } match ty { - Type::NewlineTripple => self.dst.push_str("\"\"\""), + Type::NewlineTripple => self.dst.push_str("\"\"\""), Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'), } - }, + } } Ok(()) } @@ -684,7 +686,11 @@ impl<'a> Serializer<'a> { if !first.get() { break; } - if let State::Array { parent: &State::Table {..}, ..} = *parent { + if let State::Array { + parent: &State::Table { .. }, + .. + } = *parent + { self.emit_table_header(parent)?; break; } @@ -697,7 +703,7 @@ impl<'a> Serializer<'a> { // table in the document. self.dst.push('\n'); } - }, + } State::Array { parent, first, .. } => { if !first.get() { // Always newline if we are not the first item in the @@ -709,7 +715,7 @@ impl<'a> Serializer<'a> { self.dst.push('\n'); } } - }, + } _ => {} } self.dst.push_str("["); @@ -728,9 +734,14 @@ impl<'a> Serializer<'a> { match *key { State::Array { parent, .. } => self.emit_key_part(parent), State::End => Ok(true), - State::Table { key, parent, table_emitted, .. } => { + State::Table { + key, + parent, + table_emitted, + .. + } => { table_emitted.set(true); - let first = self.emit_key_part(parent)?; + let first = self.emit_key_part(parent)?; if !first { self.dst.push_str("."); } @@ -841,7 +852,8 @@ impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> { } fn serialize_some(self, value: &T) -> Result<(), Self::Error> - where T: ser::Serialize + where + T: ser::Serialize, { value.serialize(self) } @@ -850,40 +862,44 @@ impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> { Err(Error::UnsupportedType) } - fn serialize_unit_struct(self, - _name: &'static str) - -> Result<(), Self::Error> { + fn serialize_unit_struct(self, _name: &'static str) -> Result<(), Self::Error> { Err(Error::UnsupportedType) } - fn serialize_unit_variant(self, - _name: &'static str, - _variant_index: u32, - variant: &'static str) - -> Result<(), Self::Error> { + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + ) -> Result<(), Self::Error> { self.serialize_str(variant) } - fn serialize_newtype_struct(self, _name: &'static str, value: &T) - -> Result<(), Self::Error> - where T: ser::Serialize, + fn serialize_newtype_struct( + self, + _name: &'static str, + value: &T, + ) -> Result<(), Self::Error> + where + T: ser::Serialize, { value.serialize(self) } - fn serialize_newtype_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _value: &T) - -> Result<(), Self::Error> - where T: ser::Serialize, + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T, + ) -> Result<(), Self::Error> + where + T: ser::Serialize, { Err(Error::UnsupportedType) } - fn serialize_seq(self, len: Option) - -> Result { + fn serialize_seq(self, len: Option) -> Result { self.array_type("array")?; Ok(SerializeSeq { ser: self, @@ -893,27 +909,29 @@ impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> { }) } - fn serialize_tuple(self, len: usize) - -> Result { + fn serialize_tuple(self, len: usize) -> Result { self.serialize_seq(Some(len)) } - fn serialize_tuple_struct(self, _name: &'static str, len: usize) - -> Result { + fn serialize_tuple_struct( + self, + _name: &'static str, + len: usize, + ) -> Result { self.serialize_seq(Some(len)) } - fn serialize_tuple_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - len: usize) - -> Result { + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + len: usize, + ) -> Result { self.serialize_seq(Some(len)) } - fn serialize_map(self, _len: Option) - -> Result { + fn serialize_map(self, _len: Option) -> Result { self.array_type("table")?; Ok(SerializeTable::Table { ser: self, @@ -923,8 +941,11 @@ impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> { }) } - fn serialize_struct(self, name: &'static str, _len: usize) - -> Result { + fn serialize_struct( + self, + name: &'static str, + _len: usize, + ) -> Result { if name == datetime::NAME { self.array_type("datetime")?; Ok(SerializeTable::Datetime(self)) @@ -939,12 +960,13 @@ impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> { } } - fn serialize_struct_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result { + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { Err(Error::UnsupportedType) } } @@ -954,7 +976,8 @@ impl<'a, 'b> ser::SerializeSeq for SerializeSeq<'a, 'b> { type Error = Error; fn serialize_element(&mut self, value: &T) -> Result<(), Error> - where T: ser::Serialize, + where + T: ser::Serialize, { value.serialize(&mut Serializer { dst: &mut *self.ser.dst, @@ -973,19 +996,17 @@ impl<'a, 'b> ser::SerializeSeq for SerializeSeq<'a, 'b> { fn end(self) -> Result<(), Error> { match self.type_.get() { Some("table") => return Ok(()), - Some(_) => { - match (self.len, &self.ser.settings.array) { - (Some(0...1), _) | (_, &None) => { - self.ser.dst.push_str("]"); - }, - (_, &Some(ref a)) => { - if a.trailing_comma { - self.ser.dst.push_str(","); - } - self.ser.dst.push_str("\n]"); - }, + Some(_) => match (self.len, &self.ser.settings.array) { + (Some(0...1), _) | (_, &None) => { + self.ser.dst.push_str("]"); } - } + (_, &Some(ref a)) => { + if a.trailing_comma { + self.ser.dst.push_str(","); + } + self.ser.dst.push_str("\n]"); + } + }, None => { assert!(self.first.get()); self.ser.emit_key("array")?; @@ -1004,7 +1025,8 @@ impl<'a, 'b> ser::SerializeTuple for SerializeSeq<'a, 'b> { type Error = Error; fn serialize_element(&mut self, value: &T) -> Result<(), Error> - where T: ser::Serialize, + where + T: ser::Serialize, { ser::SerializeSeq::serialize_element(self, value) } @@ -1019,7 +1041,8 @@ impl<'a, 'b> ser::SerializeTupleVariant for SerializeSeq<'a, 'b> { type Error = Error; fn serialize_field(&mut self, value: &T) -> Result<(), Error> - where T: ser::Serialize, + where + T: ser::Serialize, { ser::SerializeSeq::serialize_element(self, value) } @@ -1034,7 +1057,8 @@ impl<'a, 'b> ser::SerializeTupleStruct for SerializeSeq<'a, 'b> { type Error = Error; fn serialize_field(&mut self, value: &T) -> Result<(), Error> - where T: ser::Serialize, + where + T: ser::Serialize, { ser::SerializeSeq::serialize_element(self, value) } @@ -1049,7 +1073,8 @@ impl<'a, 'b> ser::SerializeMap for SerializeTable<'a, 'b> { type Error = Error; fn serialize_key(&mut self, input: &T) -> Result<(), Error> - where T: ser::Serialize, + where + T: ser::Serialize, { match *self { SerializeTable::Datetime(_) => panic!(), // shouldn't be possible @@ -1062,7 +1087,8 @@ impl<'a, 'b> ser::SerializeMap for SerializeTable<'a, 'b> { } fn serialize_value(&mut self, value: &T) -> Result<(), Error> - where T: ser::Serialize, + where + T: ser::Serialize, { match *self { SerializeTable::Datetime(_) => panic!(), // shouldn't be possible @@ -1085,7 +1111,7 @@ impl<'a, 'b> ser::SerializeMap for SerializeTable<'a, 'b> { }); match res { Ok(()) => first.set(false), - Err(Error::UnsupportedNone) => {}, + Err(Error::UnsupportedNone) => {} Err(e) => return Err(e), } } @@ -1096,7 +1122,7 @@ impl<'a, 'b> ser::SerializeMap for SerializeTable<'a, 'b> { fn end(self) -> Result<(), Error> { match self { SerializeTable::Datetime(_) => panic!(), // shouldn't be possible - SerializeTable::Table { ser, first, .. } => { + SerializeTable::Table { ser, first, .. } => { if first.get() { let state = ser.state.clone(); ser.emit_table_header(&state)?; @@ -1111,16 +1137,16 @@ impl<'a, 'b> ser::SerializeStruct for SerializeTable<'a, 'b> { type Ok = (); type Error = Error; - fn serialize_field(&mut self, key: &'static str, value: &T) - -> Result<(), Error> - where T: ser::Serialize, + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where + T: ser::Serialize, { match *self { SerializeTable::Datetime(ref mut ser) => { if key == datetime::FIELD { value.serialize(DateStrEmitter(&mut *ser))?; } else { - return Err(Error::DateInvalid) + return Err(Error::DateInvalid); } } SerializeTable::Table { @@ -1141,7 +1167,7 @@ impl<'a, 'b> ser::SerializeStruct for SerializeTable<'a, 'b> { }); match res { Ok(()) => first.set(false), - Err(Error::UnsupportedNone) => {}, + Err(Error::UnsupportedNone) => {} Err(e) => return Err(e), } } @@ -1151,8 +1177,8 @@ impl<'a, 'b> ser::SerializeStruct for SerializeTable<'a, 'b> { fn end(self) -> Result<(), Error> { match self { - SerializeTable::Datetime(_) => {}, - SerializeTable::Table { ser, first, .. } => { + SerializeTable::Datetime(_) => {} + SerializeTable::Table { ser, first, .. } => { if first.get() { let state = ser.state.clone(); ser.emit_table_header(&state)?; @@ -1238,7 +1264,8 @@ impl<'a, 'b> ser::Serializer for DateStrEmitter<'a, 'b> { } fn serialize_some(self, _value: &T) -> Result<(), Self::Error> - where T: ser::Serialize + where + T: ser::Serialize, { Err(Error::KeyNotString) } @@ -1247,78 +1274,88 @@ impl<'a, 'b> ser::Serializer for DateStrEmitter<'a, 'b> { Err(Error::KeyNotString) } - fn serialize_unit_struct(self, - _name: &'static str) - -> Result<(), Self::Error> { + fn serialize_unit_struct(self, _name: &'static str) -> Result<(), Self::Error> { Err(Error::DateInvalid) } - fn serialize_unit_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str) - -> Result<(), Self::Error> { + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + ) -> Result<(), Self::Error> { Err(Error::DateInvalid) } - fn serialize_newtype_struct(self, _name: &'static str, _value: &T) - -> Result<(), Self::Error> - where T: ser::Serialize, + fn serialize_newtype_struct( + self, + _name: &'static str, + _value: &T, + ) -> Result<(), Self::Error> + where + T: ser::Serialize, { Err(Error::DateInvalid) } - fn serialize_newtype_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _value: &T) - -> Result<(), Self::Error> - where T: ser::Serialize, + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T, + ) -> Result<(), Self::Error> + where + T: ser::Serialize, { Err(Error::DateInvalid) } - fn serialize_seq(self, _len: Option) - -> Result { + fn serialize_seq(self, _len: Option) -> Result { Err(Error::DateInvalid) } - fn serialize_tuple(self, _len: usize) - -> Result { + fn serialize_tuple(self, _len: usize) -> Result { Err(Error::DateInvalid) } - fn serialize_tuple_struct(self, _name: &'static str, _len: usize) - -> Result { + fn serialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { Err(Error::DateInvalid) } - fn serialize_tuple_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result { + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { Err(Error::DateInvalid) } - fn serialize_map(self, _len: Option) - -> Result { + fn serialize_map(self, _len: Option) -> Result { Err(Error::DateInvalid) } - fn serialize_struct(self, _name: &'static str, _len: usize) - -> Result { + fn serialize_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { Err(Error::DateInvalid) } - fn serialize_struct_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result { + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { Err(Error::DateInvalid) } } @@ -1397,7 +1434,8 @@ impl ser::Serializer for StringExtractor { } fn serialize_some(self, _value: &T) -> Result - where T: ser::Serialize + where + T: ser::Serialize, { Err(Error::KeyNotString) } @@ -1406,78 +1444,88 @@ impl ser::Serializer for StringExtractor { Err(Error::KeyNotString) } - fn serialize_unit_struct(self, - _name: &'static str) - -> Result { + fn serialize_unit_struct(self, _name: &'static str) -> Result { Err(Error::KeyNotString) } - fn serialize_unit_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str) - -> Result { + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + ) -> Result { Err(Error::KeyNotString) } - fn serialize_newtype_struct(self, _name: &'static str, value: &T) - -> Result - where T: ser::Serialize, + fn serialize_newtype_struct( + self, + _name: &'static str, + value: &T, + ) -> Result + where + T: ser::Serialize, { value.serialize(self) } - fn serialize_newtype_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _value: &T) - -> Result - where T: ser::Serialize, + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T, + ) -> Result + where + T: ser::Serialize, { Err(Error::KeyNotString) } - fn serialize_seq(self, _len: Option) - -> Result { + fn serialize_seq(self, _len: Option) -> Result { Err(Error::KeyNotString) } - fn serialize_tuple(self, _len: usize) - -> Result { + fn serialize_tuple(self, _len: usize) -> Result { Err(Error::KeyNotString) } - fn serialize_tuple_struct(self, _name: &'static str, _len: usize) - -> Result { + fn serialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { Err(Error::KeyNotString) } - fn serialize_tuple_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result { + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { Err(Error::KeyNotString) } - fn serialize_map(self, _len: Option) - -> Result { + fn serialize_map(self, _len: Option) -> Result { Err(Error::KeyNotString) } - fn serialize_struct(self, _name: &'static str, _len: usize) - -> Result { + fn serialize_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { Err(Error::KeyNotString) } - fn serialize_struct_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result { + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { Err(Error::KeyNotString) } } @@ -1549,12 +1597,12 @@ enum Category { /// # type Dependency = String; /// # fn main() {} /// ``` -pub fn tables_last<'a, I, K, V, S>(data: &'a I, serializer: S) - -> Result - where &'a I: IntoIterator, - K: ser::Serialize, - V: ser::Serialize, - S: ser::Serializer +pub fn tables_last<'a, I, K, V, S>(data: &'a I, serializer: S) -> Result +where + &'a I: IntoIterator, + K: ser::Serialize, + V: ser::Serialize, + S: ser::Serializer, { use serde::ser::SerializeMap; @@ -1668,15 +1716,30 @@ impl ser::Serializer for Categorize { Err(ser::Error::custom("unsupported")) } - fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Result { + fn serialize_unit_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + ) -> Result { Err(ser::Error::custom("unsupported")) } - fn serialize_newtype_struct(self, _: &'static str, v: &T) -> Result { + fn serialize_newtype_struct( + self, + _: &'static str, + v: &T, + ) -> Result { v.serialize(self) } - fn serialize_newtype_variant(self, _: &'static str, _: u32, _: &'static str, _: &T) -> Result { + fn serialize_newtype_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: &T, + ) -> Result { Err(ser::Error::custom("unsupported")) } @@ -1688,11 +1751,21 @@ impl ser::Serializer for Categorize { Ok(self) } - fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result { + fn serialize_tuple_struct( + self, + _: &'static str, + _: usize, + ) -> Result { Ok(self) } - fn serialize_tuple_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result { + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { Ok(self) } @@ -1704,7 +1777,13 @@ impl ser::Serializer for Categorize { Ok(self) } - fn serialize_struct_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result { + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result { Err(ser::Error::custom("unsupported")) } } @@ -1713,8 +1792,7 @@ impl ser::SerializeSeq for Categorize { type Ok = Category; type Error = E; - fn serialize_element(&mut self, _: &T) - -> Result<(), Self::Error> { + fn serialize_element(&mut self, _: &T) -> Result<(), Self::Error> { Ok(()) } @@ -1727,8 +1805,7 @@ impl ser::SerializeTuple for Categorize { type Ok = Category; type Error = E; - fn serialize_element(&mut self, _: &T) - -> Result<(), Self::Error> { + fn serialize_element(&mut self, _: &T) -> Result<(), Self::Error> { Ok(()) } @@ -1741,8 +1818,7 @@ impl ser::SerializeTupleVariant for Categorize { type Ok = Category; type Error = E; - fn serialize_field(&mut self, _: &T) - -> Result<(), Self::Error> { + fn serialize_field(&mut self, _: &T) -> Result<(), Self::Error> { Ok(()) } @@ -1755,8 +1831,7 @@ impl ser::SerializeTupleStruct for Categorize { type Ok = Category; type Error = E; - fn serialize_field(&mut self, _: &T) - -> Result<(), Self::Error> { + fn serialize_field(&mut self, _: &T) -> Result<(), Self::Error> { Ok(()) } @@ -1769,13 +1844,11 @@ impl ser::SerializeMap for Categorize { type Ok = Category; type Error = E; - fn serialize_key(&mut self, _: &T) - -> Result<(), Self::Error> { + fn serialize_key(&mut self, _: &T) -> Result<(), Self::Error> { Ok(()) } - fn serialize_value(&mut self, _: &T) - -> Result<(), Self::Error> { + fn serialize_value(&mut self, _: &T) -> Result<(), Self::Error> { Ok(()) } @@ -1788,10 +1861,9 @@ impl ser::SerializeStruct for Categorize { type Ok = Category; type Error = E; - fn serialize_field(&mut self, - _: &'static str, - _: &T) -> Result<(), Self::Error> - where T: ser::Serialize, + fn serialize_field(&mut self, _: &'static str, _: &T) -> Result<(), Self::Error> + where + T: ser::Serialize, { Ok(()) } diff --git a/src/spanned.rs b/src/spanned.rs index abbbd49..fb476ee 100644 --- a/src/spanned.rs +++ b/src/spanned.rs @@ -78,15 +78,18 @@ impl Spanned { } impl<'de, T> de::Deserialize<'de> for Spanned - where T: de::Deserialize<'de> +where + T: de::Deserialize<'de>, { fn deserialize(deserializer: D) -> Result, D::Error> - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct SpannedVisitor(::std::marker::PhantomData); impl<'de, T> de::Visitor<'de> for SpannedVisitor - where T: de::Deserialize<'de> + where + T: de::Deserialize<'de>, { type Value = Spanned; @@ -95,22 +98,23 @@ impl<'de, T> de::Deserialize<'de> for Spanned } fn visit_map(self, mut visitor: V) -> Result, V::Error> - where V: de::MapAccess<'de> + where + V: de::MapAccess<'de>, { 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()?; 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()?; 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()?; @@ -118,7 +122,7 @@ impl<'de, T> de::Deserialize<'de> for Spanned Ok(Spanned { start: start, end: end, - value: value + value: value, }) } } diff --git a/src/tokens.rs b/src/tokens.rs index 382c1ec..064c804 100644 --- a/src/tokens.rs +++ b/src/tokens.rs @@ -38,7 +38,11 @@ pub enum Token<'a> { RightBracket, 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)] @@ -53,7 +57,11 @@ pub enum Error { NewlineInTableKey(usize), MultilineStringKey(usize), EmptyTableKey(usize), - Wanted { at: usize, expected: &'static str, found: &'static str }, + Wanted { + at: usize, + expected: &'static str, + found: &'static str, + }, } #[derive(Clone)] @@ -101,10 +109,16 @@ impl<'a> Tokenizer<'a> { Some((start, '}')) => (start, RightBrace), Some((start, '[')) => (start, LeftBracket), Some((start, ']')) => (start, RightBracket), - Some((start, '\'')) => return self.literal_string(start) - .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, '\'')) => { + return self + .literal_string(start) + .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)) => return Err(Error::Unexpected(start, ch)), @@ -156,13 +170,11 @@ impl<'a> Tokenizer<'a> { }) } } - None => { - Err(Error::Wanted { - at: self.input.len(), - expected: expected.describe(), - found: "eof", - }) - } + None => Err(Error::Wanted { + at: self.input.len(), + expected: expected.describe(), + found: "eof", + }), } } @@ -170,33 +182,36 @@ impl<'a> Tokenizer<'a> { let current = self.current(); match self.next()? { 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); if multiline { - return Err(Error::MultilineStringKey(offset)) + return Err(Error::MultilineStringKey(offset)); } if val == "" { - return Err(Error::EmptyTableKey(offset)) + return Err(Error::EmptyTableKey(offset)); } match src.find('\n') { None => Ok((span, val)), Some(i) => Err(Error::NewlineInTableKey(offset + i)), } } - Some((_, other)) => { - Err(Error::Wanted { - at: current, - expected: "a table key", - found: other.describe(), - }) - } - None => { - Err(Error::Wanted { - at: self.input.len(), - expected: "a table key", - found: "eof", - }) - } + Some((_, other)) => Err(Error::Wanted { + at: current, + expected: "a table key", + found: other.describe(), + }), + None => Err(Error::Wanted { + 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 { if !self.eatc('#') { - return Ok(false) + return Ok(false); } drop(self.comment_token(0)); 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> { let current = self.current(); match self.next()? { - None | - Some((_, Token::Newline)) => Ok(()), - Some((_, other)) => { - Err(Error::Wanted { - at: current, - expected: "newline", - found: other.describe(), - }) - } + None | Some((_, Token::Newline)) => Ok(()), + Some((_, other)) => Err(Error::Wanted { + at: current, + expected: "newline", + found: other.describe(), + }), } } pub fn skip_to_newline(&mut self) { loop { match self.one() { - Some((_, '\n')) | - None => break, + Some((_, '\n')) | None => break, _ => {} } } @@ -251,7 +262,11 @@ impl<'a> Tokenizer<'a> { } 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 { @@ -268,30 +283,35 @@ impl<'a> Tokenizer<'a> { fn comment_token(&mut self, start: usize) -> Token<'a> { while let Some((_, ch)) = self.chars.clone().next() { if ch != '\t' && (ch < '\u{20}' || ch > '\u{10ffff}') { - break + break; } self.one(); } Comment(&self.input[start..self.current()]) } - fn read_string(&mut self, - delim: char, - start: usize, - new_ch: &mut FnMut(&mut Tokenizer, &mut MaybeString, - bool, usize, char) - -> Result<(), Error>) - -> Result, Error> { + fn read_string( + &mut self, + delim: char, + start: usize, + new_ch: &mut FnMut( + &mut Tokenizer, + &mut MaybeString, + bool, + usize, + char, + ) -> Result<(), Error>, + ) -> Result, Error> { let mut multiline = false; if self.eatc(delim) { if self.eatc(delim) { multiline = true; } else { return Ok(String { - src: &self.input[start..start+2], + src: &self.input[start..start + 2], val: Cow::Borrowed(""), multiline: false, - }) + }); } } let mut val = MaybeString::NotEscaped(self.current()); @@ -309,9 +329,9 @@ impl<'a> Tokenizer<'a> { } else { val.push('\n'); } - continue + continue; } else { - return Err(Error::NewlineInString(i)) + return Err(Error::NewlineInString(i)); } } Some((i, ch)) if ch == delim => { @@ -319,7 +339,7 @@ impl<'a> Tokenizer<'a> { for _ in 0..2 { if !self.eatc(delim) { val.push(delim); - continue 'outer + continue 'outer; } } } @@ -327,10 +347,10 @@ impl<'a> Tokenizer<'a> { src: &self.input[start..self.current()], val: val.into_cow(&self.input[..i]), multiline: multiline, - }) + }); } 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, Error> { - self.read_string('"', start, &mut |me, val, multi, i, ch| { - match ch { - '\\' => { - val.to_owned(&me.input[..i]); - match me.chars.next() { - Some((_, '"')) => val.push('"'), - Some((_, '\\')) => val.push('\\'), - Some((_, 'b')) => val.push('\u{8}'), - Some((_, 'f')) => val.push('\u{c}'), - Some((_, 'n')) => val.push('\n'), - Some((_, 'r')) => val.push('\r'), - Some((_, 't')) => val.push('\t'), - Some((i, c @ 'u')) | - Some((i, c @ 'U')) => { - 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' { - 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)), - } - } - } + self.read_string('"', start, &mut |me, val, multi, i, ch| match ch { + '\\' => { + val.to_owned(&me.input[..i]); + match me.chars.next() { + Some((_, '"')) => val.push('"'), + Some((_, '\\')) => val.push('\\'), + Some((_, 'b')) => val.push('\u{8}'), + Some((_, 'f')) => val.push('\u{c}'), + Some((_, 'n')) => val.push('\n'), + Some((_, 'r')) => val.push('\r'), + Some((_, 't')) => val.push('\t'), + Some((i, c @ 'u')) | Some((i, c @ 'U')) => { + 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' { while let Some((_, ch)) = me.chars.clone().next() { match ch { - ' ' | '\t' | '\n' => { + ' ' | '\t' => { + me.chars.next(); + continue; + } + '\n' => { me.chars.next(); + break; } - _ => break, + _ => return Err(Error::InvalidEscape(i, c)), } } } - Some((i, c)) => return Err(Error::InvalidEscape(i, c)), - None => return Err(Error::UnterminatedString(start)), + while let Some((_, ch)) = me.chars.clone().next() { + match ch { + ' ' | '\t' | '\n' => { + me.chars.next(); + } + _ => break, + } + } } - Ok(()) - } - ch if '\u{20}' <= ch && ch <= '\u{10ffff}' && ch != '\u{7f}' => { - val.push(ch); - Ok(()) + Some((i, c)) => return Err(Error::InvalidEscape(i, c)), + None => return Err(Error::UnterminatedString(start)), } - _ => Err(Error::InvalidCharInString(i, ch)) + Ok(()) + } + 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> { while let Some((_, ch)) = self.peek_one() { if !is_keylike(ch) { - break + break; } self.one(); } @@ -441,8 +456,14 @@ impl<'a> Tokenizer<'a> { /// Calculate the span of a single character. fn step_span(&mut self, start: usize) -> Span { - let end = self.peek_one().map(|t| t.0).unwrap_or_else(|| self.input.len()); - Span { start: start, end: end } + let end = self + .peek_one() + .map(|t| t.0) + .unwrap_or_else(|| self.input.len()); + Span { + start: start, + end: end, + } } /// Peek one char without consuming it. @@ -465,7 +486,7 @@ impl<'a> Iterator for CrlfFold<'a> { let mut attempt = self.chars.clone(); if let Some((_, '\n')) = attempt.next() { self.chars = attempt; - return (i, '\n') + return (i, '\n'); } } (i, c) @@ -499,11 +520,11 @@ impl MaybeString { } fn is_keylike(ch: char) -> bool { - ('A' <= ch && ch <= 'Z') || - ('a' <= ch && ch <= 'z') || - ('0' <= ch && ch <= '9') || - ch == '-' || - ch == '_' + ('A' <= ch && ch <= 'Z') + || ('a' <= ch && ch <= 'z') + || ('0' <= ch && ch <= '9') + || ch == '-' + || ch == '_' } impl<'a> Token<'a> { @@ -520,7 +541,13 @@ impl<'a> Token<'a> { Token::LeftBrace => "a left brace", Token::RightBracket => "a right 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::Plus => "a plus", } @@ -529,8 +556,8 @@ impl<'a> Token<'a> { #[cfg(test)] mod tests { + use super::{Error, Token, Tokenizer}; use std::borrow::Cow; - use super::{Tokenizer, Token, Error}; fn err(input: &str, err: Error) { let mut t = Tokenizer::new(input); @@ -544,11 +571,14 @@ mod tests { fn t(input: &str, val: &str, multiline: bool) { let mut t = Tokenizer::new(input); let (_, token) = t.next().unwrap().unwrap(); - assert_eq!(token, Token::String { - src: input, - val: Cow::Borrowed(val), - multiline: multiline, - }); + assert_eq!( + token, + Token::String { + src: input, + val: Cow::Borrowed(val), + multiline: multiline, + } + ); assert!(t.next().unwrap().is_none()); } @@ -567,11 +597,14 @@ mod tests { fn t(input: &str, val: &str, multiline: bool) { let mut t = Tokenizer::new(input); let (_, token) = t.next().unwrap().unwrap(); - assert_eq!(token, Token::String { - src: input, - val: Cow::Borrowed(val), - multiline: multiline, - }); + assert_eq!( + token, + Token::String { + src: input, + val: Cow::Borrowed(val), + multiline: multiline, + } + ); assert!(t.next().unwrap().is_none()); } @@ -585,7 +618,11 @@ mod tests { t(r#""\U000A0000""#, "\u{A0000}", false); t(r#""\\t""#, "\\t", false); 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#""\n""#, "\n", false); t(r#""\b""#, "\u{8}", false); @@ -636,39 +673,45 @@ mod tests { assert_eq!(actual.len(), expected.len()); } - t(" a ", &[ - ((0, 1), Token::Whitespace(" "), " "), - ((1, 2), Token::Keylike("a"), "a"), - ((2, 3), Token::Whitespace(" "), " "), - ]); - - t(" a\t [[]] \t [] {} , . =\n# foo \r\n#foo \n ", &[ - ((0, 1), Token::Whitespace(" "), " "), - ((1, 2), Token::Keylike("a"), "a"), - ((2, 4), Token::Whitespace("\t "), "\t "), - ((4, 5), Token::LeftBracket, "["), - ((5, 6), Token::LeftBracket, "["), - ((6, 7), Token::RightBracket, "]"), - ((7, 8), Token::RightBracket, "]"), - ((8, 11), Token::Whitespace(" \t "), " \t "), - ((11, 12), Token::LeftBracket, "["), - ((12, 13), Token::RightBracket, "]"), - ((13, 14), Token::Whitespace(" "), " "), - ((14, 15), Token::LeftBrace, "{"), - ((15, 16), Token::RightBrace, "}"), - ((16, 17), Token::Whitespace(" "), " "), - ((17, 18), Token::Comma, ","), - ((18, 19), Token::Whitespace(" "), " "), - ((19, 20), Token::Period, "."), - ((20, 21), Token::Whitespace(" "), " "), - ((21, 22), Token::Equals, "="), - ((22, 23), Token::Newline, "\n"), - ((23, 29), Token::Comment("# foo "), "# foo "), - ((29, 31), Token::Newline, "\r\n"), - ((31, 36), Token::Comment("#foo "), "#foo "), - ((36, 37), Token::Newline, "\n"), - ((37, 38), Token::Whitespace(" "), " "), - ]); + t( + " a ", + &[ + ((0, 1), Token::Whitespace(" "), " "), + ((1, 2), Token::Keylike("a"), "a"), + ((2, 3), Token::Whitespace(" "), " "), + ], + ); + + t( + " a\t [[]] \t [] {} , . =\n# foo \r\n#foo \n ", + &[ + ((0, 1), Token::Whitespace(" "), " "), + ((1, 2), Token::Keylike("a"), "a"), + ((2, 4), Token::Whitespace("\t "), "\t "), + ((4, 5), Token::LeftBracket, "["), + ((5, 6), Token::LeftBracket, "["), + ((6, 7), Token::RightBracket, "]"), + ((7, 8), Token::RightBracket, "]"), + ((8, 11), Token::Whitespace(" \t "), " \t "), + ((11, 12), Token::LeftBracket, "["), + ((12, 13), Token::RightBracket, "]"), + ((13, 14), Token::Whitespace(" "), " "), + ((14, 15), Token::LeftBrace, "{"), + ((15, 16), Token::RightBrace, "}"), + ((16, 17), Token::Whitespace(" "), " "), + ((17, 18), Token::Comma, ","), + ((18, 19), Token::Whitespace(" "), " "), + ((19, 20), Token::Period, "."), + ((20, 21), Token::Whitespace(" "), " "), + ((21, 22), Token::Equals, "="), + ((22, 23), Token::Newline, "\n"), + ((23, 29), Token::Comment("# foo "), "# foo "), + ((29, 31), Token::Newline, "\r\n"), + ((31, 36), Token::Comment("#foo "), "#foo "), + ((36, 37), Token::Newline, "\n"), + ((37, 38), Token::Whitespace(" "), " "), + ], + ); } #[test] diff --git a/src/value.rs b/src/value.rs index 2e42dc3..ee952b6 100644 --- a/src/value.rs +++ b/src/value.rs @@ -1,18 +1,18 @@ //! Definition of a TOML value use std::collections::{BTreeMap, HashMap}; -use std::hash::Hash; use std::fmt; +use std::hash::Hash; use std::ops; use std::str::FromStr; use std::vec; -use serde::ser; use serde::de; use serde::de::IntoDeserializer; +use serde::ser; -pub use datetime::{Datetime, DatetimeParseError}; use datetime::{self, DatetimeFromString}; +pub use datetime::{Datetime, DatetimeParseError}; /// Representation of a TOML value. #[derive(PartialEq, Clone, Debug)] @@ -46,7 +46,8 @@ impl Value { /// This conversion can fail if `T`'s implementation of `Serialize` decides to /// fail, or if `T` contains a map with non-string keys. pub fn try_from(value: T) -> Result - where T: ser::Serialize, + where + T: ser::Serialize, { 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 /// primitive type. pub fn try_into<'de, T>(self) -> Result - where T: de::Deserialize<'de>, + where + T: de::Deserialize<'de>, { de::Deserialize::deserialize(self) } @@ -92,7 +94,10 @@ impl Value { /// Extracts the integer value if it is an integer. pub fn as_integer(&self) -> Option { - match *self { Value::Integer(i) => Some(i), _ => None } + match *self { + Value::Integer(i) => Some(i), + _ => None, + } } /// Tests whether this value is an integer. @@ -102,7 +107,10 @@ impl Value { /// Extracts the float value if it is a float. pub fn as_float(&self) -> Option { - match *self { Value::Float(f) => Some(f), _ => None } + match *self { + Value::Float(f) => Some(f), + _ => None, + } } /// Tests whether this value is a float. @@ -112,7 +120,10 @@ impl Value { /// Extracts the boolean value if it is a boolean. pub fn as_bool(&self) -> Option { - match *self { Value::Boolean(b) => Some(b), _ => None } + match *self { + Value::Boolean(b) => Some(b), + _ => None, + } } /// Tests whether this value is a boolean. @@ -122,7 +133,10 @@ impl Value { /// Extracts the string of this value if it is a string. 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. @@ -139,7 +153,10 @@ impl Value { /// 1979-05-27T07:32:00Z /// ``` 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. @@ -149,12 +166,18 @@ impl Value { /// Extracts the array value if it is an array. pub fn as_array(&self) -> Option<&Vec> { - 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. pub fn as_array_mut(&mut self) -> Option<&mut Vec> { - 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. @@ -164,12 +187,18 @@ impl Value { /// Extracts the table value if it is a 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. 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. @@ -180,13 +209,13 @@ impl Value { /// Tests whether this and another value have the same type. 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, + (&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, } @@ -206,7 +235,10 @@ impl Value { } } -impl ops::Index for Value where I: Index { +impl ops::Index for Value +where + I: Index, +{ type Output = Value; fn index(&self, index: I) -> &Value { @@ -214,7 +246,10 @@ impl ops::Index for Value where I: Index { } } -impl ops::IndexMut for Value where I: Index { +impl ops::IndexMut for Value +where + I: Index, +{ fn index_mut(&mut self, index: I) -> &mut Value { self.get_mut(index).expect("index not found") } @@ -235,9 +270,7 @@ impl> From> for Value { impl, V: Into> From> for Value { fn from(val: BTreeMap) -> Value { - let table = val.into_iter() - .map(|(s, v)| (s.into(), v.into())) - .collect(); + let table = val.into_iter().map(|(s, v)| (s.into(), v.into())).collect(); Value::Table(table) } @@ -245,9 +278,7 @@ impl, V: Into> From> for Value { impl + Hash + Eq, V: Into> From> for Value { fn from(val: HashMap) -> Value { - let table = val.into_iter() - .map(|(s, v)| (s.into(), v.into())) - .collect(); + let table = val.into_iter().map(|(s, v)| (s.into(), v.into())).collect(); Value::Table(table) } @@ -261,7 +292,7 @@ macro_rules! impl_into_value { Value::$variant(val.into()) } } - } + }; } 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> { (**self).index(val) } @@ -352,7 +386,9 @@ impl<'s, T: ?Sized> Index for &'s T where T: Index { impl fmt::Display for Value { 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 { fn serialize(&self, serializer: S) -> Result - where S: ser::Serializer + where + S: ser::Serializer, { use serde::ser::SerializeMap; @@ -381,13 +418,20 @@ impl ser::Serialize for Value { // Be sure to visit non-tables first (and also non // array-of-tables) as all keys must be emitted first. for (k, v) in t { - if !v.is_table() && !v.is_array() || - (v.as_array().map(|a| !a.iter().any(|v| v.is_table())).unwrap_or(false)) { + if !v.is_table() && !v.is_array() + || (v + .as_array() + .map(|a| !a.iter().any(|v| v.is_table())) + .unwrap_or(false)) + { map.serialize_entry(k, v)?; } } 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)?; } } @@ -404,7 +448,8 @@ impl ser::Serialize for Value { impl<'de> de::Deserialize<'de> for Value { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de>, + where + D: de::Deserializer<'de>, { struct ValueVisitor; @@ -452,13 +497,15 @@ impl<'de> de::Deserialize<'de> for Value { } fn visit_some(self, deserializer: D) -> Result - where D: de::Deserializer<'de>, + where + D: de::Deserializer<'de>, { de::Deserialize::deserialize(deserializer) } fn visit_seq(self, mut visitor: V) -> Result - where V: de::SeqAccess<'de>, + where + V: de::SeqAccess<'de>, { let mut vec = Vec::new(); while let Some(elem) = visitor.next_element()? { @@ -468,16 +515,15 @@ impl<'de> de::Deserialize<'de> for Value { } fn visit_map(self, mut visitor: V) -> Result - where V: de::MapAccess<'de>, + where + V: de::MapAccess<'de>, { let mut key = String::new(); - let datetime = visitor.next_key_seed(DatetimeOrTable { - key: &mut key, - })?; + let datetime = visitor.next_key_seed(DatetimeOrTable { key: &mut key })?; match datetime { Some(true) => { 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())), Some(false) => {} @@ -487,7 +533,7 @@ impl<'de> de::Deserialize<'de> for Value { while let Some(key) = visitor.next_key()? { if map.contains_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()?); } @@ -503,7 +549,8 @@ impl<'de> de::Deserializer<'de> for Value { type Error = ::de::Error; fn deserialize_any(self, visitor: V) -> Result - where V: de::Visitor<'de>, + where + V: de::Visitor<'de>, { match self { Value::Boolean(v) => visitor.visit_bool(v), @@ -548,14 +595,18 @@ impl<'de> de::Deserializer<'de> for Value { { match self { 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` // as a present field. fn deserialize_option(self, visitor: V) -> Result - where V: de::Visitor<'de>, + where + V: de::Visitor<'de>, { visitor.visit_some(self) } @@ -563,9 +614,10 @@ impl<'de> de::Deserializer<'de> for Value { fn deserialize_newtype_struct( self, _name: &'static str, - visitor: V + visitor: V, ) -> Result - where V: de::Visitor<'de> + where + V: de::Visitor<'de>, { visitor.visit_newtype_struct(self) } @@ -592,9 +644,9 @@ impl SeqDeserializer { impl<'de> de::SeqAccess<'de> for SeqDeserializer { type Error = ::de::Error; - fn next_element_seed(&mut self, seed: T) - -> Result, ::de::Error> - where T: de::DeserializeSeed<'de>, + fn next_element_seed(&mut self, seed: T) -> Result, ::de::Error> + where + T: de::DeserializeSeed<'de>, { match self.iter.next() { Some(value) => seed.deserialize(value).map(Some), @@ -628,7 +680,8 @@ impl<'de> de::MapAccess<'de> for MapDeserializer { type Error = ::de::Error; fn next_key_seed(&mut self, seed: T) -> Result, ::de::Error> - where T: de::DeserializeSeed<'de>, + where + T: de::DeserializeSeed<'de>, { match self.iter.next() { Some((key, value)) => { @@ -640,7 +693,8 @@ impl<'de> de::MapAccess<'de> for MapDeserializer { } fn next_value_seed(&mut self, seed: T) -> Result - where T: de::DeserializeSeed<'de>, + where + T: de::DeserializeSeed<'de>, { let (key, res) = match self.value.take() { Some((key, value)) => (key, seed.deserialize(value)), @@ -749,35 +803,39 @@ impl ser::Serializer for Serializer { Err(::ser::Error::UnsupportedType) } - fn serialize_unit_struct(self, _name: &'static str) - -> Result { + fn serialize_unit_struct(self, _name: &'static str) -> Result { Err(::ser::Error::UnsupportedType) } - fn serialize_unit_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str) - -> Result { + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + ) -> Result { self.serialize_str(_variant) } - fn serialize_newtype_struct(self, - _name: &'static str, - value: &T) - -> Result - where T: ser::Serialize, + fn serialize_newtype_struct( + self, + _name: &'static str, + value: &T, + ) -> Result + where + T: ser::Serialize, { value.serialize(self) } - fn serialize_newtype_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _value: &T) - -> Result - where T: ser::Serialize, + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T, + ) -> Result + where + T: ser::Serialize, { Err(::ser::Error::UnsupportedType) } @@ -787,16 +845,15 @@ impl ser::Serializer for Serializer { } fn serialize_some(self, value: &T) -> Result - where T: ser::Serialize, + where + T: ser::Serialize, { value.serialize(self) } - fn serialize_seq(self, len: Option) - -> Result - { + fn serialize_seq(self, len: Option) -> Result { 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)) } - fn serialize_tuple_struct(self, _name: &'static str, len: usize) - -> Result { + fn serialize_tuple_struct( + self, + _name: &'static str, + len: usize, + ) -> Result { self.serialize_seq(Some(len)) } - fn serialize_tuple_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - len: usize) - -> Result - { + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + len: usize, + ) -> Result { self.serialize_seq(Some(len)) } - fn serialize_map(self, _len: Option) - -> Result - { + fn serialize_map(self, _len: Option) -> Result { Ok(SerializeMap { map: BTreeMap::new(), next_key: None, }) } - fn serialize_struct(self, _name: &'static str, len: usize) - -> Result { + fn serialize_struct( + self, + _name: &'static str, + len: usize, + ) -> Result { self.serialize_map(Some(len)) } - fn serialize_struct_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result - { + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { Err(::ser::Error::UnsupportedType) } } @@ -858,7 +919,8 @@ impl ser::SerializeSeq for SerializeVec { type Error = ::ser::Error; fn serialize_element(&mut self, value: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize + where + T: ser::Serialize, { self.vec.push(Value::try_from(value)?); Ok(()) @@ -874,7 +936,8 @@ impl ser::SerializeTuple for SerializeVec { type Error = ::ser::Error; fn serialize_element(&mut self, value: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize + where + T: ser::Serialize, { ser::SerializeSeq::serialize_element(self, value) } @@ -889,7 +952,8 @@ impl ser::SerializeTupleStruct for SerializeVec { type Error = ::ser::Error; fn serialize_field(&mut self, value: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize + where + T: ser::Serialize, { ser::SerializeSeq::serialize_element(self, value) } @@ -904,7 +968,8 @@ impl ser::SerializeTupleVariant for SerializeVec { type Error = ::ser::Error; fn serialize_field(&mut self, value: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize + where + T: ser::Serialize, { ser::SerializeSeq::serialize_element(self, value) } @@ -919,7 +984,8 @@ impl ser::SerializeMap for SerializeMap { type Error = ::ser::Error; fn serialize_key(&mut self, key: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize + where + T: ser::Serialize, { match Value::try_from(key)? { Value::String(s) => self.next_key = Some(s), @@ -929,12 +995,15 @@ impl ser::SerializeMap for SerializeMap { } fn serialize_value(&mut self, value: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize + where + T: ser::Serialize, { let key = self.next_key.take(); let key = key.expect("serialize_value called before serialize_key"); match Value::try_from(value) { - Ok(value) => { self.map.insert(key, value); } + Ok(value) => { + self.map.insert(key, value); + } Err(::ser::Error::UnsupportedNone) => {} Err(e) => return Err(e), } @@ -950,8 +1019,13 @@ impl ser::SerializeStruct for SerializeMap { type Ok = Value; type Error = ::ser::Error; - fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize + fn serialize_field( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), ::ser::Error> + where + T: ser::Serialize, { ser::SerializeMap::serialize_key(self, key)?; ser::SerializeMap::serialize_value(self, value) @@ -970,7 +1044,8 @@ impl<'a, 'de> de::DeserializeSeed<'de> for DatetimeOrTable<'a> { type Value = bool; fn deserialize(self, deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { deserializer.deserialize_any(self) } @@ -984,7 +1059,8 @@ impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> { } fn visit_str(self, s: &str) -> Result - where E: de::Error, + where + E: de::Error, { if s == datetime::FIELD { Ok(true) @@ -995,7 +1071,8 @@ impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> { } fn visit_string(self, s: String) -> Result - where E: de::Error, + where + E: de::Error, { if s == datetime::FIELD { Ok(true) -- cgit v1.2.3