diff options
author | Sam Scott <sam.scott89@gmail.com> | 2017-11-09 16:28:07 +0000 |
---|---|---|
committer | Sam Scott <sam.scott89@gmail.com> | 2017-11-09 16:40:24 +0000 |
commit | 61ccfb416e553301d9db604d0986d184796b0280 (patch) | |
tree | 767bc2cfe83e439f5cd973c8088aa7de68203fb9 /src/de | |
parent | d74354b1eaccfb6ea264fca81f3dd936afdff44f (diff) |
Let rustfmt do its thing.
Diffstat (limited to 'src/de')
-rw-r--r-- | src/de/mod.rs | 210 | ||||
-rw-r--r-- | src/de/parse.rs | 145 |
2 files changed, 169 insertions, 186 deletions
diff --git a/src/de/mod.rs b/src/de/mod.rs index c28c459..5d8115a 100644 --- a/src/de/mod.rs +++ b/src/de/mod.rs @@ -16,7 +16,7 @@ //! order. //! //! The `parse` module handles this step of deserializing a querystring into the -//! map structure. This uses `rust_url::percent_encoding` to handle +//! map structure. This uses `rust_url::percent_encoding` to handle //! first converting the string. //! //! From here, there are two main `Deserializer` objects: `QsDeserializer` and @@ -101,8 +101,8 @@ impl Config { /// Create a new `Config` with the specified `max_depth` and `strict` mode. pub fn new(max_depth: usize, strict: bool) -> Self { Self { - max_depth, - strict + max_depth: max_depth, + strict: strict, } } @@ -115,9 +115,8 @@ impl Config { impl Config { /// Deserializes a querystring from a `&[u8]` using this `Config`. pub fn deserialize_bytes<'de, T: de::Deserialize<'de>>(&self, - input: &'de [u8]) - -> Result<T> - { + input: &'de [u8]) + -> Result<T> { T::deserialize(QsDeserializer::with_config(self, input)?) } @@ -132,8 +131,8 @@ impl Config { /// Deserializes a querystring from a `&str` using this `Config`. pub fn deserialize_str<'de, T: de::Deserialize<'de>>(&self, - input: &'de str) - -> Result<T> { + input: &'de str) + -> Result<T> { self.deserialize_bytes(input.as_bytes()) } } @@ -225,7 +224,8 @@ impl<'a> QsDeserializer<'a> { /// Returns a new `QsDeserializer<'a>`. fn with_config(config: &Config, input: &'a [u8]) -> Result<Self> { - parse::Parser::new(input, config.max_depth(), config.strict).as_deserializer() + parse::Parser::new(input, config.max_depth(), config.strict) + .as_deserializer() } } @@ -263,12 +263,11 @@ impl<'de> de::Deserializer<'de> for QsDeserializer<'de> { Err(Error::top_level("sequence")) } - fn deserialize_newtype_struct<V>( - self, - _name: &'static str, - visitor: V - ) -> Result<V::Value> - where V: de::Visitor<'de> + fn deserialize_newtype_struct<V>(self, + _name: &'static str, + visitor: V) + -> Result<V::Value> + where V: de::Visitor<'de>, { self.deserialize_map(visitor) } @@ -276,12 +275,8 @@ impl<'de> de::Deserializer<'de> for QsDeserializer<'de> { /// Throws an error. /// /// Tuples are not supported at the top level. - fn deserialize_tuple<V>( - self, - _len: usize, - _visitor: V - ) -> Result<V::Value> - where V: de::Visitor<'de> + fn deserialize_tuple<V>(self, _len: usize, _visitor: V) -> Result<V::Value> + where V: de::Visitor<'de>, { Err(Error::top_level("tuple")) @@ -290,24 +285,22 @@ impl<'de> de::Deserializer<'de> for QsDeserializer<'de> { /// Throws an error. /// /// TupleStructs are not supported at the top level. - fn deserialize_tuple_struct<V>( - self, - _name: &'static str, - _len: usize, - _visitor: V - ) -> Result<V::Value> - where V: de::Visitor<'de> + fn deserialize_tuple_struct<V>(self, + _name: &'static str, + _len: usize, + _visitor: V) + -> Result<V::Value> + where V: de::Visitor<'de>, { Err(Error::top_level("tuple struct")) } - fn deserialize_enum<V>( - self, - _name: &'static str, - _variants: &'static [&'static str], - visitor: V - ) -> Result<V::Value> - where V: de::Visitor<'de> + fn deserialize_enum<V>(self, + _name: &'static str, + _variants: &'static [&'static str], + visitor: V) + -> Result<V::Value> + where V: de::Visitor<'de>, { visitor.visit_enum(self) } @@ -367,7 +360,7 @@ impl<'de> de::EnumAccess<'de> for QsDeserializer<'de> { type Variant = Self; fn variant_seed<V>(mut self, seed: V) -> Result<(V::Value, Self::Variant)> - where V: de::DeserializeSeed<'de> + where V: de::DeserializeSeed<'de>, { if let Some((key, value)) = self.iter.next() { self.value = Some(value); @@ -385,8 +378,7 @@ impl<'de> de::VariantAccess<'de> for QsDeserializer<'de> { } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> - where - T: de::DeserializeSeed<'de> + where T: de::DeserializeSeed<'de>, { if let Some(value) = self.value { seed.deserialize(LevelDeserializer(value)) @@ -395,13 +387,8 @@ impl<'de> de::VariantAccess<'de> for QsDeserializer<'de> { } } - fn tuple_variant<V>( - self, - _len: usize, - visitor: V - ) -> Result<V::Value> - where - V: de::Visitor<'de> + fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> + where V: de::Visitor<'de>, { if let Some(value) = self.value { de::Deserializer::deserialize_seq(LevelDeserializer(value), visitor) @@ -409,13 +396,11 @@ impl<'de> de::VariantAccess<'de> for QsDeserializer<'de> { Err(de::Error::custom("no value to deserialize")) } } - fn struct_variant<V>( - self, - _fields: &'static [&'static str], - visitor: V - ) -> Result<V::Value> - where - V: de::Visitor<'de> + fn struct_variant<V>(self, + _fields: &'static [&'static str], + visitor: V) + -> Result<V::Value> + where V: de::Visitor<'de>, { if let Some(value) = self.value { de::Deserializer::deserialize_map(LevelDeserializer(value), visitor) @@ -430,16 +415,19 @@ impl<'de> de::EnumAccess<'de> for LevelDeserializer<'de> { type Variant = Self; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant)> - where V: de::DeserializeSeed<'de> + where V: de::DeserializeSeed<'de>, { match self.0 { Level::Flat(x) => { Ok((seed.deserialize(ParsableStringDeserializer(x))?, - LevelDeserializer(Level::Invalid("this value can only deserialize to a UnitVariant")))) + LevelDeserializer(Level::Invalid("this value can only \ + deserialize to a \ + UnitVariant")))) }, _ => { - Err(de::Error::custom("this value can only deserialize to a UnitVariant")) - } + Err(de::Error::custom("this value can only deserialize to a \ + UnitVariant")) + }, } } } @@ -451,41 +439,35 @@ impl<'de> de::VariantAccess<'de> for LevelDeserializer<'de> { } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> - where - T: de::DeserializeSeed<'de> + where T: de::DeserializeSeed<'de>, { seed.deserialize(self) } - fn tuple_variant<V>( - self, - _len: usize, - visitor: V - ) -> Result<V::Value> - where - V: de::Visitor<'de> + fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> + where V: de::Visitor<'de>, { de::Deserializer::deserialize_seq(self, visitor) } - fn struct_variant<V>( - self, - _fields: &'static [&'static str], - visitor: V - ) -> Result<V::Value> - where - V: de::Visitor<'de> + fn struct_variant<V>(self, + _fields: &'static [&'static str], + visitor: V) + -> Result<V::Value> + where V: de::Visitor<'de>, { de::Deserializer::deserialize_map(self, visitor) } } -struct LevelSeq<'a, I: Iterator<Item=Level<'a>>>(I); +struct LevelSeq<'a, I: Iterator<Item = Level<'a>>>(I); -impl<'de, I: Iterator<Item=Level<'de>>> de::SeqAccess<'de> for LevelSeq<'de, I> { +impl<'de, I: Iterator<Item = Level<'de>>> de::SeqAccess<'de> + for + LevelSeq<'de, I> { type Error = Error; fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> - where T: de::DeserializeSeed<'de> + where T: de::DeserializeSeed<'de>, { if let Some(v) = self.0.next() { seed.deserialize(LevelDeserializer(v)).map(Some) @@ -534,14 +516,12 @@ macro_rules! deserialize_primitive { impl<'a> LevelDeserializer<'a> { fn into_deserializer(self) -> Result<QsDeserializer<'a>> { match self.0 { - Level::Nested(map) => { - Ok(QsDeserializer::with_map(map)) - }, - Level::Invalid(e) => { - Err(de::Error::custom(e)) - }, + Level::Nested(map) => Ok(QsDeserializer::with_map(map)), + Level::Invalid(e) => Err(de::Error::custom(e)), l => { - Err(de::Error::custom(format!("could not convert {:?} to QsDeserializer<'a>", l))) + Err(de::Error::custom(format!("could not convert {:?} to \ + QsDeserializer<'a>", + l))) }, } } @@ -569,12 +549,11 @@ impl<'de> de::Deserializer<'de> for LevelDeserializer<'de> { Cow::Borrowed(s) => visitor.visit_borrowed_str(s), } }, - Level::Invalid(e) => { - Err(de::Error::custom(e)) - }, + Level::Invalid(e) => Err(de::Error::custom(e)), Level::Uninitialised => { - Err(de::Error::custom("attempted to deserialize unitialised value")) - } + Err(de::Error::custom("attempted to deserialize unitialised \ + value")) + }, } } @@ -582,42 +561,37 @@ impl<'de> de::Deserializer<'de> for LevelDeserializer<'de> { where V: de::Visitor<'de>, { match self.0 { - Level::Flat(ref x) if x == "" => { - visitor.visit_none() - }, - _ => { - visitor.visit_some(self) - }, + Level::Flat(ref x) if x == "" => visitor.visit_none(), + _ => visitor.visit_some(self), } } - fn deserialize_enum<V>( - self, - name: &'static str, - variants: &'static [&'static str], - visitor: V - ) -> Result<V::Value> - where V: de::Visitor<'de> + fn deserialize_enum<V>(self, + name: &'static str, + variants: &'static [&'static str], + visitor: V) + -> Result<V::Value> + where V: de::Visitor<'de>, { match self.0 { Level::Nested(map) => { - QsDeserializer::with_map(map).deserialize_enum(name, variants, visitor) - }, - Level::Flat(_) => { - visitor.visit_enum(self) + QsDeserializer::with_map(map) + .deserialize_enum(name, variants, visitor) }, + Level::Flat(_) => visitor.visit_enum(self), x => { - Err(de::Error::custom(format!("{:?} does not appear to be an enum", x))) + Err(de::Error::custom(format!("{:?} does not appear to be \ + an enum", + x))) }, } } - fn deserialize_newtype_struct<V>( - self, - _name: &'static str, - visitor: V - ) -> Result<V::Value> - where V: de::Visitor<'de> + fn deserialize_newtype_struct<V>(self, + _name: &'static str, + visitor: V) + -> Result<V::Value> + where V: de::Visitor<'de>, { match self.0 { Level::Nested(_) => { @@ -630,26 +604,25 @@ impl<'de> de::Deserializer<'de> for LevelDeserializer<'de> { visitor.visit_seq(LevelSeq(seq.into_iter())) }, Level::Flat(_) => { - // For a newtype_struct, attempt to deserialize a flat value as a + // For a newtype_struct, attempt to deserialize a flat value as a // single element sequence. visitor.visit_seq(LevelSeq(vec![self.0].into_iter())) }, - Level::Invalid(e) => { - Err(de::Error::custom(e)) - }, + Level::Invalid(e) => Err(de::Error::custom(e)), Level::Uninitialised => { - Err(de::Error::custom("attempted to deserialize unitialised value")) + Err(de::Error::custom("attempted to deserialize unitialised \ + value")) }, } } deserialize_primitive!(bool, deserialize_bool, visit_bool); - deserialize_primitive!(i8, deserialize_i8, visit_i8); + deserialize_primitive!(i8, deserialize_i8, visit_i8); deserialize_primitive!(i16, deserialize_i16, visit_i16); deserialize_primitive!(i32, deserialize_i32, visit_i32); deserialize_primitive!(i64, deserialize_i64, visit_i64); - deserialize_primitive!(u8, deserialize_u8, visit_u8); + deserialize_primitive!(u8, deserialize_u8, visit_u8); deserialize_primitive!(u16, deserialize_u16, visit_u16); deserialize_primitive!(u32, deserialize_u32, visit_u32); deserialize_primitive!(u64, deserialize_u64, visit_u64); @@ -736,5 +709,4 @@ impl<'de> de::Deserializer<'de> for ParsableStringDeserializer<'de> { f32 => deserialize_f32, f64 => deserialize_f64, } - } diff --git a/src/de/parse.rs b/src/de/parse.rs index 3b39c46..1c13aaf 100644 --- a/src/de/parse.rs +++ b/src/de/parse.rs @@ -1,3 +1,5 @@ +use super::*; + use percent_encoding; use serde::de; @@ -6,8 +8,6 @@ use std::iter::Iterator; use std::slice::Iter; use std::str; -use super::*; - macro_rules! tu { ($x:expr) => ( @@ -29,19 +29,21 @@ impl<'a> Level<'a> { match map.entry(key) { Entry::Occupied(mut o) => { // Throw away old result; map is now invalid anyway. - let _ = o.insert(Level::Invalid("Multiple values for one key")); + let _ = + o.insert(Level::Invalid("Multiple values for one key")); }, Entry::Vacant(vm) => { // Map is empty, result is None let _ = vm.insert(Level::Flat(value)); }, } - } else if let Level::Uninitialised = *self { + } else if let Level::Uninitialised = *self { let mut map = BTreeMap::default(); let _ = map.insert(key, Level::Flat(value)); *self = Level::Nested(map); } else { - *self = Level::Invalid("Attempted to insert map value into non-map structure"); + *self = Level::Invalid("Attempted to insert map value into \ + non-map structure"); } } @@ -51,20 +53,22 @@ impl<'a> Level<'a> { match map.entry(key) { Entry::Occupied(mut o) => { // Throw away old result; map is now invalid anyway. - let _ = o.insert(Level::Invalid("Multiple values for one key")); + let _ = + o.insert(Level::Invalid("Multiple values for one key")); }, Entry::Vacant(vm) => { // Map is empty, result is None let _ = vm.insert(Level::Flat(value)); }, } - } else if let Level::Uninitialised = *self { + } else if let Level::Uninitialised = *self { // To reach here, self is either an OrderedSeq or nothing. let mut map = BTreeMap::default(); let _ = map.insert(key, Level::Flat(value)); *self = Level::OrderedSeq(map); } else { - *self = Level::Invalid("Attempted to insert seq value into non-seq structure"); + *self = Level::Invalid("Attempted to insert seq value into \ + non-seq structure"); } } @@ -81,7 +85,8 @@ impl<'a> Level<'a> { seq.push(Level::Flat(value)); *self = Level::Sequence(seq); } else { - *self = Level::Invalid("Attempted to insert seq value into non-seq structure"); + *self = Level::Invalid("Attempted to insert seq value into \ + non-seq structure"); } } } @@ -113,10 +118,10 @@ impl<'a> Iterator for Parser<'a> { self.index += 1; self.acc.1 += 1; self.iter.next() - } + }, } } else { - // in non-strict mode, we will happily decode any bracket + // in non-strict mode, we will happily decode any bracket match self.peeked.take() { Some(v) => Some(v), None => { @@ -139,15 +144,13 @@ impl<'a> Iterator for Parser<'a> { self.index += 2; Some(&b']') }, - _ => { - Some(v) - } + _ => Some(v), } - } + }, Some(v) => Some(v), None => None, } - } + }, } } } @@ -180,8 +183,9 @@ fn replace_plus(input: Cow<str>) -> Cow<str> { *byte = b' '; } } - Cow::Owned(String::from_utf8(replaced).expect("replacing '+' with ' ' cannot panic")) - } + Cow::Owned(String::from_utf8(replaced) + .expect("replacing '+' with ' ' cannot panic")) + }, } } @@ -193,8 +197,8 @@ impl<'a> Parser<'a> { acc: (0, 0), index: 0, peeked: None, - depth, - strict, + depth: depth, + strict: strict, } } @@ -204,11 +208,13 @@ impl<'a> Parser<'a> { } /// Extracts a string from the internal byte slice from the range tracked by - /// the parser. + /// the parser. /// Avoids allocations when neither percent encoded, nor `'+'` values are /// present. fn collect_str(&mut self) -> Result<Cow<'a, str>> { - let res: Cow<'a, str> = percent_encoding::percent_decode(&self.inner[self.acc.0..self.acc.1 - 1]).decode_utf8()?; + let res: Cow<'a, str> = + percent_encoding::percent_decode(&self.inner[self.acc.0.. + self.acc.1 - 1]).decode_utf8()?; let res: Result<Cow<'a, str>> = Ok(replace_plus(res)); self.clear_acc(); res.map_err(Error::from) @@ -221,11 +227,11 @@ impl<'a> Parser<'a> { let mut root = Level::Nested(map); // Parses all top level nodes into the `root` map. - while self.parse(&mut root)? { } + while self.parse(&mut root)? {} let iter = match root { Level::Nested(map) => map.into_iter(), - _ => BTreeMap::default().into_iter() + _ => BTreeMap::default().into_iter(), }; Ok(QsDeserializer { iter: iter, @@ -258,7 +264,7 @@ impl<'a> Parser<'a> { b'[' => { // If we're in strict mode, error, otherwise just ignore it. if self.strict { - return Err(super::Error::parse_err("found another opening bracket before the closed bracket", self.index)) + return Err(super::Error::parse_err("found another opening bracket before the closed bracket", self.index)); } else { let _ = self.next(); } @@ -277,16 +283,17 @@ impl<'a> Parser<'a> { let key = usize::from_str_radix(&key, 10).map_err(Error::from)?; self.parse_ord_seq_value(key, node)?; return Ok(true); - } + }, // Key is "[a..." so parse up to the closing "]" - 0x20...0x2f | 0x3a...0x5a | 0x5c | 0x5e...0x7e => { + 0x20...0x2f | 0x3a...0x5a | 0x5c | + 0x5e...0x7e => { let key = self.parse_key(b']', true)?; self.parse_map_value(key, node)?; return Ok(true); }, c => { if self.strict { - return Err(super::Error::parse_err(&format!("unexpected character: {}", String::from_utf8_lossy(&[c])), self.index)) + return Err(super::Error::parse_err(&format!("unexpected character: {}", String::from_utf8_lossy(&[c])), self.index)); } else { let _ = self.next(); } @@ -319,14 +326,11 @@ impl<'a> Parser<'a> { /// or `']'` when the key is a nested key. In the former case, `'='` will /// also finish the key parsing. /// - /// The `consume` flag determines whether the end character should be + /// The `consume` flag determines whether the end character should be /// returned to the buffer to be peeked. This is important when - /// parsing keys like `abc[def][ghi]` since the `'['` character is + /// parsing keys like `abc[def][ghi]` since the `'['` character is /// needed to for the next iteration of `parse`. - fn parse_key(&mut self, - end_on: u8, - consume: bool) - -> Result<Cow<'a, str>> { + fn parse_key(&mut self, end_on: u8, consume: bool) -> Result<Cow<'a, str>> { loop { if let Some(x) = self.next() { match *x { @@ -401,22 +405,22 @@ impl<'a> Parser<'a> { // Either take the existing entry, or add a new // unitialised level // Use this new node to keep parsing - let _ = self.parse( - map.entry(key).or_insert(Level::Uninitialised) - )?; + let _ = self.parse(map.entry(key) + .or_insert(Level::Uninitialised))?; break Ok(()); } else { // We expected to parse into a map here. break Err(super::Error::parse_err(&format!("tried to insert a \ new key into {:?}", - node), self.index)); + node), + self.index)); } }, c => { // Anything else is unexpected since we just finished // parsing a key. if self.strict { - break Err(super::Error::parse_err(format!("Unexpected character: '{}' found when parsing", String::from_utf8_lossy(&[c])), self.index)) + break Err(super::Error::parse_err(format!("Unexpected character: '{}' found when parsing", String::from_utf8_lossy(&[c])), self.index)); } else { let _ = self.next(); } @@ -429,7 +433,7 @@ impl<'a> Parser<'a> { } }; // We have finished parsing this level, so go back up a level. - self.depth +=1; + self.depth += 1; res } @@ -437,7 +441,10 @@ impl<'a> Parser<'a> { /// ordered sequence. /// Basically the same as the above, but we insert into `OrderedSeq` /// Can potentially be merged? - fn parse_ord_seq_value(&mut self, key: usize, node: &mut Level<'a>) -> Result<()> { + fn parse_ord_seq_value(&mut self, + key: usize, + node: &mut Level<'a>) + -> Result<()> { let res = loop { if let Some(x) = self.peek() { match *x { @@ -448,12 +455,12 @@ impl<'a> Parser<'a> { let value = self.collect_str()?; // Reached the end of the key string node.insert_ord_seq_value(key, value); - break Ok(()) + break Ok(()); }, b'&' => { // No value node.insert_ord_seq_value(key, Cow::Borrowed("")); - break Ok(()) + break Ok(()); }, b'[' => { // The key continues to another level of nested. @@ -469,19 +476,22 @@ impl<'a> Parser<'a> { // unitialised level // Use this new node to keep parsing map.entry(key).or_insert(Level::Uninitialised))?; - break Ok(()) + break Ok(()); } else { // We expected to parse into a seq here. break Err(super::Error::parse_err(&format!("tried to insert a \ new key into {:?}", - node), self.index)) + node), + self.index)); } }, c => { // Anything else is unexpected since we just finished // parsing a key. if self.strict { - break Err(super::Error::parse_err(format!("Unexpected character: {:?} found when parsing", c), self.index)) + break Err(super::Error::parse_err(format!("Unexpected character: {:?} found when parsing", + c), + self.index)); } else { let _ = self.next(); } @@ -490,7 +500,7 @@ impl<'a> Parser<'a> { } else { // The string has ended, so the value is empty. node.insert_ord_seq_value(key, Cow::Borrowed("")); - break Ok(()) + break Ok(()); } }; // We have finished parsing this level, so go back up a level. @@ -503,35 +513,36 @@ impl<'a> Parser<'a> { /// This must be the final level of nesting, so assume we have a value fn parse_seq_value(&mut self, node: &mut Level<'a>) -> Result<()> { let res = match self.peek() { - Some(x) => match *x { - b'=' => { - // Key is finished, parse up until the '&' as the value - self.clear_acc(); - for _ in self.take_while(|b| *b != &b'&') {} - let value = self.collect_str()?; - node.insert_seq_value(value); - Ok(()) - }, - b'&' => { - // key value is empty - node.insert_seq_value(Cow::Borrowed("")); - Ok(()) + Some(x) => { + match *x { + b'=' => { + // Key is finished, parse up until the '&' as the value + self.clear_acc(); + for _ in self.take_while(|b| *b != &b'&') {} + let value = self.collect_str()?; + node.insert_seq_value(value); + Ok(()) + }, + b'&' => { + // key value is empty + node.insert_seq_value(Cow::Borrowed("")); + Ok(()) + }, + _ => { + Err(super::Error::parse_err("non-indexed sequence of \ + structs not supported", + self.index)) + }, } - _ => { - Err(super::Error::parse_err("non-indexed sequence of structs not \ - supported", self.index)) - }, }, None => { // The string has ended, so the value is empty. node.insert_seq_value(Cow::Borrowed("")); Ok(()) - } + }, }; // We have finished parsing this level, so go back up a level. self.depth += 1; res } - - } |