diff options
| author | bors <bors@rust-lang.org> | 2019-12-23 02:47:52 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2019-12-23 02:47:52 +0000 |
| commit | a916ac22b9f7f1f0f7aba0a41a789b3ecd765018 (patch) | |
| tree | 139cba4184f0f290fdbdff1aa0aa68352b16ccbb /src/libserialize | |
| parent | 9b98af84c4aa66392236fff59c86da2130d46d46 (diff) | |
| parent | 0f24ccd21d9f734a21daaf3566900127167556d1 (diff) | |
Auto merge of #67540 - Mark-Simulacrum:fmt-the-world, r=Centril
Format the world This PR modifies the formatting infrastructure a bit in the first commit (to enable the forgotten 2018 edition), as well as removes most directories from the ignore list in rustfmt.toml. It then follows that up with the second commit which runs `x.py fmt` and formats the entire repository. We continue to not format the test directory (`src/test`) because of interactions with pretty printing and, in part, because re-blessing all of those files is somewhat harder to review, so is best suited for a follow up PR in my opinion.
Diffstat (limited to 'src/libserialize')
| -rw-r--r-- | src/libserialize/collection_impls.rs | 74 | ||||
| -rw-r--r-- | src/libserialize/hex.rs | 18 | ||||
| -rw-r--r-- | src/libserialize/hex/tests.rs | 19 | ||||
| -rw-r--r-- | src/libserialize/json.rs | 912 | ||||
| -rw-r--r-- | src/libserialize/json/tests.rs | 53 | ||||
| -rw-r--r-- | src/libserialize/leb128.rs | 46 | ||||
| -rw-r--r-- | src/libserialize/lib.rs | 19 | ||||
| -rw-r--r-- | src/libserialize/opaque.rs | 26 | ||||
| -rw-r--r-- | src/libserialize/serialize.rs | 270 | ||||
| -rw-r--r-- | src/libserialize/tests/json.rs | 661 | ||||
| -rw-r--r-- | src/libserialize/tests/leb128.rs | 6 | ||||
| -rw-r--r-- | src/libserialize/tests/opaque.rs | 125 |
12 files changed, 1242 insertions, 987 deletions
diff --git a/src/libserialize/collection_impls.rs b/src/libserialize/collection_impls.rs index f2e9be14c8d..c602de37b14 100644 --- a/src/libserialize/collection_impls.rs +++ b/src/libserialize/collection_impls.rs @@ -1,9 +1,9 @@ //! Implementations of serialization for structures found in liballoc -use std::hash::{Hash, BuildHasher}; +use std::hash::{BuildHasher, Hash}; -use crate::{Decodable, Encodable, Decoder, Encoder}; -use std::collections::{LinkedList, VecDeque, BTreeMap, BTreeSet, HashMap, HashSet}; +use crate::{Decodable, Decoder, Encodable, Encoder}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, LinkedList, VecDeque}; use std::rc::Rc; use std::sync::Arc; @@ -44,7 +44,7 @@ impl<T: Encodable> Encodable for LinkedList<T> { } } -impl<T:Decodable> Decodable for LinkedList<T> { +impl<T: Decodable> Decodable for LinkedList<T> { fn decode<D: Decoder>(d: &mut D) -> Result<LinkedList<T>, D::Error> { d.read_seq(|d, len| { let mut list = LinkedList::new(); @@ -67,7 +67,7 @@ impl<T: Encodable> Encodable for VecDeque<T> { } } -impl<T:Decodable> Decodable for VecDeque<T> { +impl<T: Decodable> Decodable for VecDeque<T> { fn decode<D: Decoder>(d: &mut D) -> Result<VecDeque<T>, D::Error> { d.read_seq(|d, len| { let mut deque: VecDeque<T> = VecDeque::with_capacity(len); @@ -80,8 +80,9 @@ impl<T:Decodable> Decodable for VecDeque<T> { } impl<K, V> Encodable for BTreeMap<K, V> - where K: Encodable + PartialEq + Ord, - V: Encodable +where + K: Encodable + PartialEq + Ord, + V: Encodable, { fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> { e.emit_map(self.len(), |e| { @@ -97,8 +98,9 @@ impl<K, V> Encodable for BTreeMap<K, V> } impl<K, V> Decodable for BTreeMap<K, V> - where K: Decodable + PartialEq + Ord, - V: Decodable +where + K: Decodable + PartialEq + Ord, + V: Decodable, { fn decode<D: Decoder>(d: &mut D) -> Result<BTreeMap<K, V>, D::Error> { d.read_map(|d, len| { @@ -114,7 +116,8 @@ impl<K, V> Decodable for BTreeMap<K, V> } impl<T> Encodable for BTreeSet<T> - where T: Encodable + PartialEq + Ord +where + T: Encodable + PartialEq + Ord, { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_seq(self.len(), |s| { @@ -129,7 +132,8 @@ impl<T> Encodable for BTreeSet<T> } impl<T> Decodable for BTreeSet<T> - where T: Decodable + PartialEq + Ord +where + T: Decodable + PartialEq + Ord, { fn decode<D: Decoder>(d: &mut D) -> Result<BTreeSet<T>, D::Error> { d.read_seq(|d, len| { @@ -143,9 +147,10 @@ impl<T> Decodable for BTreeSet<T> } impl<K, V, S> Encodable for HashMap<K, V, S> - where K: Encodable + Eq, - V: Encodable, - S: BuildHasher, +where + K: Encodable + Eq, + V: Encodable, + S: BuildHasher, { fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> { e.emit_map(self.len(), |e| { @@ -161,9 +166,10 @@ impl<K, V, S> Encodable for HashMap<K, V, S> } impl<K, V, S> Decodable for HashMap<K, V, S> - where K: Decodable + Hash + Eq, - V: Decodable, - S: BuildHasher + Default, +where + K: Decodable + Hash + Eq, + V: Decodable, + S: BuildHasher + Default, { fn decode<D: Decoder>(d: &mut D) -> Result<HashMap<K, V, S>, D::Error> { d.read_map(|d, len| { @@ -180,8 +186,9 @@ impl<K, V, S> Decodable for HashMap<K, V, S> } impl<T, S> Encodable for HashSet<T, S> - where T: Encodable + Eq, - S: BuildHasher, +where + T: Encodable + Eq, + S: BuildHasher, { fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> { s.emit_seq(self.len(), |s| { @@ -196,8 +203,9 @@ impl<T, S> Encodable for HashSet<T, S> } impl<T, S> Decodable for HashSet<T, S> - where T: Decodable + Hash + Eq, - S: BuildHasher + Default, +where + T: Decodable + Hash + Eq, + S: BuildHasher + Default, { fn decode<D: Decoder>(d: &mut D) -> Result<HashSet<T, S>, D::Error> { d.read_seq(|d, len| { @@ -212,9 +220,10 @@ impl<T, S> Decodable for HashSet<T, S> } impl<K, V, S> Encodable for indexmap::IndexMap<K, V, S> - where K: Encodable + Hash + Eq, - V: Encodable, - S: BuildHasher, +where + K: Encodable + Hash + Eq, + V: Encodable, + S: BuildHasher, { fn encode<E: Encoder>(&self, e: &mut E) -> Result<(), E::Error> { e.emit_map(self.len(), |e| { @@ -230,9 +239,10 @@ impl<K, V, S> Encodable for indexmap::IndexMap<K, V, S> } impl<K, V, S> Decodable for indexmap::IndexMap<K, V, S> - where K: Decodable + Hash + Eq, - V: Decodable, - S: BuildHasher + Default, +where + K: Decodable + Hash + Eq, + V: Decodable, + S: BuildHasher + Default, { fn decode<D: Decoder>(d: &mut D) -> Result<indexmap::IndexMap<K, V, S>, D::Error> { d.read_map(|d, len| { @@ -249,8 +259,9 @@ impl<K, V, S> Decodable for indexmap::IndexMap<K, V, S> } impl<T, S> Encodable for indexmap::IndexSet<T, S> - where T: Encodable + Hash + Eq, - S: BuildHasher, +where + T: Encodable + Hash + Eq, + S: BuildHasher, { fn encode<E: Encoder>(&self, s: &mut E) -> Result<(), E::Error> { s.emit_seq(self.len(), |s| { @@ -265,8 +276,9 @@ impl<T, S> Encodable for indexmap::IndexSet<T, S> } impl<T, S> Decodable for indexmap::IndexSet<T, S> - where T: Decodable + Hash + Eq, - S: BuildHasher + Default, +where + T: Decodable + Hash + Eq, + S: BuildHasher + Default, { fn decode<D: Decoder>(d: &mut D) -> Result<indexmap::IndexSet<T, S>, D::Error> { d.read_seq(|d, len| { diff --git a/src/libserialize/hex.rs b/src/libserialize/hex.rs index 95d92f311ed..a2a5a3cb59c 100644 --- a/src/libserialize/hex.rs +++ b/src/libserialize/hex.rs @@ -2,8 +2,8 @@ pub use self::FromHexError::*; -use std::fmt; use std::error; +use std::fmt; /// A trait for converting a value to hexadecimal encoding pub trait ToHex { @@ -37,9 +37,7 @@ impl ToHex for [u8] { v.push(CHARS[(byte & 0xf) as usize]); } - unsafe { - String::from_utf8_unchecked(v) - } + unsafe { String::from_utf8_unchecked(v) } } } @@ -62,8 +60,9 @@ pub enum FromHexError { impl fmt::Display for FromHexError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - InvalidHexCharacter(ch, idx) => - write!(f, "Invalid character '{}' at position {}", ch, idx), + InvalidHexCharacter(ch, idx) => { + write!(f, "Invalid character '{}' at position {}", ch, idx) + } InvalidHexLength => write!(f, "Invalid input length"), } } @@ -78,7 +77,6 @@ impl error::Error for FromHexError { } } - impl FromHex for str { /// Converts any hexadecimal encoded string (literal, `@`, `&`, or `~`) /// to the byte values it encodes. @@ -118,13 +116,13 @@ impl FromHex for str { b'A'..=b'F' => buf |= byte - b'A' + 10, b'a'..=b'f' => buf |= byte - b'a' + 10, b'0'..=b'9' => buf |= byte - b'0', - b' '|b'\r'|b'\n'|b'\t' => { + b' ' | b'\r' | b'\n' | b'\t' => { buf >>= 4; - continue + continue; } _ => { let ch = self[idx..].chars().next().unwrap(); - return Err(InvalidHexCharacter(ch, idx)) + return Err(InvalidHexCharacter(ch, idx)); } } diff --git a/src/libserialize/hex/tests.rs b/src/libserialize/hex/tests.rs index 471912c11d0..ce62c0ff232 100644 --- a/src/libserialize/hex/tests.rs +++ b/src/libserialize/hex/tests.rs @@ -1,6 +1,6 @@ extern crate test; -use test::Bencher; use crate::hex::{FromHex, ToHex}; +use test::Bencher; #[test] pub fn test_to_hex() { @@ -9,10 +9,8 @@ pub fn test_to_hex() { #[test] pub fn test_from_hex_okay() { - assert_eq!("666f6f626172".from_hex().unwrap(), - b"foobar"); - assert_eq!("666F6F626172".from_hex().unwrap(), - b"foobar"); + assert_eq!("666f6f626172".from_hex().unwrap(), b"foobar"); + assert_eq!("666F6F626172".from_hex().unwrap(), b"foobar"); } #[test] @@ -28,8 +26,7 @@ pub fn test_from_hex_invalid_char() { #[test] pub fn test_from_hex_ignores_whitespace() { - assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), - b"foobar"); + assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), b"foobar"); } #[test] @@ -43,12 +40,8 @@ pub fn test_to_hex_all_bytes() { pub fn test_from_hex_all_bytes() { for i in 0..256 { let ii: &[u8] = &[i as u8]; - assert_eq!(format!("{:02x}", i as usize).from_hex() - .unwrap(), - ii); - assert_eq!(format!("{:02X}", i as usize).from_hex() - .unwrap(), - ii); + assert_eq!(format!("{:02x}", i as usize).from_hex().unwrap(), ii); + assert_eq!(format!("{:02X}", i as usize).from_hex().unwrap(), ii); } } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index d2e360f5e20..b1ad0e853a3 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -182,17 +182,17 @@ //! } //! ``` -use self::JsonEvent::*; +use self::DecoderError::*; use self::ErrorCode::*; +use self::InternalStackElement::*; +use self::JsonEvent::*; use self::ParserError::*; -use self::DecoderError::*; use self::ParserState::*; -use self::InternalStackElement::*; use std::borrow::Cow; -use std::collections::{HashMap, BTreeMap}; -use std::io::prelude::*; +use std::collections::{BTreeMap, HashMap}; use std::io; +use std::io::prelude::*; use std::mem::swap; use std::num::FpCategory as Fp; use std::ops::Index; @@ -218,10 +218,17 @@ pub enum Json { pub type Array = Vec<Json>; pub type Object = BTreeMap<string::String, Json>; -pub struct PrettyJson<'a> { inner: &'a Json } +pub struct PrettyJson<'a> { + inner: &'a Json, +} -pub struct AsJson<'a, T> { inner: &'a T } -pub struct AsPrettyJson<'a, T> { inner: &'a T, indent: Option<usize> } +pub struct AsJson<'a, T> { + inner: &'a T, +} +pub struct AsPrettyJson<'a, T> { + inner: &'a T, + indent: Option<usize>, +} /// The errors that can arise while parsing a JSON stream. #[derive(Clone, Copy, PartialEq, Debug)] @@ -261,7 +268,7 @@ pub enum DecoderError { ExpectedError(string::String, string::String), MissingFieldError(string::String), UnknownVariantError(string::String), - ApplicationError(string::String) + ApplicationError(string::String), } #[derive(Copy, Clone, Debug)] @@ -297,7 +304,7 @@ pub fn error_str(error: ErrorCode) -> &'static str { pub fn decode<T: crate::Decodable>(s: &str) -> DecodeResult<T> { let json = match from_str(s) { Ok(x) => x, - Err(e) => return Err(ParseError(e)) + Err(e) => return Err(ParseError(e)), }; let mut decoder = Decoder::new(json); @@ -339,7 +346,9 @@ impl fmt::Display for DecoderError { } impl std::error::Error for DecoderError { - fn description(&self) -> &str { "decoder error" } + fn description(&self) -> &str { + "decoder error" + } } impl fmt::Display for EncoderError { @@ -350,14 +359,18 @@ impl fmt::Display for EncoderError { } impl std::error::Error for EncoderError { - fn description(&self) -> &str { "encoder error" } + fn description(&self) -> &str { + "encoder error" + } } impl From<fmt::Error> for EncoderError { /// Converts a [`fmt::Error`] into `EncoderError` /// /// This conversion does not allocate memory. - fn from(err: fmt::Error) -> EncoderError { EncoderError::FmtError(err) } + fn from(err: fmt::Error) -> EncoderError { + EncoderError::FmtError(err) + } } pub type EncodeResult = Result<(), EncoderError>; @@ -405,7 +418,9 @@ fn escape_str(wr: &mut dyn fmt::Write, v: &str) -> EncodeResult { b'\x1e' => "\\u001e", b'\x1f' => "\\u001f", b'\x7f' => "\\u007f", - _ => { continue; } + _ => { + continue; + } }; if start < i { @@ -453,7 +468,7 @@ fn fmt_number_or_null(v: f64) -> string::String { /// A structure for implementing serialization to JSON. pub struct Encoder<'a> { - writer: &'a mut (dyn fmt::Write+'a), + writer: &'a mut (dyn fmt::Write + 'a), is_emitting_map_key: bool, } @@ -461,46 +476,74 @@ impl<'a> Encoder<'a> { /// Creates a new JSON encoder whose output will be written to the writer /// specified. pub fn new(writer: &'a mut dyn fmt::Write) -> Encoder<'a> { - Encoder { writer, is_emitting_map_key: false, } + Encoder { writer, is_emitting_map_key: false } } } macro_rules! emit_enquoted_if_mapkey { - ($enc:ident,$e:expr) => ({ + ($enc:ident,$e:expr) => {{ if $enc.is_emitting_map_key { write!($enc.writer, "\"{}\"", $e)?; } else { write!($enc.writer, "{}", $e)?; } Ok(()) - }) + }}; } impl<'a> crate::Encoder for Encoder<'a> { type Error = EncoderError; fn emit_unit(&mut self) -> EncodeResult { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } write!(self.writer, "null")?; Ok(()) } - fn emit_usize(&mut self, v: usize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_u128(&mut self, v: u128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_u64(&mut self, v: u64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_u32(&mut self, v: u32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_u16(&mut self, v: u16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_u8(&mut self, v: u8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } + fn emit_usize(&mut self, v: usize) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_u128(&mut self, v: u128) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_u64(&mut self, v: u64) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_u32(&mut self, v: u32) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_u16(&mut self, v: u16) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_u8(&mut self, v: u8) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } - fn emit_isize(&mut self, v: isize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_i128(&mut self, v: i128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_i64(&mut self, v: i64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_i32(&mut self, v: i32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_i16(&mut self, v: i16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_i8(&mut self, v: i8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } + fn emit_isize(&mut self, v: isize) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_i128(&mut self, v: i128) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_i64(&mut self, v: i64) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_i32(&mut self, v: i32) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_i16(&mut self, v: i16) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_i8(&mut self, v: i8) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } fn emit_bool(&mut self, v: bool) -> EncodeResult { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if v { write!(self.writer, "true")?; } else { @@ -523,17 +566,15 @@ impl<'a> crate::Encoder for Encoder<'a> { escape_str(self.writer, v) } - fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where + fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { f(self) } - fn emit_enum_variant<F>(&mut self, - name: &str, - _id: usize, - cnt: usize, - f: F) -> EncodeResult where + fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { // enums are encoded as strings or objects @@ -542,7 +583,9 @@ impl<'a> crate::Encoder for Encoder<'a> { if cnt == 0 { escape_str(self.writer, name) } else { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } write!(self.writer, "{{\"variant\":")?; escape_str(self.writer, name)?; write!(self.writer, ",\"fields\":[")?; @@ -552,145 +595,198 @@ impl<'a> crate::Encoder for Encoder<'a> { } } - fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where + fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if idx != 0 { write!(self.writer, ",")?; } f(self) } - fn emit_enum_struct_variant<F>(&mut self, - name: &str, - id: usize, - cnt: usize, - f: F) -> EncodeResult where + fn emit_enum_struct_variant<F>( + &mut self, + name: &str, + id: usize, + cnt: usize, + f: F, + ) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_enum_variant(name, id, cnt, f) } - fn emit_enum_struct_variant_field<F>(&mut self, - _: &str, - idx: usize, - f: F) -> EncodeResult where + fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_enum_variant_arg(idx, f) } - fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult where + fn emit_struct<F>(&mut self, _: &str, _: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } write!(self.writer, "{{")?; f(self)?; write!(self.writer, "}}")?; Ok(()) } - fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult where + fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } - if idx != 0 { write!(self.writer, ",")?; } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } + if idx != 0 { + write!(self.writer, ",")?; + } escape_str(self.writer, name)?; write!(self.writer, ":")?; f(self) } - fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult where + fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_seq(len, f) } - fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where + fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_seq_elt(idx, f) } - fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult where + fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_seq(len, f) } - fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where + fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_seq_elt(idx, f) } - fn emit_option<F>(&mut self, f: F) -> EncodeResult where + fn emit_option<F>(&mut self, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } f(self) } fn emit_option_none(&mut self) -> EncodeResult { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_unit() } - fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where + fn emit_option_some<F>(&mut self, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } f(self) } - fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult where + fn emit_seq<F>(&mut self, _len: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } write!(self.writer, "[")?; f(self)?; write!(self.writer, "]")?; Ok(()) } - fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult where + fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if idx != 0 { write!(self.writer, ",")?; } f(self) } - fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult where + fn emit_map<F>(&mut self, _len: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } write!(self.writer, "{{")?; f(self)?; write!(self.writer, "}}")?; Ok(()) } - fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult where + fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } - if idx != 0 { write!(self.writer, ",")? } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } + if idx != 0 { + write!(self.writer, ",")? + } self.is_emitting_map_key = true; f(self)?; self.is_emitting_map_key = false; Ok(()) } - fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult where + fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut Encoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } write!(self.writer, ":")?; f(self) } @@ -699,7 +795,7 @@ impl<'a> crate::Encoder for Encoder<'a> { /// Another encoder for JSON, but prints out human-readable JSON instead of /// compact data pub struct PrettyEncoder<'a> { - writer: &'a mut (dyn fmt::Write+'a), + writer: &'a mut (dyn fmt::Write + 'a), curr_indent: usize, indent: usize, is_emitting_map_key: bool, @@ -708,12 +804,7 @@ pub struct PrettyEncoder<'a> { impl<'a> PrettyEncoder<'a> { /// Creates a new encoder whose output will be written to the specified writer pub fn new(writer: &'a mut dyn fmt::Write) -> PrettyEncoder<'a> { - PrettyEncoder { - writer, - curr_indent: 0, - indent: 2, - is_emitting_map_key: false, - } + PrettyEncoder { writer, curr_indent: 0, indent: 2, is_emitting_map_key: false } } /// Sets the number of spaces to indent for each level. @@ -730,27 +821,55 @@ impl<'a> crate::Encoder for PrettyEncoder<'a> { type Error = EncoderError; fn emit_unit(&mut self) -> EncodeResult { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } write!(self.writer, "null")?; Ok(()) } - fn emit_usize(&mut self, v: usize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_u128(&mut self, v: u128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_u64(&mut self, v: u64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_u32(&mut self, v: u32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_u16(&mut self, v: u16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_u8(&mut self, v: u8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } + fn emit_usize(&mut self, v: usize) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_u128(&mut self, v: u128) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_u64(&mut self, v: u64) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_u32(&mut self, v: u32) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_u16(&mut self, v: u16) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_u8(&mut self, v: u8) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } - fn emit_isize(&mut self, v: isize) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_i128(&mut self, v: i128) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_i64(&mut self, v: i64) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_i32(&mut self, v: i32) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_i16(&mut self, v: i16) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } - fn emit_i8(&mut self, v: i8) -> EncodeResult { emit_enquoted_if_mapkey!(self, v) } + fn emit_isize(&mut self, v: isize) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_i128(&mut self, v: i128) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_i64(&mut self, v: i64) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_i32(&mut self, v: i32) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_i16(&mut self, v: i16) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } + fn emit_i8(&mut self, v: i8) -> EncodeResult { + emit_enquoted_if_mapkey!(self, v) + } fn emit_bool(&mut self, v: bool) -> EncodeResult { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if v { write!(self.writer, "true")?; } else { @@ -773,24 +892,23 @@ impl<'a> crate::Encoder for PrettyEncoder<'a> { escape_str(self.writer, v) } - fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult where + fn emit_enum<F>(&mut self, _name: &str, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { f(self) } - fn emit_enum_variant<F>(&mut self, - name: &str, - _id: usize, - cnt: usize, - f: F) - -> EncodeResult where + fn emit_enum_variant<F>(&mut self, name: &str, _id: usize, cnt: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { if cnt == 0 { escape_str(self.writer, name) } else { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } writeln!(self.writer, "{{")?; self.curr_indent += self.indent; spaces(self.writer, self.curr_indent)?; @@ -812,10 +930,13 @@ impl<'a> crate::Encoder for PrettyEncoder<'a> { } } - fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where + fn emit_enum_variant_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if idx != 0 { writeln!(self.writer, ",")?; } @@ -823,32 +944,39 @@ impl<'a> crate::Encoder for PrettyEncoder<'a> { f(self) } - fn emit_enum_struct_variant<F>(&mut self, - name: &str, - id: usize, - cnt: usize, - f: F) -> EncodeResult where + fn emit_enum_struct_variant<F>( + &mut self, + name: &str, + id: usize, + cnt: usize, + f: F, + ) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_enum_variant(name, id, cnt, f) } - fn emit_enum_struct_variant_field<F>(&mut self, - _: &str, - idx: usize, - f: F) -> EncodeResult where + fn emit_enum_struct_variant_field<F>(&mut self, _: &str, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_enum_variant_arg(idx, f) } - - fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult where + fn emit_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if len == 0 { write!(self.writer, "{{}}")?; } else { @@ -863,10 +991,13 @@ impl<'a> crate::Encoder for PrettyEncoder<'a> { Ok(()) } - fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult where + fn emit_struct_field<F>(&mut self, name: &str, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if idx == 0 { writeln!(self.writer)?; } else { @@ -878,53 +1009,76 @@ impl<'a> crate::Encoder for PrettyEncoder<'a> { f(self) } - fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult where + fn emit_tuple<F>(&mut self, len: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_seq(len, f) } - fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where + fn emit_tuple_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_seq_elt(idx, f) } - fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult where + fn emit_tuple_struct<F>(&mut self, _: &str, len: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_seq(len, f) } - fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult where + fn emit_tuple_struct_arg<F>(&mut self, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_seq_elt(idx, f) } - fn emit_option<F>(&mut self, f: F) -> EncodeResult where + fn emit_option<F>(&mut self, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } f(self) } fn emit_option_none(&mut self) -> EncodeResult { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } self.emit_unit() } - fn emit_option_some<F>(&mut self, f: F) -> EncodeResult where + fn emit_option_some<F>(&mut self, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } f(self) } - fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult where + fn emit_seq<F>(&mut self, len: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if len == 0 { write!(self.writer, "[]")?; } else { @@ -939,10 +1093,13 @@ impl<'a> crate::Encoder for PrettyEncoder<'a> { Ok(()) } - fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult where + fn emit_seq_elt<F>(&mut self, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if idx == 0 { writeln!(self.writer)?; } else { @@ -952,10 +1109,13 @@ impl<'a> crate::Encoder for PrettyEncoder<'a> { f(self) } - fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult where + fn emit_map<F>(&mut self, len: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if len == 0 { write!(self.writer, "{{}}")?; } else { @@ -970,10 +1130,13 @@ impl<'a> crate::Encoder for PrettyEncoder<'a> { Ok(()) } - fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult where + fn emit_map_elt_key<F>(&mut self, idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } if idx == 0 { writeln!(self.writer)?; } else { @@ -986,10 +1149,13 @@ impl<'a> crate::Encoder for PrettyEncoder<'a> { Ok(()) } - fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult where + fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> EncodeResult + where F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, { - if self.is_emitting_map_key { return Err(EncoderError::BadHashmapKey); } + if self.is_emitting_map_key { + return Err(EncoderError::BadHashmapKey); + } write!(self.writer, ": ")?; f(self) } @@ -1029,19 +1195,19 @@ impl Json { PrettyJson { inner: self } } - /// If the Json value is an Object, returns the value associated with the provided key. + /// If the Json value is an Object, returns the value associated with the provided key. /// Otherwise, returns None. pub fn find(&self, key: &str) -> Option<&Json> { match *self { Json::Object(ref map) => map.get(key), - _ => None + _ => None, } } /// Attempts to get a nested Json Object for each key in `keys`. /// If any key is found not to exist, `find_path` will return `None`. /// Otherwise, it will return the Json value associated with the final key. - pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{ + pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json> { let mut target = self; for key in keys { target = target.find(*key)?; @@ -1054,21 +1220,19 @@ impl Json { /// or the Json value is not an Object, returns `None`. pub fn search(&self, key: &str) -> Option<&Json> { match *self { - Json::Object(ref map) => { - match map.get(key) { - Some(json_value) => Some(json_value), - None => { - for v in map.values() { - match v.search(key) { - x if x.is_some() => return x, - _ => () - } + Json::Object(ref map) => match map.get(key) { + Some(json_value) => Some(json_value), + None => { + for v in map.values() { + match v.search(key) { + x if x.is_some() => return x, + _ => (), } - None } + None } }, - _ => None + _ => None, } } @@ -1082,7 +1246,7 @@ impl Json { pub fn as_object(&self) -> Option<&Object> { match *self { Json::Object(ref map) => Some(map), - _ => None + _ => None, } } @@ -1096,7 +1260,7 @@ impl Json { pub fn as_array(&self) -> Option<&Array> { match *self { Json::Array(ref array) => Some(&*array), - _ => None + _ => None, } } @@ -1110,7 +1274,7 @@ impl Json { pub fn as_string(&self) -> Option<&str> { match *self { Json::String(ref s) => Some(&s[..]), - _ => None + _ => None, } } @@ -1152,7 +1316,7 @@ impl Json { match *self { Json::I64(n) => Some(n), Json::U64(n) => Some(n as i64), - _ => None + _ => None, } } @@ -1162,7 +1326,7 @@ impl Json { match *self { Json::I64(n) => Some(n as u64), Json::U64(n) => Some(n), - _ => None + _ => None, } } @@ -1173,7 +1337,7 @@ impl Json { Json::I64(n) => Some(n as f64), Json::U64(n) => Some(n as f64), Json::F64(n) => Some(n), - _ => None + _ => None, } } @@ -1187,7 +1351,7 @@ impl Json { pub fn as_boolean(&self) -> Option<bool> { match *self { Json::Boolean(b) => Some(b), - _ => None + _ => None, } } @@ -1201,12 +1365,12 @@ impl Json { pub fn as_null(&self) -> Option<()> { match *self { Json::Null => Some(()), - _ => None + _ => None, } } } -impl<'a> Index<&'a str> for Json { +impl<'a> Index<&'a str> for Json { type Output = Json; fn index(&self, idx: &'a str) -> &Json { @@ -1220,7 +1384,7 @@ impl Index<usize> for Json { fn index(&self, idx: usize) -> &Json { match *self { Json::Array(ref v) => &v[idx], - _ => panic!("can only index Json with usize if it is an array") + _ => panic!("can only index Json with usize if it is an array"), } } } @@ -1291,10 +1455,14 @@ impl Stack { } /// Returns The number of elements in the Stack. - pub fn len(&self) -> usize { self.stack.len() } + pub fn len(&self) -> usize { + self.stack.len() + } /// Returns `true` if the stack is empty. - pub fn is_empty(&self) -> bool { self.stack.is_empty() } + pub fn is_empty(&self) -> bool { + self.stack.is_empty() + } /// Provides access to the StackElement at a given index. /// lower indices are at the bottom of the stack while higher indices are @@ -1302,19 +1470,22 @@ impl Stack { pub fn get(&self, idx: usize) -> StackElement<'_> { match self.stack[idx] { InternalIndex(i) => StackElement::Index(i), - InternalKey(start, size) => { - StackElement::Key(str::from_utf8( - &self.str_buffer[start as usize .. start as usize + size as usize]) - .unwrap()) - } + InternalKey(start, size) => StackElement::Key( + str::from_utf8(&self.str_buffer[start as usize..start as usize + size as usize]) + .unwrap(), + ), } } /// Compares this stack with an array of StackElement<'_>s. pub fn is_equal_to(&self, rhs: &[StackElement<'_>]) -> bool { - if self.stack.len() != rhs.len() { return false; } + if self.stack.len() != rhs.len() { + return false; + } for (i, r) in rhs.iter().enumerate() { - if self.get(i) != *r { return false; } + if self.get(i) != *r { + return false; + } } true } @@ -1322,9 +1493,13 @@ impl Stack { /// Returns `true` if the bottom-most elements of this stack are the same as /// the ones passed as parameter. pub fn starts_with(&self, rhs: &[StackElement<'_>]) -> bool { - if self.stack.len() < rhs.len() { return false; } + if self.stack.len() < rhs.len() { + return false; + } for (i, r) in rhs.iter().enumerate() { - if self.get(i) != *r { return false; } + if self.get(i) != *r { + return false; + } } true } @@ -1332,10 +1507,14 @@ impl Stack { /// Returns `true` if the top-most elements of this stack are the same as /// the ones passed as parameter. pub fn ends_with(&self, rhs: &[StackElement<'_>]) -> bool { - if self.stack.len() < rhs.len() { return false; } + if self.stack.len() < rhs.len() { + return false; + } let offset = self.stack.len() - rhs.len(); for (i, r) in rhs.iter().enumerate() { - if self.get(i + offset) != *r { return false; } + if self.get(i + offset) != *r { + return false; + } } true } @@ -1345,11 +1524,9 @@ impl Stack { match self.stack.last() { None => None, Some(&InternalIndex(i)) => Some(StackElement::Index(i)), - Some(&InternalKey(start, size)) => { - Some(StackElement::Key(str::from_utf8( - &self.str_buffer[start as usize .. (start+size) as usize] - ).unwrap())) - } + Some(&InternalKey(start, size)) => Some(StackElement::Key( + str::from_utf8(&self.str_buffer[start as usize..(start + size) as usize]).unwrap(), + )), } } @@ -1389,8 +1566,10 @@ impl Stack { fn bump_index(&mut self) { let len = self.stack.len(); let idx = match *self.stack.last().unwrap() { - InternalIndex(i) => { i + 1 } - _ => { panic!(); } + InternalIndex(i) => i + 1, + _ => { + panic!(); + } }; self.stack[len - 1] = InternalIndex(idx); } @@ -1410,7 +1589,7 @@ pub struct Parser<T> { state: ParserState, } -impl<T: Iterator<Item=char>> Iterator for Parser<T> { +impl<T: Iterator<Item = char>> Iterator for Parser<T> { type Item = JsonEvent; fn next(&mut self) -> Option<JsonEvent> { @@ -1433,7 +1612,7 @@ impl<T: Iterator<Item=char>> Iterator for Parser<T> { } } -impl<T: Iterator<Item=char>> Parser<T> { +impl<T: Iterator<Item = char>> Parser<T> { /// Creates the JSON parser. pub fn new(rdr: T) -> Parser<T> { let mut p = Parser { @@ -1454,8 +1633,12 @@ impl<T: Iterator<Item=char>> Parser<T> { &self.stack } - fn eof(&self) -> bool { self.ch.is_none() } - fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') } + fn eof(&self) -> bool { + self.ch.is_none() + } + fn ch_or_null(&self) -> char { + self.ch.unwrap_or('\x00') + } fn bump(&mut self) { self.ch = self.rdr.next(); @@ -1480,10 +1663,9 @@ impl<T: Iterator<Item=char>> Parser<T> { } fn parse_whitespace(&mut self) { - while self.ch_is(' ') || - self.ch_is('\n') || - self.ch_is('\t') || - self.ch_is('\r') { self.bump(); } + while self.ch_is(' ') || self.ch_is('\n') || self.ch_is('\t') || self.ch_is('\r') { + self.bump(); + } } fn parse_number(&mut self) -> JsonEvent { @@ -1496,7 +1678,9 @@ impl<T: Iterator<Item=char>> Parser<T> { let res = match self.parse_u64() { Ok(res) => res, - Err(e) => { return Error(e); } + Err(e) => { + return Error(e); + } }; if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') { @@ -1505,14 +1689,18 @@ impl<T: Iterator<Item=char>> Parser<T> { if self.ch_is('.') { res = match self.parse_decimal(res) { Ok(res) => res, - Err(e) => { return Error(e); } + Err(e) => { + return Error(e); + } }; } if self.ch_is('e') || self.ch_is('E') { res = match self.parse_exponent(res) { Ok(res) => res, - Err(e) => { return Error(e); } + Err(e) => { + return Error(e); + } }; } @@ -1544,19 +1732,21 @@ impl<T: Iterator<Item=char>> Parser<T> { self.bump(); // A leading '0' must be the only digit before the decimal point. - if let '0' ..= '9' = self.ch_or_null() { - return self.error(InvalidNumber) + if let '0'..='9' = self.ch_or_null() { + return self.error(InvalidNumber); } - }, - '1' ..= '9' => { + } + '1'..='9' => { while !self.eof() { match self.ch_or_null() { - c @ '0' ..= '9' => { + c @ '0'..='9' => { accum = accum.wrapping_mul(10); accum = accum.wrapping_add((c as u64) - ('0' as u64)); // Detect overflow by comparing to the last value. - if accum <= last_accum { return self.error(InvalidNumber); } + if accum <= last_accum { + return self.error(InvalidNumber); + } self.bump(); } @@ -1575,14 +1765,14 @@ impl<T: Iterator<Item=char>> Parser<T> { // Make sure a digit follows the decimal place. match self.ch_or_null() { - '0' ..= '9' => (), - _ => return self.error(InvalidNumber) + '0'..='9' => (), + _ => return self.error(InvalidNumber), } let mut dec = 1.0; while !self.eof() { match self.ch_or_null() { - c @ '0' ..= '9' => { + c @ '0'..='9' => { dec /= 10.0; res += (((c as isize) - ('0' as isize)) as f64) * dec; self.bump(); @@ -1609,18 +1799,18 @@ impl<T: Iterator<Item=char>> Parser<T> { // Make sure a digit follows the exponent place. match self.ch_or_null() { - '0' ..= '9' => (), - _ => return self.error(InvalidNumber) + '0'..='9' => (), + _ => return self.error(InvalidNumber), } while !self.eof() { match self.ch_or_null() { - c @ '0' ..= '9' => { + c @ '0'..='9' => { exp *= 10; exp += (c as usize) - ('0' as usize); self.bump(); } - _ => break + _ => break, } } @@ -1640,14 +1830,14 @@ impl<T: Iterator<Item=char>> Parser<T> { while i < 4 && !self.eof() { self.bump(); n = match self.ch_or_null() { - c @ '0' ..= '9' => n * 16 + ((c as u16) - ('0' as u16)), + c @ '0'..='9' => n * 16 + ((c as u16) - ('0' as u16)), 'a' | 'A' => n * 16 + 10, 'b' | 'B' => n * 16 + 11, 'c' | 'C' => n * 16 + 12, 'd' | 'D' => n * 16 + 13, 'e' | 'E' => n * 16 + 14, 'f' | 'F' => n * 16 + 15, - _ => return self.error(InvalidEscape) + _ => return self.error(InvalidEscape), }; i += 1; @@ -1682,13 +1872,11 @@ impl<T: Iterator<Item=char>> Parser<T> { 'r' => res.push('\r'), 't' => res.push('\t'), 'u' => match self.decode_hex_escape()? { - 0xDC00 ..= 0xDFFF => { - return self.error(LoneLeadingSurrogateInHexEscape) - } + 0xDC00..=0xDFFF => return self.error(LoneLeadingSurrogateInHexEscape), // Non-BMP characters are encoded as a sequence of // two hex escapes, representing UTF-16 surrogates. - n1 @ 0xD800 ..= 0xDBFF => { + n1 @ 0xD800..=0xDBFF => { match (self.next_char(), self.next_char()) { (Some('\\'), Some('u')) => (), _ => return self.error(UnexpectedEndOfHexEscape), @@ -1696,10 +1884,10 @@ impl<T: Iterator<Item=char>> Parser<T> { let n2 = self.decode_hex_escape()?; if n2 < 0xDC00 || n2 > 0xDFFF { - return self.error(LoneLeadingSurrogateInHexEscape) + return self.error(LoneLeadingSurrogateInHexEscape); } - let c = (u32::from(n1 - 0xD800) << 10 | - u32::from(n2 - 0xDC00)) + 0x1_0000; + let c = + (u32::from(n1 - 0xD800) << 10 | u32::from(n2 - 0xDC00)) + 0x1_0000; res.push(char::from_u32(c).unwrap()); } @@ -1718,9 +1906,9 @@ impl<T: Iterator<Item=char>> Parser<T> { Some('"') => { self.bump(); return Ok(res); - }, + } Some(c) => res.push(c), - None => unreachable!() + None => unreachable!(), } } } @@ -1910,12 +2098,14 @@ impl<T: Iterator<Item=char>> Parser<T> { } fn parse_value(&mut self) -> JsonEvent { - if self.eof() { return self.error_event(EOFWhileParsingValue); } + if self.eof() { + return self.error_event(EOFWhileParsingValue); + } match self.ch_or_null() { - 'n' => { self.parse_ident("ull", NullValue) } - 't' => { self.parse_ident("rue", BooleanValue(true)) } - 'f' => { self.parse_ident("alse", BooleanValue(false)) } - '0' ..= '9' | '-' => self.parse_number(), + 'n' => self.parse_ident("ull", NullValue), + 't' => self.parse_ident("rue", BooleanValue(true)), + 'f' => self.parse_ident("alse", BooleanValue(false)), + '0'..='9' | '-' => self.parse_number(), '"' => match self.parse_str() { Ok(s) => StringValue(s), Err(e) => Error(e), @@ -1928,7 +2118,7 @@ impl<T: Iterator<Item=char>> Parser<T> { self.bump(); ObjectStart } - _ => { self.error_event(InvalidSyntax) } + _ => self.error_event(InvalidSyntax), } } @@ -1953,10 +2143,10 @@ pub struct Builder<T> { token: Option<JsonEvent>, } -impl<T: Iterator<Item=char>> Builder<T> { +impl<T: Iterator<Item = char>> Builder<T> { /// Creates a JSON Builder. pub fn new(src: T) -> Builder<T> { - Builder { parser: Parser::new(src), token: None, } + Builder { parser: Parser::new(src), token: None } } // Decode a Json value from a Parser. @@ -1966,8 +2156,12 @@ impl<T: Iterator<Item=char>> Builder<T> { self.bump(); match self.token { None => {} - Some(Error(ref e)) => { return Err(e.clone()); } - ref tok => { panic!("unexpected token {:?}", tok.clone()); } + Some(Error(ref e)) => { + return Err(e.clone()); + } + ref tok => { + panic!("unexpected token {:?}", tok.clone()); + } } result } @@ -2007,7 +2201,7 @@ impl<T: Iterator<Item=char>> Builder<T> { } match self.build_value() { Ok(v) => values.push(v), - Err(e) => { return Err(e) } + Err(e) => return Err(e), } self.bump(); } @@ -2020,18 +2214,30 @@ impl<T: Iterator<Item=char>> Builder<T> { loop { match self.token { - Some(ObjectEnd) => { return Ok(Json::Object(values)); } - Some(Error(ref e)) => { return Err(e.clone()); } - None => { break; } + Some(ObjectEnd) => { + return Ok(Json::Object(values)); + } + Some(Error(ref e)) => { + return Err(e.clone()); + } + None => { + break; + } _ => {} } let key = match self.parser.stack().top() { - Some(StackElement::Key(k)) => { k.to_owned() } - _ => { panic!("invalid state"); } + Some(StackElement::Key(k)) => k.to_owned(), + _ => { + panic!("invalid state"); + } }; match self.build_value() { - Ok(value) => { values.insert(key, value); } - Err(e) => { return Err(e); } + Ok(value) => { + values.insert(key, value); + } + Err(e) => { + return Err(e); + } } self.bump(); } @@ -2043,12 +2249,12 @@ impl<T: Iterator<Item=char>> Builder<T> { pub fn from_reader(rdr: &mut dyn Read) -> Result<Json, BuilderError> { let mut contents = Vec::new(); match rdr.read_to_end(&mut contents) { - Ok(c) => c, - Err(e) => return Err(io_error_to_error(e)) + Ok(c) => c, + Err(e) => return Err(io_error_to_error(e)), }; let s = match str::from_utf8(&contents).ok() { Some(s) => s, - _ => return Err(SyntaxError(NotUtf8, 0, 0)) + _ => return Err(SyntaxError(NotUtf8, 0, 0)), }; let mut builder = Builder::new(s.chars()); builder.build() @@ -2077,22 +2283,18 @@ impl Decoder { } macro_rules! expect { - ($e:expr, Null) => ({ + ($e:expr, Null) => {{ match $e { Json::Null => Ok(()), - other => Err(ExpectedError("Null".to_owned(), - other.to_string())) + other => Err(ExpectedError("Null".to_owned(), other.to_string())), } - }); - ($e:expr, $t:ident) => ({ + }}; + ($e:expr, $t:ident) => {{ match $e { Json::$t(v) => Ok(v), - other => { - Err(ExpectedError(stringify!($t).to_owned(), - other.to_string())) - } + other => Err(ExpectedError(stringify!($t).to_owned(), other.to_string())), } - }) + }}; } macro_rules! read_primitive { @@ -2134,7 +2336,9 @@ impl crate::Decoder for Decoder { read_primitive! { read_i64, i64 } read_primitive! { read_i128, i128 } - fn read_f32(&mut self) -> DecodeResult<f32> { self.read_f64().map(|x| x as f32) } + fn read_f32(&mut self) -> DecodeResult<f32> { + self.read_f64().map(|x| x as f32) + } fn read_f64(&mut self) -> DecodeResult<f64> { match self.pop() { @@ -2148,9 +2352,9 @@ impl crate::Decoder for Decoder { Some(f) => Ok(f), None => Err(ExpectedError("Number".to_owned(), s)), } - }, + } Json::Null => Ok(f64::NAN), - value => Err(ExpectedError("Number".to_owned(), value.to_string())) + value => Err(ExpectedError("Number".to_owned(), value.to_string())), } } @@ -2174,76 +2378,71 @@ impl crate::Decoder for Decoder { expect!(self.pop(), String).map(Cow::Owned) } - fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> where + fn read_enum<T, F>(&mut self, _name: &str, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder) -> DecodeResult<T>, { f(self) } - fn read_enum_variant<T, F>(&mut self, names: &[&str], - mut f: F) -> DecodeResult<T> - where F: FnMut(&mut Decoder, usize) -> DecodeResult<T>, + fn read_enum_variant<T, F>(&mut self, names: &[&str], mut f: F) -> DecodeResult<T> + where + F: FnMut(&mut Decoder, usize) -> DecodeResult<T>, { let name = match self.pop() { Json::String(s) => s, Json::Object(mut o) => { let n = match o.remove(&"variant".to_owned()) { Some(Json::String(s)) => s, - Some(val) => { - return Err(ExpectedError("String".to_owned(), val.to_string())) - } - None => { - return Err(MissingFieldError("variant".to_owned())) - } + Some(val) => return Err(ExpectedError("String".to_owned(), val.to_string())), + None => return Err(MissingFieldError("variant".to_owned())), }; match o.remove(&"fields".to_string()) { Some(Json::Array(l)) => { self.stack.extend(l.into_iter().rev()); - }, - Some(val) => { - return Err(ExpectedError("Array".to_owned(), val.to_string())) - } - None => { - return Err(MissingFieldError("fields".to_owned())) } + Some(val) => return Err(ExpectedError("Array".to_owned(), val.to_string())), + None => return Err(MissingFieldError("fields".to_owned())), } n } - json => { - return Err(ExpectedError("String or Object".to_owned(), json.to_string())) - } + json => return Err(ExpectedError("String or Object".to_owned(), json.to_string())), }; let idx = match names.iter().position(|n| *n == &name[..]) { Some(idx) => idx, - None => return Err(UnknownVariantError(name)) + None => return Err(UnknownVariantError(name)), }; f(self, idx) } - fn read_enum_variant_arg<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where + fn read_enum_variant_arg<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder) -> DecodeResult<T>, { f(self) } - fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> where + fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> DecodeResult<T> + where F: FnMut(&mut Decoder, usize) -> DecodeResult<T>, { self.read_enum_variant(names, f) } - - fn read_enum_struct_variant_field<T, F>(&mut self, - _name: &str, - idx: usize, - f: F) - -> DecodeResult<T> where + fn read_enum_struct_variant_field<T, F>( + &mut self, + _name: &str, + idx: usize, + f: F, + ) -> DecodeResult<T> + where F: FnOnce(&mut Decoder) -> DecodeResult<T>, { self.read_enum_variant_arg(idx, f) } - fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T> where + fn read_struct<T, F>(&mut self, _name: &str, _len: usize, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder) -> DecodeResult<T>, { let value = f(self)?; @@ -2251,11 +2450,8 @@ impl crate::Decoder for Decoder { Ok(value) } - fn read_struct_field<T, F>(&mut self, - name: &str, - _idx: usize, - f: F) - -> DecodeResult<T> where + fn read_struct_field<T, F>(&mut self, name: &str, _idx: usize, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder) -> DecodeResult<T>, { let mut obj = expect!(self.pop(), Object)?; @@ -2269,7 +2465,7 @@ impl crate::Decoder for Decoder { Ok(x) => x, Err(_) => return Err(MissingFieldError(name.to_string())), } - }, + } Some(json) => { self.stack.push(json); f(self)? @@ -2279,7 +2475,8 @@ impl crate::Decoder for Decoder { Ok(value) } - fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T> where + fn read_tuple<T, F>(&mut self, tuple_len: usize, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder) -> DecodeResult<T>, { self.read_seq(move |d, len| { @@ -2291,41 +2488,42 @@ impl crate::Decoder for Decoder { }) } - fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T> where + fn read_tuple_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder) -> DecodeResult<T>, { self.read_seq_elt(idx, f) } - fn read_tuple_struct<T, F>(&mut self, - _name: &str, - len: usize, - f: F) - -> DecodeResult<T> where + fn read_tuple_struct<T, F>(&mut self, _name: &str, len: usize, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder) -> DecodeResult<T>, { self.read_tuple(len, f) } - fn read_tuple_struct_arg<T, F>(&mut self, - idx: usize, - f: F) - -> DecodeResult<T> where + fn read_tuple_struct_arg<T, F>(&mut self, idx: usize, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder) -> DecodeResult<T>, { self.read_tuple_arg(idx, f) } - fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> where + fn read_option<T, F>(&mut self, mut f: F) -> DecodeResult<T> + where F: FnMut(&mut Decoder, bool) -> DecodeResult<T>, { match self.pop() { Json::Null => f(self, false), - value => { self.stack.push(value); f(self, true) } + value => { + self.stack.push(value); + f(self, true) + } } } - fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> where + fn read_seq<T, F>(&mut self, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>, { let array = expect!(self.pop(), Array)?; @@ -2334,13 +2532,15 @@ impl crate::Decoder for Decoder { f(self, len) } - fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where + fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder) -> DecodeResult<T>, { f(self) } - fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> where + fn read_map<T, F>(&mut self, f: F) -> DecodeResult<T> + where F: FnOnce(&mut Decoder, usize) -> DecodeResult<T>, { let obj = expect!(self.pop(), Object)?; @@ -2352,14 +2552,16 @@ impl crate::Decoder for Decoder { f(self, len) } - fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where - F: FnOnce(&mut Decoder) -> DecodeResult<T>, + fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> + where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, { f(self) } - fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> where - F: FnOnce(&mut Decoder) -> DecodeResult<T>, + fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> DecodeResult<T> + where + F: FnOnce(&mut Decoder) -> DecodeResult<T>, { f(self) } @@ -2400,36 +2602,48 @@ macro_rules! to_json_impl_u64 { to_json_impl_u64! { usize, u8, u16, u32, u64 } impl ToJson for Json { - fn to_json(&self) -> Json { self.clone() } + fn to_json(&self) -> Json { + self.clone() + } } impl ToJson for f32 { - fn to_json(&self) -> Json { f64::from(*self).to_json() } + fn to_json(&self) -> Json { + f64::from(*self).to_json() + } } impl ToJson for f64 { fn to_json(&self) -> Json { match self.classify() { Fp::Nan | Fp::Infinite => Json::Null, - _ => Json::F64(*self) + _ => Json::F64(*self), } } } impl ToJson for () { - fn to_json(&self) -> Json { Json::Null } + fn to_json(&self) -> Json { + Json::Null + } } impl ToJson for bool { - fn to_json(&self) -> Json { Json::Boolean(*self) } + fn to_json(&self) -> Json { + Json::Boolean(*self) + } } impl ToJson for str { - fn to_json(&self) -> Json { Json::String(self.to_string()) } + fn to_json(&self) -> Json { + Json::String(self.to_string()) + } } impl ToJson for string::String { - fn to_json(&self) -> Json { Json::String((*self).clone()) } + fn to_json(&self) -> Json { + Json::String((*self).clone()) + } } macro_rules! tuple_impl { @@ -2451,25 +2665,29 @@ macro_rules! tuple_impl { } } -tuple_impl!{A} -tuple_impl!{A, B} -tuple_impl!{A, B, C} -tuple_impl!{A, B, C, D} -tuple_impl!{A, B, C, D, E} -tuple_impl!{A, B, C, D, E, F} -tuple_impl!{A, B, C, D, E, F, G} -tuple_impl!{A, B, C, D, E, F, G, H} -tuple_impl!{A, B, C, D, E, F, G, H, I} -tuple_impl!{A, B, C, D, E, F, G, H, I, J} -tuple_impl!{A, B, C, D, E, F, G, H, I, J, K} -tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} +tuple_impl! {A} +tuple_impl! {A, B} +tuple_impl! {A, B, C} +tuple_impl! {A, B, C, D} +tuple_impl! {A, B, C, D, E} +tuple_impl! {A, B, C, D, E, F} +tuple_impl! {A, B, C, D, E, F, G} +tuple_impl! {A, B, C, D, E, F, G, H} +tuple_impl! {A, B, C, D, E, F, G, H, I} +tuple_impl! {A, B, C, D, E, F, G, H, I, J} +tuple_impl! {A, B, C, D, E, F, G, H, I, J, K} +tuple_impl! {A, B, C, D, E, F, G, H, I, J, K, L} impl<A: ToJson> ToJson for [A] { - fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) } + fn to_json(&self) -> Json { + Json::Array(self.iter().map(|elt| elt.to_json()).collect()) + } } impl<A: ToJson> ToJson for Vec<A> { - fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) } + fn to_json(&self) -> Json { + Json::Array(self.iter().map(|elt| elt.to_json()).collect()) + } } impl<A: ToJson> ToJson for BTreeMap<string::String, A> { @@ -2492,11 +2710,11 @@ impl<A: ToJson> ToJson for HashMap<string::String, A> { } } -impl<A:ToJson> ToJson for Option<A> { +impl<A: ToJson> ToJson for Option<A> { fn to_json(&self) -> Json { match *self { None => Json::Null, - Some(ref value) => value.to_json() + Some(ref value) => value.to_json(), } } } @@ -2509,7 +2727,7 @@ impl<'a, 'b> fmt::Write for FormatShim<'a, 'b> { fn write_str(&mut self, s: &str) -> fmt::Result { match self.inner.write_str(s) { Ok(_) => Ok(()), - Err(_) => Err(fmt::Error) + Err(_) => Err(fmt::Error), } } } @@ -2521,7 +2739,7 @@ impl fmt::Display for Json { let mut encoder = Encoder::new(&mut shim); match self.encode(&mut encoder) { Ok(_) => Ok(()), - Err(_) => Err(fmt::Error) + Err(_) => Err(fmt::Error), } } } @@ -2533,7 +2751,7 @@ impl<'a> fmt::Display for PrettyJson<'a> { let mut encoder = PrettyEncoder::new(&mut shim); match self.inner.encode(&mut encoder) { Ok(_) => Ok(()), - Err(_) => Err(fmt::Error) + Err(_) => Err(fmt::Error), } } } @@ -2545,7 +2763,7 @@ impl<'a, T: Encodable> fmt::Display for AsJson<'a, T> { let mut encoder = Encoder::new(&mut shim); match self.inner.encode(&mut encoder) { Ok(_) => Ok(()), - Err(_) => Err(fmt::Error) + Err(_) => Err(fmt::Error), } } } @@ -2568,7 +2786,7 @@ impl<'a, T: Encodable> fmt::Display for AsPrettyJson<'a, T> { } match self.inner.encode(&mut encoder) { Ok(_) => Ok(()), - Err(_) => Err(fmt::Error) + Err(_) => Err(fmt::Error), } } } diff --git a/src/libserialize/json/tests.rs b/src/libserialize/json/tests.rs index a16b8bdd787..01678fbf0b7 100644 --- a/src/libserialize/json/tests.rs +++ b/src/libserialize/json/tests.rs @@ -1,9 +1,9 @@ // Benchmarks and tests that require private items extern crate test; -use test::Bencher; -use super::{from_str, Parser, StackElement, Stack}; +use super::{from_str, Parser, Stack, StackElement}; use std::string; +use test::Bencher; #[test] fn test_stack() { @@ -38,19 +38,25 @@ fn test_stack() { stack.push_key("bar".to_string()); assert!(stack.len() == 3); - assert!(stack.is_equal_to(&[StackElement::Index(1), - StackElement::Key("foo"), - StackElement::Key("bar")])); + assert!(stack.is_equal_to(&[ + StackElement::Index(1), + StackElement::Key("foo"), + StackElement::Key("bar") + ])); assert!(stack.starts_with(&[StackElement::Index(1)])); assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")])); - assert!(stack.starts_with(&[StackElement::Index(1), - StackElement::Key("foo"), - StackElement::Key("bar")])); + assert!(stack.starts_with(&[ + StackElement::Index(1), + StackElement::Key("foo"), + StackElement::Key("bar") + ])); assert!(stack.ends_with(&[StackElement::Key("bar")])); assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")])); - assert!(stack.ends_with(&[StackElement::Index(1), - StackElement::Key("foo"), - StackElement::Key("bar")])); + assert!(stack.ends_with(&[ + StackElement::Index(1), + StackElement::Key("foo"), + StackElement::Key("bar") + ])); assert!(!stack.last_is_index()); assert!(stack.get(0) == StackElement::Index(1)); assert!(stack.get(1) == StackElement::Key("foo")); @@ -71,7 +77,7 @@ fn test_stack() { #[bench] fn bench_streaming_small(b: &mut Bencher) { - b.iter( || { + b.iter(|| { let mut parser = Parser::new( r#"{ "a": 1.0, @@ -80,7 +86,8 @@ fn bench_streaming_small(b: &mut Bencher) { "foo\nbar", { "c": {"d": null} } ] - }"#.chars() + }"# + .chars(), ); loop { match parser.next() { @@ -92,23 +99,27 @@ fn bench_streaming_small(b: &mut Bencher) { } #[bench] fn bench_small(b: &mut Bencher) { - b.iter( || { - let _ = from_str(r#"{ + b.iter(|| { + let _ = from_str( + r#"{ "a": 1.0, "b": [ true, "foo\nbar", { "c": {"d": null} } ] - }"#); + }"#, + ); }); } fn big_json() -> string::String { let mut src = "[\n".to_string(); for _ in 0..500 { - src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \ - [1,2,3]},"#); + src.push_str( + r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \ + [1,2,3]},"#, + ); } src.push_str("{}]"); return src; @@ -117,7 +128,7 @@ fn big_json() -> string::String { #[bench] fn bench_streaming_large(b: &mut Bencher) { let src = big_json(); - b.iter( || { + b.iter(|| { let mut parser = Parser::new(src.chars()); loop { match parser.next() { @@ -130,5 +141,7 @@ fn bench_streaming_large(b: &mut Bencher) { #[bench] fn bench_large(b: &mut Bencher) { let src = big_json(); - b.iter( || { let _ = from_str(&src); }); + b.iter(|| { + let _ = from_str(&src); + }); } diff --git a/src/libserialize/leb128.rs b/src/libserialize/leb128.rs index 88ce6d81d75..b8242f7154e 100644 --- a/src/libserialize/leb128.rs +++ b/src/libserialize/leb128.rs @@ -9,18 +9,28 @@ const USIZE_LEB128_SIZE: usize = 5; const USIZE_LEB128_SIZE: usize = 10; macro_rules! leb128_size { - (u16) => (3); - (u32) => (5); - (u64) => (10); - (u128) => (19); - (usize) => (USIZE_LEB128_SIZE); + (u16) => { + 3 + }; + (u32) => { + 5 + }; + (u64) => { + 10 + }; + (u128) => { + 19 + }; + (usize) => { + USIZE_LEB128_SIZE + }; } macro_rules! impl_write_unsigned_leb128 { - ($fn_name:ident, $int_ty:ident) => ( + ($fn_name:ident, $int_ty:ident) => { #[inline] pub fn $fn_name(out: &mut Vec<u8>, mut value: $int_ty) { - for _ in 0 .. leb128_size!($int_ty) { + for _ in 0..leb128_size!($int_ty) { let mut byte = (value & 0x7F) as u8; value >>= 7; if value != 0 { @@ -34,7 +44,7 @@ macro_rules! impl_write_unsigned_leb128 { } } } - ) + }; } impl_write_unsigned_leb128!(write_u16_leb128, u16); @@ -43,19 +53,16 @@ impl_write_unsigned_leb128!(write_u64_leb128, u64); impl_write_unsigned_leb128!(write_u128_leb128, u128); impl_write_unsigned_leb128!(write_usize_leb128, usize); - macro_rules! impl_read_unsigned_leb128 { - ($fn_name:ident, $int_ty:ident) => ( + ($fn_name:ident, $int_ty:ident) => { #[inline] pub fn $fn_name(slice: &[u8]) -> ($int_ty, usize) { let mut result: $int_ty = 0; let mut shift = 0; let mut position = 0; - for _ in 0 .. leb128_size!($int_ty) { - let byte = unsafe { - *slice.get_unchecked(position) - }; + for _ in 0..leb128_size!($int_ty) { + let byte = unsafe { *slice.get_unchecked(position) }; position += 1; result |= ((byte & 0x7F) as $int_ty) << shift; if (byte & 0x80) == 0 { @@ -69,7 +76,7 @@ macro_rules! impl_read_unsigned_leb128 { (result, position) } - ) + }; } impl_read_unsigned_leb128!(read_u16_leb128, u16); @@ -78,8 +85,6 @@ impl_read_unsigned_leb128!(read_u64_leb128, u64); impl_read_unsigned_leb128!(read_u128_leb128, u128); impl_read_unsigned_leb128!(read_usize_leb128, usize); - - #[inline] /// encodes an integer using signed leb128 encoding and stores /// the result using a callback function. @@ -88,13 +93,14 @@ impl_read_unsigned_leb128!(read_usize_leb128, usize); /// that is to be written to with the byte to be encoded /// at that position. pub fn write_signed_leb128_to<W>(mut value: i128, mut write: W) - where W: FnMut(u8) +where + W: FnMut(u8), { loop { let mut byte = (value as u8) & 0x7f; value >>= 7; - let more = !(((value == 0) && ((byte & 0x40) == 0)) || - ((value == -1) && ((byte & 0x40) != 0))); + let more = + !(((value == 0) && ((byte & 0x40) == 0)) || ((value == -1) && ((byte & 0x40) != 0))); if more { byte |= 0x80; // Mark this byte to show that more bytes will follow. diff --git a/src/libserialize/lib.rs b/src/libserialize/lib.rs index e45d56c320c..280fb078f7d 100644 --- a/src/libserialize/lib.rs +++ b/src/libserialize/lib.rs @@ -4,10 +4,11 @@ Core encoding and decoding interfaces. */ -#![doc(html_root_url = "https://doc.rust-lang.org/nightly/", - html_playground_url = "https://play.rust-lang.org/", - test(attr(allow(unused_variables), deny(warnings))))] - +#![doc( + html_root_url = "https://doc.rust-lang.org/nightly/", + html_playground_url = "https://play.rust-lang.org/", + test(attr(allow(unused_variables), deny(warnings))) +)] #![feature(box_syntax)] #![feature(core_intrinsics)] #![feature(specialization)] @@ -17,16 +18,16 @@ Core encoding and decoding interfaces. #![cfg_attr(test, feature(test))] #![allow(rustc::internal)] -pub use self::serialize::{Decoder, Encoder, Decodable, Encodable}; +pub use self::serialize::{Decodable, Decoder, Encodable, Encoder}; -pub use self::serialize::{SpecializationError, SpecializedEncoder, SpecializedDecoder}; -pub use self::serialize::{UseSpecializedEncodable, UseSpecializedDecodable}; +pub use self::serialize::{SpecializationError, SpecializedDecoder, SpecializedEncoder}; +pub use self::serialize::{UseSpecializedDecodable, UseSpecializedEncodable}; -mod serialize; mod collection_impls; +mod serialize; pub mod hex; pub mod json; -pub mod opaque; pub mod leb128; +pub mod opaque; diff --git a/src/libserialize/opaque.rs b/src/libserialize/opaque.rs index 75988198eb9..e808d981998 100644 --- a/src/libserialize/opaque.rs +++ b/src/libserialize/opaque.rs @@ -31,14 +31,14 @@ macro_rules! write_uleb128 { ($enc:expr, $value:expr, $fun:ident) => {{ leb128::$fun(&mut $enc.data, $value); Ok(()) - }} + }}; } macro_rules! write_sleb128 { ($enc:expr, $value:expr) => {{ write_signed_leb128(&mut $enc.data, $value as i128); Ok(()) - }} + }}; } impl serialize::Encoder for Encoder { @@ -113,11 +113,7 @@ impl serialize::Encoder for Encoder { #[inline] fn emit_bool(&mut self, v: bool) -> EncodeResult { - self.emit_u8(if v { - 1 - } else { - 0 - }) + self.emit_u8(if v { 1 } else { 0 }) } #[inline] @@ -164,10 +160,7 @@ pub struct Decoder<'a> { impl<'a> Decoder<'a> { #[inline] pub fn new(data: &'a [u8], position: usize) -> Decoder<'a> { - Decoder { - data, - position, - } + Decoder { data, position } } #[inline] @@ -199,22 +192,21 @@ impl<'a> Decoder<'a> { } macro_rules! read_uleb128 { - ($dec:expr, $t:ty, $fun:ident) => ({ - let (value, bytes_read) = leb128::$fun(&$dec.data[$dec.position ..]); + ($dec:expr, $t:ty, $fun:ident) => {{ + let (value, bytes_read) = leb128::$fun(&$dec.data[$dec.position..]); $dec.position += bytes_read; Ok(value) - }) + }}; } macro_rules! read_sleb128 { - ($dec:expr, $t:ty) => ({ + ($dec:expr, $t:ty) => {{ let (value, bytes_read) = read_signed_leb128($dec.data, $dec.position); $dec.position += bytes_read; Ok(value as $t) - }) + }}; } - impl<'a> serialize::Decoder for Decoder<'a> { type Error = String; diff --git a/src/libserialize/serialize.rs b/src/libserialize/serialize.rs index a5f7b4898ae..19283ffc438 100644 --- a/src/libserialize/serialize.rs +++ b/src/libserialize/serialize.rs @@ -6,10 +6,10 @@ Core encoding and decoding interfaces. use std::any; use std::borrow::Cow; +use std::cell::{Cell, RefCell}; use std::marker::PhantomData; use std::path; use std::rc::Rc; -use std::cell::{Cell, RefCell}; use std::sync::Arc; pub trait Encoder { @@ -37,75 +37,109 @@ pub trait Encoder { // Compound types: fn emit_enum<F>(&mut self, _name: &str, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } - fn emit_enum_variant<F>(&mut self, _v_name: &str, v_id: usize, _len: usize, f: F) - -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> + fn emit_enum_variant<F>( + &mut self, + _v_name: &str, + v_id: usize, + _len: usize, + f: F, + ) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_usize(v_id)?; f(self) } fn emit_enum_variant_arg<F>(&mut self, _a_idx: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } - fn emit_enum_struct_variant<F>(&mut self, v_name: &str, v_id: usize, len: usize, f: F) - -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> + fn emit_enum_struct_variant<F>( + &mut self, + v_name: &str, + v_id: usize, + len: usize, + f: F, + ) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_enum_variant(v_name, v_id, len, f) } - fn emit_enum_struct_variant_field<F>(&mut self, _f_name: &str, f_idx: usize, f: F) - -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> + fn emit_enum_struct_variant_field<F>( + &mut self, + _f_name: &str, + f_idx: usize, + f: F, + ) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_enum_variant_arg(f_idx, f) } fn emit_struct<F>(&mut self, _name: &str, _len: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } - fn emit_struct_field<F>(&mut self, _f_name: &str, _f_idx: usize, f: F) - -> Result<(), Self::Error> where F: FnOnce(&mut Self) -> Result<(), Self::Error> + fn emit_struct_field<F>( + &mut self, + _f_name: &str, + _f_idx: usize, + f: F, + ) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } fn emit_tuple<F>(&mut self, _len: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } fn emit_tuple_arg<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } fn emit_tuple_struct<F>(&mut self, _name: &str, len: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_tuple(len, f) } fn emit_tuple_struct_arg<F>(&mut self, f_idx: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_tuple_arg(f_idx, f) } // Specialized types: fn emit_option<F>(&mut self, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_enum("Option", f) } @@ -116,39 +150,45 @@ pub trait Encoder { } fn emit_option_some<F>(&mut self, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_enum_variant("Some", 1, 1, f) } fn emit_seq<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_usize(len)?; f(self) } fn emit_seq_elt<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } fn emit_map<F>(&mut self, len: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { self.emit_usize(len)?; f(self) } fn emit_map_elt_key<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } fn emit_map_elt_val<F>(&mut self, _idx: usize, f: F) -> Result<(), Self::Error> - where F: FnOnce(&mut Self) -> Result<(), Self::Error> + where + F: FnOnce(&mut Self) -> Result<(), Self::Error>, { f(self) } @@ -179,115 +219,140 @@ pub trait Decoder { // Compound types: fn read_enum<T, F>(&mut self, _name: &str, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { f(self) } fn read_enum_variant<T, F>(&mut self, _names: &[&str], mut f: F) -> Result<T, Self::Error> - where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> + where + F: FnMut(&mut Self, usize) -> Result<T, Self::Error>, { let disr = self.read_usize()?; f(self, disr) } fn read_enum_variant_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { f(self) } fn read_enum_struct_variant<T, F>(&mut self, names: &[&str], f: F) -> Result<T, Self::Error> - where F: FnMut(&mut Self, usize) -> Result<T, Self::Error> + where + F: FnMut(&mut Self, usize) -> Result<T, Self::Error>, { self.read_enum_variant(names, f) } - fn read_enum_struct_variant_field<T, F>(&mut self, _f_name: &str, f_idx: usize, f: F) - -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> + fn read_enum_struct_variant_field<T, F>( + &mut self, + _f_name: &str, + f_idx: usize, + f: F, + ) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { self.read_enum_variant_arg(f_idx, f) } fn read_struct<T, F>(&mut self, _s_name: &str, _len: usize, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { f(self) } - fn read_struct_field<T, F>(&mut self, _f_name: &str, _f_idx: usize, f: F) - -> Result<T, Self::Error> where F: FnOnce(&mut Self) -> Result<T, Self::Error> + fn read_struct_field<T, F>( + &mut self, + _f_name: &str, + _f_idx: usize, + f: F, + ) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { f(self) } fn read_tuple<T, F>(&mut self, _len: usize, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { f(self) } fn read_tuple_arg<T, F>(&mut self, _a_idx: usize, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { f(self) } fn read_tuple_struct<T, F>(&mut self, _s_name: &str, len: usize, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { self.read_tuple(len, f) } fn read_tuple_struct_arg<T, F>(&mut self, a_idx: usize, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { self.read_tuple_arg(a_idx, f) } // Specialized types: fn read_option<T, F>(&mut self, mut f: F) -> Result<T, Self::Error> - where F: FnMut(&mut Self, bool) -> Result<T, Self::Error> + where + F: FnMut(&mut Self, bool) -> Result<T, Self::Error>, { self.read_enum("Option", move |this| { - this.read_enum_variant(&["None", "Some"], move |this, idx| { - match idx { - 0 => f(this, false), - 1 => f(this, true), - _ => Err(this.error("read_option: expected 0 for None or 1 for Some")), - } + this.read_enum_variant(&["None", "Some"], move |this, idx| match idx { + 0 => f(this, false), + 1 => f(this, true), + _ => Err(this.error("read_option: expected 0 for None or 1 for Some")), }) }) } fn read_seq<T, F>(&mut self, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>, { let len = self.read_usize()?; f(self, len) } fn read_seq_elt<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { f(self) } fn read_map<T, F>(&mut self, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self, usize) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self, usize) -> Result<T, Self::Error>, { let len = self.read_usize()?; f(self, len) } fn read_map_elt_key<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { f(self) } fn read_map_elt_val<T, F>(&mut self, _idx: usize, f: F) -> Result<T, Self::Error> - where F: FnOnce(&mut Self) -> Result<T, Self::Error> + where + F: FnOnce(&mut Self) -> Result<T, Self::Error>, { f(self) } @@ -563,32 +628,32 @@ impl<T: ?Sized + Encodable> Encodable for Box<T> { } } -impl< T: Decodable> Decodable for Box<T> { +impl<T: Decodable> Decodable for Box<T> { fn decode<D: Decoder>(d: &mut D) -> Result<Box<T>, D::Error> { Ok(box Decodable::decode(d)?) } } -impl< T: Decodable> Decodable for Box<[T]> { +impl<T: Decodable> Decodable for Box<[T]> { fn decode<D: Decoder>(d: &mut D) -> Result<Box<[T]>, D::Error> { let v: Vec<T> = Decodable::decode(d)?; Ok(v.into_boxed_slice()) } } -impl<T:Encodable> Encodable for Rc<T> { +impl<T: Encodable> Encodable for Rc<T> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { (**self).encode(s) } } -impl<T:Decodable> Decodable for Rc<T> { +impl<T: Decodable> Decodable for Rc<T> { fn decode<D: Decoder>(d: &mut D) -> Result<Rc<T>, D::Error> { Ok(Rc::new(Decodable::decode(d)?)) } } -impl<T:Encodable> Encodable for [T] { +impl<T: Encodable> Encodable for [T] { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_seq(self.len(), |s| { for (i, e) in self.iter().enumerate() { @@ -599,7 +664,7 @@ impl<T:Encodable> Encodable for [T] { } } -impl<T:Encodable> Encodable for Vec<T> { +impl<T: Encodable> Encodable for Vec<T> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_seq(self.len(), |s| { for (i, e) in self.iter().enumerate() { @@ -610,7 +675,7 @@ impl<T:Encodable> Encodable for Vec<T> { } } -impl<T:Decodable> Decodable for Vec<T> { +impl<T: Decodable> Decodable for Vec<T> { fn decode<D: Decoder>(d: &mut D) -> Result<Vec<T>, D::Error> { d.read_seq(|d, len| { let mut v = Vec::with_capacity(len); @@ -622,7 +687,10 @@ impl<T:Decodable> Decodable for Vec<T> { } } -impl<'a, T:Encodable> Encodable for Cow<'a, [T]> where [T]: ToOwned<Owned = Vec<T>> { +impl<'a, T: Encodable> Encodable for Cow<'a, [T]> +where + [T]: ToOwned<Owned = Vec<T>>, +{ fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { s.emit_seq(self.len(), |s| { for (i, e) in self.iter().enumerate() { @@ -633,8 +701,9 @@ impl<'a, T:Encodable> Encodable for Cow<'a, [T]> where [T]: ToOwned<Owned = Vec< } } -impl<T:Decodable+ToOwned> Decodable for Cow<'static, [T]> - where [T]: ToOwned<Owned = Vec<T>> +impl<T: Decodable + ToOwned> Decodable for Cow<'static, [T]> +where + [T]: ToOwned<Owned = Vec<T>>, { fn decode<D: Decoder>(d: &mut D) -> Result<Cow<'static, [T]>, D::Error> { d.read_seq(|d, len| { @@ -647,72 +716,45 @@ impl<T:Decodable+ToOwned> Decodable for Cow<'static, [T]> } } - -impl<T:Encodable> Encodable for Option<T> { +impl<T: Encodable> Encodable for Option<T> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { - s.emit_option(|s| { - match *self { - None => s.emit_option_none(), - Some(ref v) => s.emit_option_some(|s| v.encode(s)), - } + s.emit_option(|s| match *self { + None => s.emit_option_none(), + Some(ref v) => s.emit_option_some(|s| v.encode(s)), }) } } -impl<T:Decodable> Decodable for Option<T> { +impl<T: Decodable> Decodable for Option<T> { fn decode<D: Decoder>(d: &mut D) -> Result<Option<T>, D::Error> { - d.read_option(|d, b| { - if b { - Ok(Some(Decodable::decode(d)?)) - } else { - Ok(None) - } - }) + d.read_option(|d, b| if b { Ok(Some(Decodable::decode(d)?)) } else { Ok(None) }) } } impl<T1: Encodable, T2: Encodable> Encodable for Result<T1, T2> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { - s.emit_enum("Result", |s| { - match *self { - Ok(ref v) => { - s.emit_enum_variant("Ok", 0, 1, |s| { - s.emit_enum_variant_arg(0, |s| { - v.encode(s) - }) - }) - } - Err(ref v) => { - s.emit_enum_variant("Err", 1, 1, |s| { - s.emit_enum_variant_arg(0, |s| { - v.encode(s) - }) - }) - } + s.emit_enum("Result", |s| match *self { + Ok(ref v) => { + s.emit_enum_variant("Ok", 0, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s))) + } + Err(ref v) => { + s.emit_enum_variant("Err", 1, 1, |s| s.emit_enum_variant_arg(0, |s| v.encode(s))) } }) } } -impl<T1:Decodable, T2:Decodable> Decodable for Result<T1, T2> { +impl<T1: Decodable, T2: Decodable> Decodable for Result<T1, T2> { fn decode<D: Decoder>(d: &mut D) -> Result<Result<T1, T2>, D::Error> { d.read_enum("Result", |d| { - d.read_enum_variant(&["Ok", "Err"], |d, disr| { - match disr { - 0 => { - Ok(Ok(d.read_enum_variant_arg(0, |d| { - T1::decode(d) - })?)) - } - 1 => { - Ok(Err(d.read_enum_variant_arg(0, |d| { - T2::decode(d) - })?)) - } - _ => { - panic!("Encountered invalid discriminant while \ - decoding `Result`."); - } + d.read_enum_variant(&["Ok", "Err"], |d, disr| match disr { + 0 => Ok(Ok(d.read_enum_variant_arg(0, |d| T1::decode(d))?)), + 1 => Ok(Err(d.read_enum_variant_arg(0, |d| T2::decode(d))?)), + _ => { + panic!( + "Encountered invalid discriminant while \ + decoding `Result`." + ); } }) }) @@ -819,13 +861,13 @@ impl<T: Decodable> Decodable for RefCell<T> { } } -impl<T:Encodable> Encodable for Arc<T> { +impl<T: Encodable> Encodable for Arc<T> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { (**self).encode(s) } } -impl<T:Decodable> Decodable for Arc<T> { +impl<T: Decodable> Decodable for Arc<T> { fn decode<D: Decoder>(d: &mut D) -> Result<Arc<T>, D::Error> { Ok(Arc::new(Decodable::decode(d)?)) } @@ -848,11 +890,13 @@ pub trait SpecializationError { impl<E> SpecializationError for E { default fn not_found<S, T: ?Sized>(trait_name: &'static str, method_name: &'static str) -> E { - panic!("missing specialization: `<{} as {}<{}>>::{}` not overridden", - any::type_name::<S>(), - trait_name, - any::type_name::<T>(), - method_name); + panic!( + "missing specialization: `<{} as {}<{}>>::{}` not overridden", + any::type_name::<S>(), + trait_name, + any::type_name::<T>(), + method_name + ); } } diff --git a/src/libserialize/tests/json.rs b/src/libserialize/tests/json.rs index 898168252e5..c16426b5919 100644 --- a/src/libserialize/tests/json.rs +++ b/src/libserialize/tests/json.rs @@ -2,21 +2,23 @@ extern crate serialize as rustc_serialize; -use rustc_serialize::{Encodable, Decodable}; -use rustc_serialize::json; -use json::Json::*; -use json::ErrorCode::*; -use json::ParserError::*; use json::DecoderError::*; +use json::ErrorCode::*; +use json::Json::*; use json::JsonEvent::*; -use json::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser, StackElement, - Decoder, Encoder, EncoderError}; +use json::ParserError::*; +use json::{ + from_str, DecodeResult, Decoder, DecoderError, Encoder, EncoderError, Json, JsonEvent, Parser, + StackElement, +}; +use rustc_serialize::json; +use rustc_serialize::{Decodable, Encodable}; -use Animal::*; -use std::{i64, u64, f32, f64}; -use std::io::prelude::*; use std::collections::BTreeMap; +use std::io::prelude::*; use std::string; +use std::{f32, f64, i64, u64}; +use Animal::*; #[derive(RustcDecodable, Eq, PartialEq, Debug)] struct OptionData { @@ -25,7 +27,7 @@ struct OptionData { #[test] fn test_decode_option_none() { - let s ="{}"; + let s = "{}"; let obj: OptionData = json::decode(s).unwrap(); assert_eq!(obj, OptionData { opt: None }); } @@ -39,16 +41,20 @@ fn test_decode_option_some() { #[test] fn test_decode_option_malformed() { - check_err::<OptionData>("{ \"opt\": [] }", - ExpectedError("Number".to_string(), "[]".to_string())); - check_err::<OptionData>("{ \"opt\": false }", - ExpectedError("Number".to_string(), "false".to_string())); + check_err::<OptionData>( + "{ \"opt\": [] }", + ExpectedError("Number".to_string(), "[]".to_string()), + ); + check_err::<OptionData>( + "{ \"opt\": false }", + ExpectedError("Number".to_string(), "false".to_string()), + ); } #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)] enum Animal { Dog, - Frog(string::String, isize) + Frog(string::String, isize), } #[derive(PartialEq, RustcEncodable, RustcDecodable, Debug)] @@ -68,9 +74,11 @@ fn mk_object(items: &[(string::String, Json)]) -> Json { for item in items { match *item { - (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); }, + (ref key, ref value) => { + d.insert((*key).clone(), (*value).clone()); + } } - }; + } Object(d) } @@ -158,13 +166,10 @@ fn test_write_array() { ]" ); - let long_test_array = Array(vec![ - Boolean(false), - Null, - Array(vec![String("foo\nbar".to_string()), F64(3.5)])]); + let long_test_array = + Array(vec![Boolean(false), Null, Array(vec![String("foo\nbar".to_string()), F64(3.5)])]); - assert_eq!(long_test_array.to_string(), - "[false,null,[\"foo\\nbar\",3.5]]"); + assert_eq!(long_test_array.to_string(), "[false,null,[\"foo\\nbar\",3.5]]"); assert_eq!( long_test_array.pretty().to_string(), "\ @@ -184,12 +189,7 @@ fn test_write_object() { assert_eq!(mk_object(&[]).to_string(), "{}"); assert_eq!(mk_object(&[]).pretty().to_string(), "{}"); - assert_eq!( - mk_object(&[ - ("a".to_string(), Boolean(true)) - ]).to_string(), - "{\"a\":true}" - ); + assert_eq!(mk_object(&[("a".to_string(), Boolean(true))]).to_string(), "{\"a\":true}"); assert_eq!( mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(), "\ @@ -198,12 +198,13 @@ fn test_write_object() { }" ); - let complex_obj = mk_object(&[ - ("b".to_string(), Array(vec![ - mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]), - mk_object(&[("d".to_string(), String("".to_string()))]) - ])) - ]); + let complex_obj = mk_object(&[( + "b".to_string(), + Array(vec![ + mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]), + mk_object(&[("d".to_string(), String("".to_string()))]), + ]), + )]); assert_eq!( complex_obj.to_string(), @@ -231,10 +232,13 @@ fn test_write_object() { let a = mk_object(&[ ("a".to_string(), Boolean(true)), - ("b".to_string(), Array(vec![ - mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]), - mk_object(&[("d".to_string(), String("".to_string()))]) - ])) + ( + "b".to_string(), + Array(vec![ + mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]), + mk_object(&[("d".to_string(), String("".to_string()))]), + ]), + ), ]); // We can't compare the strings directly because the object fields be @@ -246,14 +250,8 @@ fn test_write_object() { #[test] fn test_write_enum() { let animal = Dog; - assert_eq!( - json::as_json(&animal).to_string(), - "\"Dog\"" - ); - assert_eq!( - json::as_pretty_json(&animal).to_string(), - "\"Dog\"" - ); + assert_eq!(json::as_json(&animal).to_string(), "\"Dog\""); + assert_eq!(json::as_pretty_json(&animal).to_string(), "\"Dog\""); let animal = Frog("Henry".to_string(), 349); assert_eq!( @@ -273,13 +271,13 @@ fn test_write_enum() { } macro_rules! check_encoder_for_simple { - ($value:expr, $expected:expr) => ({ + ($value:expr, $expected:expr) => {{ let s = json::as_json(&$value).to_string(); assert_eq!(s, $expected); let s = json::as_pretty_json(&$value).to_string(); assert_eq!(s, $expected); - }) + }}; } #[test] @@ -306,22 +304,22 @@ fn test_write_char() { #[test] fn test_trailing_characters() { - assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5))); - assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5))); + assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5))); + assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5))); assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6))); - assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2))); - assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3))); - assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3))); + assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2))); + assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3))); + assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3))); } #[test] fn test_read_identifiers() { - assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2))); - assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2))); assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2))); - assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3))); + assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3))); assert_eq!(from_str("null"), Ok(Null)); assert_eq!(from_str("true"), Ok(Boolean(true))); @@ -345,13 +343,13 @@ fn test_decode_identifiers() { #[test] fn test_read_number() { - assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1))); - assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1))); + assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1))); + assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1))); assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1))); - assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2))); - assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2))); - assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3))); - assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3))); + assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2))); + assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2))); + assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3))); + assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3))); assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4))); assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20))); @@ -407,13 +405,12 @@ fn test_decode_numbers() { assert_eq!(v, i64::MAX); let res: DecodeResult<i64> = json::decode("765.25"); - assert_eq!(res, Err(ExpectedError("Integer".to_string(), - "765.25".to_string()))); + assert_eq!(res, Err(ExpectedError("Integer".to_string(), "765.25".to_string()))); } #[test] fn test_read_str() { - assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2))); + assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2))); assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5))); assert_eq!(from_str("\"\""), Ok(String("".to_string()))); @@ -430,15 +427,17 @@ fn test_read_str() { #[test] fn test_decode_str() { - let s = [("\"\"", ""), - ("\"foo\"", "foo"), - ("\"\\\"\"", "\""), - ("\"\\b\"", "\x08"), - ("\"\\n\"", "\n"), - ("\"\\r\"", "\r"), - ("\"\\t\"", "\t"), - ("\"\\u12ab\"", "\u{12ab}"), - ("\"\\uAB12\"", "\u{AB12}")]; + let s = [ + ("\"\"", ""), + ("\"foo\"", "foo"), + ("\"\\\"\"", "\""), + ("\"\\b\"", "\x08"), + ("\"\\n\"", "\n"), + ("\"\\r\"", "\r"), + ("\"\\t\"", "\t"), + ("\"\\u12ab\"", "\u{12ab}"), + ("\"\\uAB12\"", "\u{AB12}"), + ]; for &(i, o) in &s { let v: string::String = json::decode(i).unwrap(); @@ -448,23 +447,20 @@ fn test_decode_str() { #[test] fn test_read_array() { - assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2))); - assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3))); - assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4))); - assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2))); + assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3))); + assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4))); + assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4))); assert_eq!(from_str("[]"), Ok(Array(vec![]))); assert_eq!(from_str("[ ]"), Ok(Array(vec![]))); assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)]))); assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)]))); assert_eq!(from_str("[null]"), Ok(Array(vec![Null]))); - assert_eq!(from_str("[3, 1]"), - Ok(Array(vec![U64(3), U64(1)]))); - assert_eq!(from_str("\n[3, 2]\n"), - Ok(Array(vec![U64(3), U64(2)]))); - assert_eq!(from_str("[2, [4, 1]]"), - Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])]))); + assert_eq!(from_str("[3, 1]"), Ok(Array(vec![U64(3), U64(1)]))); + assert_eq!(from_str("\n[3, 2]\n"), Ok(Array(vec![U64(3), U64(2)]))); + assert_eq!(from_str("[2, [4, 1]]"), Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])]))); } #[test] @@ -506,57 +502,58 @@ fn test_decode_tuple_malformed_length() { #[test] fn test_read_object() { - assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2))); - assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3))); - assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2))); + assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2))); + assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3))); + assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2))); assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6))); - assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5))); + assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5))); assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6))); - assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6))); - assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6))); - assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7))); - assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8))); - assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8))); + assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6))); + assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6))); + assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7))); + assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8))); + assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8))); assert_eq!(from_str("{}").unwrap(), mk_object(&[])); - assert_eq!(from_str("{\"a\": 3}").unwrap(), - mk_object(&[("a".to_string(), U64(3))])); - - assert_eq!(from_str( - "{ \"a\": null, \"b\" : true }").unwrap(), - mk_object(&[ - ("a".to_string(), Null), - ("b".to_string(), Boolean(true))])); - assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(), - mk_object(&[ - ("a".to_string(), Null), - ("b".to_string(), Boolean(true))])); - assert_eq!(from_str( - "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(), - mk_object(&[ - ("a".to_string(), F64(1.0)), - ("b".to_string(), Array(vec![Boolean(true)])) - ])); - assert_eq!(from_str( - "{\ + assert_eq!(from_str("{\"a\": 3}").unwrap(), mk_object(&[("a".to_string(), U64(3))])); + + assert_eq!( + from_str("{ \"a\": null, \"b\" : true }").unwrap(), + mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))]) + ); + assert_eq!( + from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(), + mk_object(&[("a".to_string(), Null), ("b".to_string(), Boolean(true))]) + ); + assert_eq!( + from_str("{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(), + mk_object(&[("a".to_string(), F64(1.0)), ("b".to_string(), Array(vec![Boolean(true)]))]) + ); + assert_eq!( + from_str( + "{\ \"a\": 1.0, \ \"b\": [\ true,\ \"foo\\nbar\", \ { \"c\": {\"d\": null} } \ ]\ - }").unwrap(), - mk_object(&[ - ("a".to_string(), F64(1.0)), - ("b".to_string(), Array(vec![ - Boolean(true), - String("foo\nbar".to_string()), - mk_object(&[ - ("c".to_string(), mk_object(&[("d".to_string(), Null)])) - ]) - ])) - ])); + }" + ) + .unwrap(), + mk_object(&[ + ("a".to_string(), F64(1.0)), + ( + "b".to_string(), + Array(vec![ + Boolean(true), + String("foo\nbar".to_string()), + mk_object(&[("c".to_string(), mk_object(&[("d".to_string(), Null)]))]) + ]) + ) + ]) + ); } #[test] @@ -570,18 +567,14 @@ fn test_decode_struct() { let v: Outer = json::decode(s).unwrap(); assert_eq!( v, - Outer { - inner: vec![ - Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] } - ] - } + Outer { inner: vec![Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] }] } ); } #[derive(RustcDecodable)] struct FloatStruct { f: f64, - a: Vec<f64> + a: Vec<f64>, } #[test] fn test_decode_struct_with_nan() { @@ -623,8 +616,7 @@ fn test_decode_map() { #[test] fn test_multiline_errors() { - assert_eq!(from_str("{\n \"foo\":\n \"bar\""), - Err(SyntaxError(EOFWhileParsingObject, 3, 8))); + assert_eq!(from_str("{\n \"foo\":\n \"bar\""), Err(SyntaxError(EOFWhileParsingObject, 3, 8))); } #[derive(RustcDecodable)] @@ -633,23 +625,21 @@ struct DecodeStruct { x: f64, y: bool, z: string::String, - w: Vec<DecodeStruct> + w: Vec<DecodeStruct>, } #[derive(RustcDecodable)] enum DecodeEnum { A(f64), - B(string::String) + B(string::String), } fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) { let res: DecodeResult<T> = match from_str(to_parse) { Err(e) => Err(ParseError(e)), - Ok(json) => Decodable::decode(&mut Decoder::new(json)) + Ok(json) => Decodable::decode(&mut Decoder::new(json)), }; match res { - Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`", - to_parse, expected), - Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}", - to_parse, e), + Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`", to_parse, expected), + Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}", to_parse, e), Err(e) => { assert_eq!(e, expected); } @@ -658,54 +648,68 @@ fn check_err<T: Decodable>(to_parse: &'static str, expected: DecoderError) { #[test] fn test_decode_errors_struct() { check_err::<DecodeStruct>("[]", ExpectedError("Object".to_string(), "[]".to_string())); - check_err::<DecodeStruct>("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}", - ExpectedError("Number".to_string(), "true".to_string())); - check_err::<DecodeStruct>("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}", - ExpectedError("Boolean".to_string(), "[]".to_string())); - check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}", - ExpectedError("String".to_string(), "{}".to_string())); - check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}", - ExpectedError("Array".to_string(), "null".to_string())); - check_err::<DecodeStruct>("{\"x\": 1, \"y\": true, \"z\": \"\"}", - MissingFieldError("w".to_string())); + check_err::<DecodeStruct>( + "{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}", + ExpectedError("Number".to_string(), "true".to_string()), + ); + check_err::<DecodeStruct>( + "{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}", + ExpectedError("Boolean".to_string(), "[]".to_string()), + ); + check_err::<DecodeStruct>( + "{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}", + ExpectedError("String".to_string(), "{}".to_string()), + ); + check_err::<DecodeStruct>( + "{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}", + ExpectedError("Array".to_string(), "null".to_string()), + ); + check_err::<DecodeStruct>( + "{\"x\": 1, \"y\": true, \"z\": \"\"}", + MissingFieldError("w".to_string()), + ); } #[test] fn test_decode_errors_enum() { - check_err::<DecodeEnum>("{}", - MissingFieldError("variant".to_string())); - check_err::<DecodeEnum>("{\"variant\": 1}", - ExpectedError("String".to_string(), "1".to_string())); - check_err::<DecodeEnum>("{\"variant\": \"A\"}", - MissingFieldError("fields".to_string())); - check_err::<DecodeEnum>("{\"variant\": \"A\", \"fields\": null}", - ExpectedError("Array".to_string(), "null".to_string())); - check_err::<DecodeEnum>("{\"variant\": \"C\", \"fields\": []}", - UnknownVariantError("C".to_string())); + check_err::<DecodeEnum>("{}", MissingFieldError("variant".to_string())); + check_err::<DecodeEnum>( + "{\"variant\": 1}", + ExpectedError("String".to_string(), "1".to_string()), + ); + check_err::<DecodeEnum>("{\"variant\": \"A\"}", MissingFieldError("fields".to_string())); + check_err::<DecodeEnum>( + "{\"variant\": \"A\", \"fields\": null}", + ExpectedError("Array".to_string(), "null".to_string()), + ); + check_err::<DecodeEnum>( + "{\"variant\": \"C\", \"fields\": []}", + UnknownVariantError("C".to_string()), + ); } #[test] -fn test_find(){ +fn test_find() { let json_value = from_str("{\"dog\" : \"cat\"}").unwrap(); let found_str = json_value.find("dog"); assert!(found_str.unwrap().as_string().unwrap() == "cat"); } #[test] -fn test_find_path(){ +fn test_find_path() { let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap(); let found_str = json_value.find_path(&["dog", "cat", "mouse"]); assert!(found_str.unwrap().as_string().unwrap() == "cheese"); } #[test] -fn test_search(){ +fn test_search() { let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap(); let found_str = json_value.search("mouse").and_then(|j| j.as_string()); assert!(found_str.unwrap() == "cheese"); } #[test] -fn test_index(){ +fn test_index() { let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap(); let ref array = json_value["animals"]; assert_eq!(array[0].as_string().unwrap(), "dog"); @@ -714,26 +718,26 @@ fn test_index(){ } #[test] -fn test_is_object(){ +fn test_is_object() { let json_value = from_str("{}").unwrap(); assert!(json_value.is_object()); } #[test] -fn test_as_object(){ +fn test_as_object() { let json_value = from_str("{}").unwrap(); let json_object = json_value.as_object(); assert!(json_object.is_some()); } #[test] -fn test_is_array(){ +fn test_is_array() { let json_value = from_str("[1, 2, 3]").unwrap(); assert!(json_value.is_array()); } #[test] -fn test_as_array(){ +fn test_as_array() { let json_value = from_str("[1, 2, 3]").unwrap(); let json_array = json_value.as_array(); let expected_length = 3; @@ -741,13 +745,13 @@ fn test_as_array(){ } #[test] -fn test_is_string(){ +fn test_is_string() { let json_value = from_str("\"dog\"").unwrap(); assert!(json_value.is_string()); } #[test] -fn test_as_string(){ +fn test_as_string() { let json_value = from_str("\"dog\"").unwrap(); let json_str = json_value.as_string(); let expected_str = "dog"; @@ -755,13 +759,13 @@ fn test_as_string(){ } #[test] -fn test_is_number(){ +fn test_is_number() { let json_value = from_str("12").unwrap(); assert!(json_value.is_number()); } #[test] -fn test_is_i64(){ +fn test_is_i64() { let json_value = from_str("-12").unwrap(); assert!(json_value.is_i64()); @@ -773,7 +777,7 @@ fn test_is_i64(){ } #[test] -fn test_is_u64(){ +fn test_is_u64() { let json_value = from_str("12").unwrap(); assert!(json_value.is_u64()); @@ -785,7 +789,7 @@ fn test_is_u64(){ } #[test] -fn test_is_f64(){ +fn test_is_f64() { let json_value = from_str("12").unwrap(); assert!(!json_value.is_f64()); @@ -800,34 +804,34 @@ fn test_is_f64(){ } #[test] -fn test_as_i64(){ +fn test_as_i64() { let json_value = from_str("-12").unwrap(); let json_num = json_value.as_i64(); assert_eq!(json_num, Some(-12)); } #[test] -fn test_as_u64(){ +fn test_as_u64() { let json_value = from_str("12").unwrap(); let json_num = json_value.as_u64(); assert_eq!(json_num, Some(12)); } #[test] -fn test_as_f64(){ +fn test_as_f64() { let json_value = from_str("12.0").unwrap(); let json_num = json_value.as_f64(); assert_eq!(json_num, Some(12f64)); } #[test] -fn test_is_boolean(){ +fn test_is_boolean() { let json_value = from_str("false").unwrap(); assert!(json_value.is_boolean()); } #[test] -fn test_as_boolean(){ +fn test_as_boolean() { let json_value = from_str("false").unwrap(); let json_bool = json_value.as_boolean(); let expected_bool = false; @@ -835,13 +839,13 @@ fn test_as_boolean(){ } #[test] -fn test_is_null(){ +fn test_is_null() { let json_value = from_str("null").unwrap(); assert!(json_value.is_null()); } #[test] -fn test_as_null(){ +fn test_as_null() { let json_value = from_str("null").unwrap(); let json_null = json_value.as_null(); let expected_null = (); @@ -850,8 +854,8 @@ fn test_as_null(){ #[test] fn test_encode_hashmap_with_numeric_key() { - use std::str::from_utf8; use std::collections::HashMap; + use std::str::from_utf8; let mut hm: HashMap<usize, bool> = HashMap::new(); hm.insert(1, true); let mut mem_buf = Vec::new(); @@ -865,8 +869,8 @@ fn test_encode_hashmap_with_numeric_key() { #[test] fn test_prettyencode_hashmap_with_numeric_key() { - use std::str::from_utf8; use std::collections::HashMap; + use std::str::from_utf8; let mut hm: HashMap<usize, bool> = HashMap::new(); hm.insert(1, true); let mut mem_buf = Vec::new(); @@ -880,8 +884,8 @@ fn test_prettyencode_hashmap_with_numeric_key() { #[test] fn test_prettyencoder_indent_level_param() { - use std::str::from_utf8; use std::collections::BTreeMap; + use std::str::from_utf8; let mut tree = BTreeMap::new(); @@ -891,12 +895,12 @@ fn test_prettyencoder_indent_level_param() { let json = Array( // The following layout below should look a lot like // the pretty-printed JSON (indent * x) - vec! - ( // 0x + vec![ + // 0x String("greetings".to_string()), // 1x - Object(tree), // 1x + 2x + 2x + 1x - ) // 0x - // End JSON array (7 lines) + Object(tree), // 1x + 2x + 2x + 1x + ], // 0x + // End JSON array (7 lines) ); // Helper function for counting indents @@ -908,8 +912,7 @@ fn test_prettyencoder_indent_level_param() { // Test up to 4 spaces of indents (more?) for i in 0..4 { let mut writer = Vec::new(); - write!(&mut writer, "{}", - json::as_pretty_json(&json).indent(i)).unwrap(); + write!(&mut writer, "{}", json::as_pretty_json(&json).indent(i)).unwrap(); let printed = from_utf8(&writer[..]).unwrap(); @@ -953,7 +956,7 @@ fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() { let json_str = "{\"1\":true}"; let json_obj = match from_str(json_str) { Err(_) => panic!("Unable to parse json_str: {:?}", json_str), - Ok(o) => o + Ok(o) => o, }; let mut decoder = Decoder::new(json_obj); let _hm: HashMap<usize, bool> = Decodable::decode(&mut decoder).unwrap(); @@ -965,28 +968,29 @@ fn test_hashmap_with_numeric_key_will_error_with_string_keys() { let json_str = "{\"a\":true}"; let json_obj = match from_str(json_str) { Err(_) => panic!("Unable to parse json_str: {:?}", json_str), - Ok(o) => o + Ok(o) => o, }; let mut decoder = Decoder::new(json_obj); let result: Result<HashMap<usize, bool>, DecoderError> = Decodable::decode(&mut decoder); assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string()))); } -fn assert_stream_equal(src: &str, - expected: Vec<(JsonEvent, Vec<StackElement<'_>>)>) { +fn assert_stream_equal(src: &str, expected: Vec<(JsonEvent, Vec<StackElement<'_>>)>) { let mut parser = Parser::new(src.chars()); let mut i = 0; loop { let evt = match parser.next() { Some(e) => e, - None => { break; } + None => { + break; + } }; let (ref expected_evt, ref expected_stack) = expected[i]; if !parser.stack().is_equal_to(expected_stack) { panic!("Parser stack is not equal to {:?}", expected_stack); } assert_eq!(&evt, expected_evt); - i+=1; + i += 1; } } #[test] @@ -994,26 +998,23 @@ fn test_streaming_parser() { assert_stream_equal( r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#, vec![ - (ObjectStart, vec![]), - (StringValue("bar".to_string()), vec![StackElement::Key("foo")]), - (ArrayStart, vec![StackElement::Key("array")]), - (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]), - (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]), - (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]), - (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]), - (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]), - (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]), - (ArrayEnd, vec![StackElement::Key("array")]), - (ArrayStart, vec![StackElement::Key("idents")]), - (NullValue, vec![StackElement::Key("idents"), - StackElement::Index(0)]), - (BooleanValue(true), vec![StackElement::Key("idents"), - StackElement::Index(1)]), - (BooleanValue(false), vec![StackElement::Key("idents"), - StackElement::Index(2)]), - (ArrayEnd, vec![StackElement::Key("idents")]), - (ObjectEnd, vec![]), - ] + (ObjectStart, vec![]), + (StringValue("bar".to_string()), vec![StackElement::Key("foo")]), + (ArrayStart, vec![StackElement::Key("array")]), + (U64Value(0), vec![StackElement::Key("array"), StackElement::Index(0)]), + (U64Value(1), vec![StackElement::Key("array"), StackElement::Index(1)]), + (U64Value(2), vec![StackElement::Key("array"), StackElement::Index(2)]), + (U64Value(3), vec![StackElement::Key("array"), StackElement::Index(3)]), + (U64Value(4), vec![StackElement::Key("array"), StackElement::Index(4)]), + (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]), + (ArrayEnd, vec![StackElement::Key("array")]), + (ArrayStart, vec![StackElement::Key("idents")]), + (NullValue, vec![StackElement::Key("idents"), StackElement::Index(0)]), + (BooleanValue(true), vec![StackElement::Key("idents"), StackElement::Index(1)]), + (BooleanValue(false), vec![StackElement::Key("idents"), StackElement::Index(2)]), + (ArrayEnd, vec![StackElement::Key("idents")]), + (ObjectEnd, vec![]), + ], ); } fn last_event(src: &str) -> JsonEvent { @@ -1029,50 +1030,47 @@ fn last_event(src: &str) -> JsonEvent { #[test] fn test_read_object_streaming() { - assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3))); - assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2))); + assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3))); + assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2))); assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6))); - assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5))); + assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5))); assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6))); - assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6))); - assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6))); - assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7))); - assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8))); - assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8))); + assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6))); + assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6))); + assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7))); + assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8))); + assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8))); assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8))); - assert_stream_equal( - "{}", - vec![(ObjectStart, vec![]), (ObjectEnd, vec![])] - ); + assert_stream_equal("{}", vec![(ObjectStart, vec![]), (ObjectEnd, vec![])]); assert_stream_equal( "{\"a\": 3}", vec![ - (ObjectStart, vec![]), - (U64Value(3), vec![StackElement::Key("a")]), - (ObjectEnd, vec![]), - ] + (ObjectStart, vec![]), + (U64Value(3), vec![StackElement::Key("a")]), + (ObjectEnd, vec![]), + ], ); assert_stream_equal( "{ \"a\": null, \"b\" : true }", vec![ - (ObjectStart, vec![]), - (NullValue, vec![StackElement::Key("a")]), - (BooleanValue(true), vec![StackElement::Key("b")]), - (ObjectEnd, vec![]), - ] + (ObjectStart, vec![]), + (NullValue, vec![StackElement::Key("a")]), + (BooleanValue(true), vec![StackElement::Key("b")]), + (ObjectEnd, vec![]), + ], ); assert_stream_equal( "{\"a\" : 1.0 ,\"b\": [ true ]}", vec![ - (ObjectStart, vec![]), - (F64Value(1.0), vec![StackElement::Key("a")]), - (ArrayStart, vec![StackElement::Key("b")]), - (BooleanValue(true),vec![StackElement::Key("b"), StackElement::Index(0)]), - (ArrayEnd, vec![StackElement::Key("b")]), - (ObjectEnd, vec![]), - ] + (ObjectStart, vec![]), + (F64Value(1.0), vec![StackElement::Key("a")]), + (ArrayStart, vec![StackElement::Key("b")]), + (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]), + (ArrayEnd, vec![StackElement::Key("b")]), + (ObjectEnd, vec![]), + ], ); assert_stream_equal( r#"{ @@ -1084,120 +1082,109 @@ fn test_read_object_streaming() { ] }"#, vec![ - (ObjectStart, vec![]), - (F64Value(1.0), vec![StackElement::Key("a")]), - (ArrayStart, vec![StackElement::Key("b")]), - (BooleanValue(true), vec![StackElement::Key("b"), - StackElement::Index(0)]), - (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"), - StackElement::Index(1)]), - (ObjectStart, vec![StackElement::Key("b"), - StackElement::Index(2)]), - (ObjectStart, vec![StackElement::Key("b"), - StackElement::Index(2), - StackElement::Key("c")]), - (NullValue, vec![StackElement::Key("b"), - StackElement::Index(2), - StackElement::Key("c"), - StackElement::Key("d")]), - (ObjectEnd, vec![StackElement::Key("b"), - StackElement::Index(2), - StackElement::Key("c")]), - (ObjectEnd, vec![StackElement::Key("b"), - StackElement::Index(2)]), - (ArrayEnd, vec![StackElement::Key("b")]), - (ObjectEnd, vec![]), - ] + (ObjectStart, vec![]), + (F64Value(1.0), vec![StackElement::Key("a")]), + (ArrayStart, vec![StackElement::Key("b")]), + (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]), + ( + StringValue("foo\nbar".to_string()), + vec![StackElement::Key("b"), StackElement::Index(1)], + ), + (ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2)]), + ( + ObjectStart, + vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")], + ), + ( + NullValue, + vec![ + StackElement::Key("b"), + StackElement::Index(2), + StackElement::Key("c"), + StackElement::Key("d"), + ], + ), + ( + ObjectEnd, + vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")], + ), + (ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2)]), + (ArrayEnd, vec![StackElement::Key("b")]), + (ObjectEnd, vec![]), + ], ); } #[test] fn test_read_array_streaming() { - assert_stream_equal( - "[]", - vec![ - (ArrayStart, vec![]), - (ArrayEnd, vec![]), - ] - ); - assert_stream_equal( - "[ ]", - vec![ - (ArrayStart, vec![]), - (ArrayEnd, vec![]), - ] - ); + assert_stream_equal("[]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]); + assert_stream_equal("[ ]", vec![(ArrayStart, vec![]), (ArrayEnd, vec![])]); assert_stream_equal( "[true]", vec![ - (ArrayStart, vec![]), - (BooleanValue(true), vec![StackElement::Index(0)]), - (ArrayEnd, vec![]), - ] + (ArrayStart, vec![]), + (BooleanValue(true), vec![StackElement::Index(0)]), + (ArrayEnd, vec![]), + ], ); assert_stream_equal( "[ false ]", vec![ - (ArrayStart, vec![]), - (BooleanValue(false), vec![StackElement::Index(0)]), - (ArrayEnd, vec![]), - ] + (ArrayStart, vec![]), + (BooleanValue(false), vec![StackElement::Index(0)]), + (ArrayEnd, vec![]), + ], ); assert_stream_equal( "[null]", - vec![ - (ArrayStart, vec![]), - (NullValue, vec![StackElement::Index(0)]), - (ArrayEnd, vec![]), - ] + vec![(ArrayStart, vec![]), (NullValue, vec![StackElement::Index(0)]), (ArrayEnd, vec![])], ); assert_stream_equal( "[3, 1]", vec![ - (ArrayStart, vec![]), - (U64Value(3), vec![StackElement::Index(0)]), - (U64Value(1), vec![StackElement::Index(1)]), - (ArrayEnd, vec![]), - ] + (ArrayStart, vec![]), + (U64Value(3), vec![StackElement::Index(0)]), + (U64Value(1), vec![StackElement::Index(1)]), + (ArrayEnd, vec![]), + ], ); assert_stream_equal( "\n[3, 2]\n", vec![ - (ArrayStart, vec![]), - (U64Value(3), vec![StackElement::Index(0)]), - (U64Value(2), vec![StackElement::Index(1)]), - (ArrayEnd, vec![]), - ] + (ArrayStart, vec![]), + (U64Value(3), vec![StackElement::Index(0)]), + (U64Value(2), vec![StackElement::Index(1)]), + (ArrayEnd, vec![]), + ], ); assert_stream_equal( "[2, [4, 1]]", vec![ - (ArrayStart, vec![]), - (U64Value(2), vec![StackElement::Index(0)]), - (ArrayStart, vec![StackElement::Index(1)]), - (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]), - (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]), - (ArrayEnd, vec![StackElement::Index(1)]), - (ArrayEnd, vec![]), - ] + (ArrayStart, vec![]), + (U64Value(2), vec![StackElement::Index(0)]), + (ArrayStart, vec![StackElement::Index(1)]), + (U64Value(4), vec![StackElement::Index(1), StackElement::Index(0)]), + (U64Value(1), vec![StackElement::Index(1), StackElement::Index(1)]), + (ArrayEnd, vec![StackElement::Index(1)]), + (ArrayEnd, vec![]), + ], ); - assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2))); - - assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2))); - assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3))); - assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4))); - assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2))); + assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2))); + assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3))); + assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4))); + assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4))); } #[test] fn test_trailing_characters_streaming() { - assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5))); - assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5))); + assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5))); + assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5))); assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6))); - assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2))); - assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3))); - assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3))); + assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2))); + assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3))); + assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3))); } #[test] fn test_read_identifiers_streaming() { @@ -1205,18 +1192,18 @@ fn test_read_identifiers_streaming() { assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true))); assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false))); - assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2))); - assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4))); + assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2))); assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2))); - assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3))); + assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2))); + assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3))); } #[test] fn test_to_json() { - use std::collections::{HashMap,BTreeMap}; use json::ToJson; + use std::collections::{BTreeMap, HashMap}; let array2 = Array(vec![U64(1), U64(2)]); let array3 = Array(vec![U64(1), U64(2), U64(3)]); @@ -1279,6 +1266,6 @@ fn test_encode_hashmap_with_arbitrary_key() { let result = hm.encode(&mut encoder); match result.unwrap_err() { EncoderError::BadHashmapKey => (), - _ => panic!("expected bad hash map key") + _ => panic!("expected bad hash map key"), } } diff --git a/src/libserialize/tests/leb128.rs b/src/libserialize/tests/leb128.rs index 4eb4397fecc..bf5afb409f8 100644 --- a/src/libserialize/tests/leb128.rs +++ b/src/libserialize/tests/leb128.rs @@ -2,7 +2,7 @@ extern crate serialize as rustc_serialize; use rustc_serialize::leb128::*; macro_rules! impl_test_unsigned_leb128 { - ($test_name:ident, $write_fn_name:ident, $read_fn_name:ident, $int_ty:ident) => ( + ($test_name:ident, $write_fn_name:ident, $read_fn_name:ident, $int_ty:ident) => { #[test] fn $test_name() { let mut stream = Vec::new(); @@ -14,13 +14,13 @@ macro_rules! impl_test_unsigned_leb128 { let mut position = 0; for x in 0..62 { let expected = (3u64 << x) as $int_ty; - let (actual, bytes_read) = $read_fn_name(&stream[position ..]); + let (actual, bytes_read) = $read_fn_name(&stream[position..]); assert_eq!(expected, actual); position += bytes_read; } assert_eq!(stream.len(), position); } - ) + }; } impl_test_unsigned_leb128!(test_u16_leb128, write_u16_leb128, read_u16_leb128, u16); diff --git a/src/libserialize/tests/opaque.rs b/src/libserialize/tests/opaque.rs index 592bc090399..aa099bb8a36 100644 --- a/src/libserialize/tests/opaque.rs +++ b/src/libserialize/tests/opaque.rs @@ -2,8 +2,8 @@ extern crate serialize as rustc_serialize; -use rustc_serialize::{Encodable, Decodable}; -use rustc_serialize::opaque::{Encoder, Decoder}; +use rustc_serialize::opaque::{Decoder, Encoder}; +use rustc_serialize::{Decodable, Encodable}; use std::fmt::Debug; #[derive(PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)] @@ -29,7 +29,6 @@ struct Struct { q: Option<u32>, } - fn check_round_trip<T: Encodable + Decodable + PartialEq + Debug>(values: Vec<T>) { let mut encoder = Encoder::new(Vec::new()); @@ -144,13 +143,15 @@ fn test_char() { #[test] fn test_string() { - let vec = vec!["abcbuÖeiovÄnameÜavmpßvmea€µsbpnvapeapmaebn".to_string(), - "abcbuÖganeiovÄnameÜavmpßvmea€µsbpnvapeapmaebn".to_string(), - "abcbuÖganeiovÄnameÜavmpßvmea€µsbpapmaebn".to_string(), - "abcbuÖganeiovÄnameÜavmpßvmeabpnvapeapmaebn".to_string(), - "abcbuÖganeiÄnameÜavmpßvmea€µsbpnvapeapmaebn".to_string(), - "abcbuÖganeiovÄnameÜavmpßvmea€µsbpmaebn".to_string(), - "abcbuÖganeiovÄnameÜavmpßvmea€µnvapeapmaebn".to_string()]; + let vec = vec![ + "abcbuÖeiovÄnameÜavmpßvmea€µsbpnvapeapmaebn".to_string(), + "abcbuÖganeiovÄnameÜavmpßvmea€µsbpnvapeapmaebn".to_string(), + "abcbuÖganeiovÄnameÜavmpßvmea€µsbpapmaebn".to_string(), + "abcbuÖganeiovÄnameÜavmpßvmeabpnvapeapmaebn".to_string(), + "abcbuÖganeiÄnameÜavmpßvmea€µsbpnvapeapmaebn".to_string(), + "abcbuÖganeiovÄnameÜavmpßvmea€µsbpmaebn".to_string(), + "abcbuÖganeiovÄnameÜavmpßvmea€µnvapeapmaebn".to_string(), + ]; check_round_trip(vec); } @@ -182,75 +183,65 @@ fn test_option() { #[test] fn test_struct() { check_round_trip(vec![Struct { - a: (), - b: 10, - c: 11, - d: 12, - e: 13, - f: 14, - - g: 15, - h: 16, - i: 17, - j: 18, - k: 19, - - l: 'x', - m: "abc".to_string(), - n: 20.5, - o: 21.5, - p: false, - q: None, - }]); + a: (), + b: 10, + c: 11, + d: 12, + e: 13, + f: 14, + + g: 15, + h: 16, + i: 17, + j: 18, + k: 19, + + l: 'x', + m: "abc".to_string(), + n: 20.5, + o: 21.5, + p: false, + q: None, + }]); check_round_trip(vec![Struct { - a: (), - b: 101, - c: 111, - d: 121, - e: 131, - f: 141, - - g: -15, - h: -16, - i: -17, - j: -18, - k: -19, - - l: 'y', - m: "def".to_string(), - n: -20.5, - o: -21.5, - p: true, - q: Some(1234567), - }]); + a: (), + b: 101, + c: 111, + d: 121, + e: 131, + f: 141, + + g: -15, + h: -16, + i: -17, + j: -18, + k: -19, + + l: 'y', + m: "def".to_string(), + n: -20.5, + o: -21.5, + p: true, + q: Some(1234567), + }]); } #[derive(PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)] enum Enum { Variant1, Variant2(usize, f32), - Variant3 { - a: i32, - b: char, - c: bool, - }, + Variant3 { a: i32, b: char, c: bool }, } #[test] fn test_enum() { - check_round_trip(vec![Enum::Variant1, - Enum::Variant2(1, 2.5), - Enum::Variant3 { - a: 3, - b: 'b', - c: false, - }, - Enum::Variant3 { - a: -4, - b: 'f', - c: true, - }]); + check_round_trip(vec![ + Enum::Variant1, + Enum::Variant2(1, 2.5), + Enum::Variant3 { a: 3, b: 'b', c: false }, + Enum::Variant3 { a: -4, b: 'f', c: true }, + ]); } #[test] |
