Skip to content
This repository was archived by the owner on Aug 15, 2021. It is now read-only.

Suggestion: turn off "small heuristic" of rustfmt #193

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# see https://editorconfig.org for more options, and setup instructions for yours editor

[*.rs]
indent_style = space
indent_size = 4
1 change: 1 addition & 0 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
use_small_heuristics = "Off"
66 changes: 33 additions & 33 deletions src/de.rs
Original file line number Diff line number Diff line change
@@ -266,23 +266,17 @@ where

fn parse_u16(&mut self) -> Result<u16> {
let mut buf = [0; 2];
self.read
.read_into(&mut buf)
.map(|()| u16::from_be_bytes(buf))
self.read.read_into(&mut buf).map(|()| u16::from_be_bytes(buf))
}

fn parse_u32(&mut self) -> Result<u32> {
let mut buf = [0; 4];
self.read
.read_into(&mut buf)
.map(|()| u32::from_be_bytes(buf))
self.read.read_into(&mut buf).map(|()| u32::from_be_bytes(buf))
}

fn parse_u64(&mut self) -> Result<u64> {
let mut buf = [0; 8];
self.read
.read_into(&mut buf)
.map(|()| u64::from_be_bytes(buf))
self.read.read_into(&mut buf).map(|()| u64::from_be_bytes(buf))
}

fn parse_bytes<V>(&mut self, len: usize, visitor: V) -> Result<V::Value>
@@ -355,10 +349,7 @@ where
}
} else {
// An overflow would have occured.
Err(Error::syntax(
ErrorCode::LengthOutOfRange,
self.read.offset(),
))
Err(Error::syntax(ErrorCode::LengthOutOfRange, self.read.offset()))
}
}

@@ -440,7 +431,10 @@ where
V: de::Visitor<'de>,
{
self.recursion_checked(|de| {
let value = visitor.visit_seq(SeqAccess { de, len: &mut len })?;
let value = visitor.visit_seq(SeqAccess {
de,
len: &mut len,
})?;

if len != 0 {
Err(de.error(ErrorCode::TrailingData))
@@ -455,7 +449,9 @@ where
V: de::Visitor<'de>,
{
self.recursion_checked(|de| {
let value = visitor.visit_seq(IndefiniteSeqAccess { de })?;
let value = visitor.visit_seq(IndefiniteSeqAccess {
de,
})?;
match de.next()? {
Some(0xff) => Ok(value),
Some(_) => Err(de.error(ErrorCode::TrailingData)),
@@ -512,7 +508,10 @@ where
{
self.recursion_checked(|de| {
let value = visitor.visit_enum(VariantAccess {
seq: SeqAccess { de, len: &mut len },
seq: SeqAccess {
de,
len: &mut len,
},
})?;

if len != 0 {
@@ -554,7 +553,9 @@ where
{
self.recursion_checked(|de| {
let value = visitor.visit_enum(VariantAccess {
seq: IndefiniteSeqAccess { de },
seq: IndefiniteSeqAccess {
de,
},
})?;
match de.next()? {
Some(0xff) => Ok(value),
@@ -868,7 +869,9 @@ where
if !self.accept_standard_enums && !self.accept_legacy_enums {
return Err(self.error(ErrorCode::WrongEnumFormat));
}
visitor.visit_enum(UnitVariantAccess { de: self })
visitor.visit_enum(UnitVariantAccess {
de: self,
})
}
}
}
@@ -1103,30 +1106,21 @@ where
where
T: de::DeserializeSeed<'de>,
{
Err(de::Error::invalid_type(
de::Unexpected::UnitVariant,
&"newtype variant",
))
Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"newtype variant"))
}

fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
Err(de::Error::invalid_type(
de::Unexpected::UnitVariant,
&"tuple variant",
))
Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"tuple variant"))
}

fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
Err(de::Error::invalid_type(
de::Unexpected::UnitVariant,
&"struct variant",
))
Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"struct variant"))
}
}

@@ -1190,7 +1184,9 @@ where
where
V: de::Visitor<'de>,
{
let seed = StructVariantSeed { visitor };
let seed = StructVariantSeed {
visitor,
};
match self.seq.next_element_seed(seed) {
Ok(Some(variant)) => Ok(variant),
Ok(None) => Err(self.seq.error(ErrorCode::ArrayTooShort)),
@@ -1346,15 +1342,19 @@ where
where
V: de::Visitor<'de>,
{
let seed = StructVariantSeed { visitor };
let seed = StructVariantSeed {
visitor,
};
self.map.next_value_seed(seed)
}

fn struct_variant<V>(mut self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
let seed = StructVariantSeed { visitor };
let seed = StructVariantSeed {
visitor,
};
self.map.next_value_seed(seed)
}
}
5 changes: 4 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
@@ -35,7 +35,10 @@ impl Error {
}

pub(crate) fn syntax(code: ErrorCode, offset: u64) -> Error {
Error(ErrorImpl { code, offset })
Error(ErrorImpl {
code,
offset,
})
}

#[cfg(feature = "std")]
30 changes: 9 additions & 21 deletions src/read.rs
Original file line number Diff line number Diff line change
@@ -153,7 +153,10 @@ where
/// Creates a new CBOR input source to read from a std::io input stream.
pub fn new(reader: R) -> IoRead<R> {
IoRead {
reader: OffsetReader { reader, offset: 0 },
reader: OffsetReader {
reader,
offset: 0,
},
scratch: vec![],
ch: None,
}
@@ -227,10 +230,7 @@ where

match transfer_result {
Ok(r) if r == n => Ok(()),
Ok(_) => Err(Error::syntax(
ErrorCode::EofWhileParsingValue,
self.offset(),
)),
Ok(_) => Err(Error::syntax(ErrorCode::EofWhileParsingValue, self.offset())),
Err(e) => Err(Error::io(e)),
}
}
@@ -318,10 +318,7 @@ impl<'a> SliceRead<'a> {
fn end(&self, n: usize) -> Result<usize> {
match self.index.checked_add(n) {
Some(end) if end <= self.slice.len() => Ok(end),
_ => Err(Error::syntax(
ErrorCode::EofWhileParsingValue,
self.slice.len() as u64,
)),
_ => Err(Error::syntax(ErrorCode::EofWhileParsingValue, self.slice.len() as u64)),
}
}
}
@@ -334,10 +331,7 @@ impl<'a> Offset for SliceRead<'a> {
}
}

#[cfg(all(
any(feature = "std", feature = "alloc"),
not(feature = "unsealed_read_write")
))]
#[cfg(all(any(feature = "std", feature = "alloc"), not(feature = "unsealed_read_write")))]
impl<'a> private::Sealed for SliceRead<'a> {}

#[cfg(any(feature = "std", feature = "alloc"))]
@@ -431,10 +425,7 @@ impl<'a, 'b> SliceReadFixed<'a, 'b> {
fn end(&self, n: usize) -> Result<usize> {
match self.index.checked_add(n) {
Some(end) if end <= self.slice.len() => Ok(end),
_ => Err(Error::syntax(
ErrorCode::EofWhileParsingValue,
self.slice.len() as u64,
)),
_ => Err(Error::syntax(ErrorCode::EofWhileParsingValue, self.slice.len() as u64)),
}
}

@@ -551,10 +542,7 @@ impl<'a> MutSliceRead<'a> {
fn end(&self, n: usize) -> Result<usize> {
match self.index.checked_add(n) {
Some(end) if end <= self.slice.len() => Ok(end),
_ => Err(Error::syntax(
ErrorCode::EofWhileParsingValue,
self.slice.len() as u64,
)),
_ => Err(Error::syntax(ErrorCode::EofWhileParsingValue, self.slice.len() as u64)),
}
}
}
19 changes: 11 additions & 8 deletions src/ser.rs
Original file line number Diff line number Diff line change
@@ -193,9 +193,7 @@ where
false
}
None => {
self.writer
.write_all(&[major << 5 | 31])
.map_err(|e| e.into())?;
self.writer.write_all(&[major << 5 | 31]).map_err(|e| e.into())?;
true
}
};
@@ -224,7 +222,11 @@ where

#[inline]
fn serialize_bool(self, value: bool) -> Result<()> {
let value = if value { 0xf5 } else { 0xf4 };
let value = if value {
0xf5
} else {
0xf4
};
self.writer.write_all(&[value]).map_err(|e| e.into())
}

@@ -352,9 +354,7 @@ where
#[inline]
fn serialize_str(self, value: &str) -> Result<()> {
self.write_u64(3, value.len() as u64)?;
self.writer
.write_all(value.as_bytes())
.map_err(|e| e.into())
self.writer.write_all(value.as_bytes()).map_err(|e| e.into())
}

#[inline]
@@ -494,7 +494,10 @@ where
#[inline]
fn serialize_struct(self, _name: &'static str, len: usize) -> Result<StructSerializer<'a, W>> {
self.write_u64(5, len as u64)?;
Ok(StructSerializer { ser: self, idx: 0 })
Ok(StructSerializer {
ser: self,
idx: 0,
})
}

#[inline]
8 changes: 5 additions & 3 deletions src/tags.rs
Original file line number Diff line number Diff line change
@@ -23,7 +23,10 @@ pub struct Tagged<T> {
impl<T> Tagged<T> {
/// Create a new tagged value
pub fn new(tag: Option<u64>, value: T) -> Self {
Self { tag, value }
Self {
tag,
value,
}
}
}

@@ -42,8 +45,7 @@ fn untagged<T>(value: T) -> Tagged<T> {

macro_rules! delegate {
($name: ident, $type: ty) => {
fn $name<E: serde::de::Error>(self, v: $type) -> Result<Self::Value, E>
{
fn $name<E: serde::de::Error>(self, v: $type) -> Result<Self::Value, E> {
T::deserialize(v.into_deserializer()).map(untagged)
}
};
3 changes: 1 addition & 2 deletions src/value/ser.rs
Original file line number Diff line number Diff line change
@@ -392,8 +392,7 @@ impl serde::ser::SerializeStructVariant for SerializeStructVariant {
where
T: Serialize,
{
self.map
.insert(Value::from(String::from(key)), to_value(&value)?);
self.map.insert(Value::from(String::from(key)), to_value(&value)?);
Ok(())
}

10 changes: 5 additions & 5 deletions src/write.rs
Original file line number Diff line number Diff line change
@@ -102,10 +102,7 @@ impl Write for Vec<u8> {
}
}

#[cfg(all(
any(feature = "std", feature = "alloc"),
not(feature = "unsealed_read_write")
))]
#[cfg(all(any(feature = "std", feature = "alloc"), not(feature = "unsealed_read_write")))]
impl private::Sealed for Vec<u8> {}

#[cfg(not(feature = "std"))]
@@ -142,7 +139,10 @@ pub struct SliceWrite<'a> {
impl<'a> SliceWrite<'a> {
/// Wraps a mutable slice so it can be used as a `Write`.
pub fn new(slice: &'a mut [u8]) -> SliceWrite<'a> {
SliceWrite { slice, index: 0 }
SliceWrite {
slice,
index: 0,
}
}

/// Returns the number of bytes written to the underlying slice.
6 changes: 2 additions & 4 deletions tests/canonical.rs
Original file line number Diff line number Diff line change
@@ -34,10 +34,8 @@ mod std_tests {

#[test]
fn string_canonical_sort_order() {
let expected = ["", "a", "b", "aa"]
.iter()
.map(|s| Value::Text(s.to_string()))
.collect::<Vec<_>>();
let expected =
["", "a", "b", "aa"].iter().map(|s| Value::Text(s.to_string())).collect::<Vec<_>>();

let mut sorted = expected.clone();
sorted.sort();
97 changes: 25 additions & 72 deletions tests/de.rs
Original file line number Diff line number Diff line change
@@ -37,7 +37,10 @@ fn test_indefinite_object() {
a: u64,
b: [u64; 2],
}
let expected = Foo { a: 1, b: [2, 3] };
let expected = Foo {
a: 1,
b: [2, 3],
};
let actual: Foo =
de::from_slice_with_scratch(b"\xbfaa\x01ab\x9f\x02\x03\xff\xff", &mut []).unwrap();
assert_eq!(expected, actual);
@@ -119,11 +122,7 @@ mod std_tests {
let value: error::Result<Value> = de::from_slice(b"\x83\x01\x02\x03");
assert_eq!(
value.unwrap(),
Value::Array(vec![
Value::Integer(1),
Value::Integer(2),
Value::Integer(3)
])
Value::Array(vec![Value::Integer(1), Value::Integer(2), Value::Integer(3)])
);
}

@@ -134,10 +133,7 @@ mod std_tests {
value.unwrap(),
Value::Array(vec![
Value::Integer(1),
Value::Array(vec![
Value::Integer(2),
Value::Array(vec![Value::Integer(3)])
])
Value::Array(vec![Value::Integer(2), Value::Array(vec![Value::Integer(3)])])
])
);
}
@@ -171,22 +167,15 @@ mod std_tests {
let value: error::Result<Value> = de::from_slice(b"\x9f\x01\x02\x03\xff");
assert_eq!(
value.unwrap(),
Value::Array(vec![
Value::Integer(1),
Value::Integer(2),
Value::Integer(3)
])
Value::Array(vec![Value::Integer(1), Value::Integer(2), Value::Integer(3)])
);
}

#[test]
fn test_indefinite_string() {
let value: error::Result<Value> =
de::from_slice(b"\x7f\x65Mary \x64Had \x62a \x67Little \x60\x64Lamb\xff");
assert_eq!(
value.unwrap(),
Value::Text("Mary Had a Little Lamb".to_owned())
);
assert_eq!(value.unwrap(), Value::Text("Mary Had a Little Lamb".to_owned()));
}

#[test]
@@ -314,10 +303,7 @@ mod std_tests {
let slice = b"\xbf\x67\x6d\x65\x73\x73\x61\x67\x65\x64\x70\x6f\x6e\x67\xff";
let value: Value = de::from_slice(slice).unwrap();
let mut map = BTreeMap::new();
map.insert(
Value::Text("message".to_string()),
Value::Text("pong".to_string()),
);
map.insert(Value::Text("message".to_string()), Value::Text("pong".to_string()));
assert_eq!(value, Value::Map(map))
}

@@ -327,10 +313,7 @@ mod std_tests {

// 0.1% chance of not catching failure
for _ in 0..10 {
assert_eq!(
&to_vec(&de::from_slice::<Value>(expected).unwrap()).unwrap(),
expected
);
assert_eq!(&to_vec(&de::from_slice::<Value>(expected).unwrap()).unwrap(), expected);
}
}

@@ -339,10 +322,7 @@ mod std_tests {
let slice = b"\x01\x66foobar";
let mut it = Deserializer::from_slice(slice).into_iter::<Value>();
assert_eq!(Value::Integer(1), it.next().unwrap().unwrap());
assert_eq!(
Value::Text("foobar".to_string()),
it.next().unwrap().unwrap()
);
assert_eq!(Value::Text("foobar".to_string()), it.next().unwrap().unwrap());
assert!(it.next().is_none());
}

@@ -381,10 +361,7 @@ mod std_tests {
fn crash() {
let file = include_bytes!("crash.cbor");
let value_result: error::Result<Value> = de::from_slice(file);
assert_eq!(
value_result.unwrap_err().classify(),
serde_cbor::error::Category::Syntax
);
assert_eq!(value_result.unwrap_err().classify(), serde_cbor::error::Category::Syntax);
}

fn from_slice_stream<'a, T>(slice: &'a [u8]) -> error::Result<(&'a [u8], T)>
@@ -501,7 +478,10 @@ mod std_tests {
Unit,
NewType(i32),
Tuple(String, bool),
Struct { x: i32, y: i32 },
Struct {
x: i32,
y: i32,
},
}

// This is the format used in serde >= 0.10
@@ -520,16 +500,10 @@ mod std_tests {
assert_eq!(value, Enum::NewType(10));
let value: error::Result<(&[u8], Enum)> =
from_slice_stream_options(&v[..], Options::default().no_standard());
assert_eq!(
value.unwrap_err().classify(),
serde_cbor::error::Category::Syntax
);
assert_eq!(value.unwrap_err().classify(), serde_cbor::error::Category::Syntax);
let value: error::Result<(&[u8], Enum)> =
from_slice_stream_options(&v[..], Options::default().no_standard().no_legacy());
assert_eq!(
value.unwrap_err().classify(),
serde_cbor::error::Category::Syntax
);
assert_eq!(value.unwrap_err().classify(), serde_cbor::error::Category::Syntax);
// Serialization of Enum::Unit
let v: Vec<u8> = vec![
0x64, 0x55, 0x6e, 0x69, 0x74, // utf8 string: Unit
@@ -544,10 +518,7 @@ mod std_tests {
assert_eq!(value, Enum::Unit);
let value: error::Result<(&[u8], Enum)> =
from_slice_stream_options(&v[..], Options::default().no_legacy().no_standard());
assert_eq!(
value.unwrap_err().classify(),
serde_cbor::error::Category::Syntax
);
assert_eq!(value.unwrap_err().classify(), serde_cbor::error::Category::Syntax);

// This is the format used in serde <= 0.9
let v: Vec<u8> = vec![
@@ -560,19 +531,13 @@ mod std_tests {
assert_eq!(value, Enum::NewType(10));
let value: error::Result<(&[u8], Enum)> =
from_slice_stream_options(&v[..], Options::default().no_legacy());
assert_eq!(
value.unwrap_err().classify(),
serde_cbor::error::Category::Syntax
);
assert_eq!(value.unwrap_err().classify(), serde_cbor::error::Category::Syntax);
let value: error::Result<(&[u8], Enum)> =
from_slice_stream_options(&v[..], Options::default().no_standard());
assert_eq!(value.unwrap().1, Enum::NewType(10));
let value: error::Result<(&[u8], Enum)> =
from_slice_stream_options(&v[..], Options::default().no_standard().no_legacy());
assert_eq!(
value.unwrap_err().classify(),
serde_cbor::error::Category::Syntax
);
assert_eq!(value.unwrap_err().classify(), serde_cbor::error::Category::Syntax);
}

#[test]
@@ -612,10 +577,7 @@ mod std_tests {
);
let value: error::Result<(&[u8], User)> =
from_slice_stream_options(&v[..], Options::default().no_named());
assert_eq!(
value.unwrap_err().classify(),
serde_cbor::error::Category::Syntax
);
assert_eq!(value.unwrap_err().classify(), serde_cbor::error::Category::Syntax);

// unpacked - indefinite length
let v: Vec<u8> = vec![
@@ -647,10 +609,7 @@ mod std_tests {
);
let value: error::Result<(&[u8], User)> =
from_slice_stream_options(&v[..], Options::default().no_named());
assert_eq!(
value.unwrap_err().classify(),
serde_cbor::error::Category::Syntax
);
assert_eq!(value.unwrap_err().classify(), serde_cbor::error::Category::Syntax);

// packed
let v: Vec<u8> = vec![
@@ -680,10 +639,7 @@ mod std_tests {
);
let value: error::Result<(&[u8], User)> =
from_slice_stream_options(&v[..], Options::default().no_packed());
assert_eq!(
value.unwrap_err().classify(),
serde_cbor::error::Category::Syntax
);
assert_eq!(value.unwrap_err().classify(), serde_cbor::error::Category::Syntax);

// packed - indefinite length
let v: Vec<u8> = vec![
@@ -714,10 +670,7 @@ mod std_tests {
);
let value: error::Result<(&[u8], User)> =
from_slice_stream_options(&v[..], Options::default().no_packed());
assert_eq!(
value.unwrap_err().classify(),
serde_cbor::error::Category::Syntax
);
assert_eq!(value.unwrap_err().classify(), serde_cbor::error::Category::Syntax);
}

use serde_cbor::{de::from_slice, ser::to_vec_packed};
66 changes: 42 additions & 24 deletions tests/enum.rs
Original file line number Diff line number Diff line change
@@ -57,7 +57,9 @@ mod std_tests {

#[test]
fn test_enum() {
let enum_struct = EnumStruct { e: Enum::B };
let enum_struct = EnumStruct {
e: Enum::B,
};
let raw = &to_vec(&enum_struct).unwrap();
println!("raw enum {:?}", raw);
let re: EnumStruct = from_slice(raw).unwrap();
@@ -78,7 +80,9 @@ mod std_tests {

#[test]
fn test_repr_enum() {
let repr_enum_struct = ReprEnumStruct { e: ReprEnum::B };
let repr_enum_struct = ReprEnumStruct {
e: ReprEnum::B,
};
let re: ReprEnumStruct = from_slice(&to_vec(&repr_enum_struct).unwrap()).unwrap();
assert_eq!(repr_enum_struct, re);
}
@@ -87,7 +91,10 @@ mod std_tests {
enum DataEnum {
A(u32),
B(bool, u8),
C { x: u8, y: String },
C {
x: u8,
y: String,
},
}

#[test]
@@ -111,14 +118,8 @@ mod std_tests {
fn test_serialize() {
assert_eq!(to_vec_legacy(&Enum::A).unwrap(), &[97, 65]);
assert_eq!(to_vec_legacy(&Enum::B).unwrap(), &[97, 66]);
assert_eq!(
to_vec_legacy(&DataEnum::A(42)).unwrap(),
&[130, 97, 65, 24, 42]
);
assert_eq!(
to_vec_legacy(&DataEnum::B(true, 9)).unwrap(),
&[131, 97, 66, 245, 9]
);
assert_eq!(to_vec_legacy(&DataEnum::A(42)).unwrap(), &[130, 97, 65, 24, 42]);
assert_eq!(to_vec_legacy(&DataEnum::B(true, 9)).unwrap(), &[131, 97, 66, 245, 9]);
}

#[test]
@@ -147,7 +148,10 @@ mod std_tests {
Empty,
Number(i32),
Flag(String, bool),
Point { x: i32, y: i32 },
Point {
x: i32,
y: i32,
},
}

#[test]
@@ -173,14 +177,15 @@ mod std_tests {
assert_eq!(flag_s, flag_vec_s);

// struct-variants serialize like ["<variant>", {struct..}]
let point_s = to_vec_legacy(&Bar::Point { x: 5, y: -5 }).unwrap();
let point_s = to_vec_legacy(&Bar::Point {
x: 5,
y: -5,
})
.unwrap();
let mut struct_map = BTreeMap::new();
struct_map.insert(Value::Text("x".to_string()), Value::Integer(5));
struct_map.insert(Value::Text("y".to_string()), Value::Integer(-5));
let point_vec = vec![
Value::Text("Point".to_string()),
Value::Map(struct_map.clone()),
];
let point_vec = vec![Value::Text("Point".to_string()), Value::Map(struct_map.clone())];
let point_vec_s = to_vec_legacy(&point_vec).unwrap();
assert_eq!(point_s, point_vec_s);

@@ -200,15 +205,16 @@ mod std_tests {
// multi-element tuple variants serialize like {"<variant>": [values..]}
let flag_s = to_vec(&Bar::Flag("foo".to_string(), true)).unwrap();
let mut flag_map = BTreeMap::new();
flag_map.insert(
"Flag",
vec![Value::Text("foo".to_string()), Value::Bool(true)],
);
flag_map.insert("Flag", vec![Value::Text("foo".to_string()), Value::Bool(true)]);
let flag_map_s = to_vec(&flag_map).unwrap();
assert_eq!(flag_s, flag_map_s);

// struct-variants serialize like {"<variant>", {struct..}}
let point_s = to_vec(&Bar::Point { x: 5, y: -5 }).unwrap();
let point_s = to_vec(&Bar::Point {
x: 5,
y: -5,
})
.unwrap();
let mut point_map = BTreeMap::new();
point_map.insert("Point", Value::Map(struct_map));
let point_map_s = to_vec(&point_map).unwrap();
@@ -229,8 +235,20 @@ mod std_tests {
assert_eq!(Bar::Flag("foo".to_string(), true), flag_map_ds);

let point_vec_ds = from_slice(&point_vec_s).unwrap();
assert_eq!(Bar::Point { x: 5, y: -5 }, point_vec_ds);
assert_eq!(
Bar::Point {
x: 5,
y: -5
},
point_vec_ds
);
let point_map_ds = from_slice(&point_map_s).unwrap();
assert_eq!(Bar::Point { x: 5, y: -5 }, point_map_ds);
assert_eq!(
Bar::Point {
x: 5,
y: -5
},
point_map_ds
);
}
}
29 changes: 7 additions & 22 deletions tests/ser.rs
Original file line number Diff line number Diff line change
@@ -98,16 +98,9 @@ mod std_tests {
fn test_object_object_keys() {
use std::iter::FromIterator;
let mut object = BTreeMap::new();
let keys = vec![
vec!["a"],
vec!["b"],
vec!["c"],
vec!["d"],
vec!["aa"],
vec!["a", "aa"],
]
.into_iter()
.map(|v| BTreeMap::from_iter(v.into_iter().map(|s| (s.to_owned(), ()))));
let keys = vec![vec!["a"], vec!["b"], vec!["c"], vec!["d"], vec!["aa"], vec!["a", "aa"]]
.into_iter()
.map(|v| BTreeMap::from_iter(v.into_iter().map(|s| (s.to_owned(), ()))));

for key in keys {
object.insert(key, ());
@@ -202,19 +195,15 @@ mod std_tests {
// Very short byte strings have 1-byte headers
let short = vec![0, 1, 2, 255];
let mut short_s = Vec::new();
serde_cbor::Serializer::new(&mut short_s)
.serialize_bytes(&short)
.unwrap();
serde_cbor::Serializer::new(&mut short_s).serialize_bytes(&short).unwrap();
assert_eq!(&short_s[..], [0x44, 0, 1, 2, 255]);

// byte strings > 23 bytes have 2-byte headers
let medium = vec![
0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 255,
];
let mut medium_s = Vec::new();
serde_cbor::Serializer::new(&mut medium_s)
.serialize_bytes(&medium)
.unwrap();
serde_cbor::Serializer::new(&mut medium_s).serialize_bytes(&medium).unwrap();
assert_eq!(
&medium_s[..],
[
@@ -226,18 +215,14 @@ mod std_tests {
// byte strings > 256 bytes have 3-byte headers
let long_vec = (0..256).map(|i| (i & 0xFF) as u8).collect::<Vec<_>>();
let mut long_s = Vec::new();
serde_cbor::Serializer::new(&mut long_s)
.serialize_bytes(&long_vec)
.unwrap();
serde_cbor::Serializer::new(&mut long_s).serialize_bytes(&long_vec).unwrap();
assert_eq!(&long_s[0..3], [0x59, 1, 0]);
assert_eq!(&long_s[3..], &long_vec[..]);

// byte strings > 2^16 bytes have 5-byte headers
let very_long_vec = (0..65536).map(|i| (i & 0xFF) as u8).collect::<Vec<_>>();
let mut very_long_s = Vec::new();
serde_cbor::Serializer::new(&mut very_long_s)
.serialize_bytes(&very_long_vec)
.unwrap();
serde_cbor::Serializer::new(&mut very_long_s).serialize_bytes(&very_long_vec).unwrap();
assert_eq!(&very_long_s[0..5], [0x5a, 0, 1, 0, 0]);
assert_eq!(&very_long_s[5..], &very_long_vec[..]);

34 changes: 5 additions & 29 deletions tests/std_types.rs
Original file line number Diff line number Diff line change
@@ -52,11 +52,7 @@ mod std_tests {
fn $name() {
let expr: $ty = $expr;
let mut serialized = to_binary($s);
assert_eq!(
to_vec(&expr).expect("ser1 works"),
serialized,
"serialization differs"
);
assert_eq!(to_vec(&expr).expect("ser1 works"), serialized, "serialization differs");
let parsed: $ty = from_slice(&serialized[..]).expect("de1 works");
assert_eq!(parsed, expr, "parsed result differs");
let packed = &to_vec_packed(&expr).expect("serializing packed")[..];
@@ -96,12 +92,7 @@ mod std_tests {
testcase!(test_f64_neg_infinity, f64, -::std::f64::INFINITY, "f9fc00");
testcase!(test_char_null, char, '\x00', "6100");
testcase!(test_char_broken_heart, char, '💔', "64f09f9294");
testcase!(
test_str_pangram_de,
String,
"aâø↓é".to_owned(),
"6a61c3a2c3b8e28693c3a9"
);
testcase!(test_str_pangram_de, String, "aâø↓é".to_owned(), "6a61c3a2c3b8e28693c3a9");
testcase!(test_unit, (), (), "f6");

#[derive(Debug, PartialEq, Deserialize, Serialize)]
@@ -110,12 +101,7 @@ mod std_tests {

#[derive(Debug, PartialEq, Deserialize, Serialize)]
struct NewtypeStruct(bool);
testcase!(
test_newtype_struct,
NewtypeStruct,
NewtypeStruct(true),
"f5"
);
testcase!(test_newtype_struct, NewtypeStruct, NewtypeStruct(true), "f5");

testcase!(test_option_none, Option<u8>, None, "f6");
testcase!(test_option_some, Option<u8>, Some(42), "182a");
@@ -163,24 +149,14 @@ mod std_tests {
}

testcase!(test_color_enum, Color, Color::Blue, "64426c7565");
testcase!(
test_color_enum_transparent,
Color,
Color::Other(42),
"a1654f74686572182a"
);
testcase!(test_color_enum_transparent, Color, Color::Other(42), "a1654f74686572182a");
testcase!(
test_color_enum_with_alpha,
Color,
Color::Alpha(234567, 60),
"a165416c706861821a00039447183c"
);
testcase!(test_i128_a, i128, -1i128, "20");
testcase!(
test_i128_b,
i128,
-18446744073709551616i128,
"3BFFFFFFFFFFFFFFFF"
);
testcase!(test_i128_b, i128, -18446744073709551616i128, "3BFFFFFFFFFFFFFFFF");
testcase!(test_u128, u128, 17, "11");
}
5 changes: 1 addition & 4 deletions tests/tags.rs
Original file line number Diff line number Diff line change
@@ -4,10 +4,7 @@ mod tagtests {
use serde_cbor::{from_slice, to_vec};

fn decode_hex(s: &str) -> std::result::Result<Vec<u8>, std::num::ParseIntError> {
(0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16))
.collect()
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16)).collect()
}

// get bytes from http://cbor.me/ trees
10 changes: 5 additions & 5 deletions tests/value.rs
Original file line number Diff line number Diff line change
@@ -70,10 +70,7 @@ mod std_tests {
panic!()
}

for ((k1, v1), (k2, v2)) in as_object(&value)
.iter()
.zip(as_object(&data_de_value).iter())
{
for ((k1, v1), (k2, v2)) in as_object(&value).iter().zip(as_object(&data_de_value).iter()) {
assert_eq!(k1, k2);
assert_eq!(v1, v2);
}
@@ -92,7 +89,10 @@ mod std_tests {
// Test whether the packed format works.
// Field names should not be serialized,
// instead field indizes are serialized.
let value = SmallStruct { spam: 17, eggs: 42 };
let value = SmallStruct {
spam: 17,
eggs: 42,
};
let data = serde_cbor::ser::to_vec_packed(&value).unwrap();
let reference = b"\xa2\x00\x11\x01\x18\x2a";
assert_eq!(data, reference);