1 #[macro_use]
2 extern crate serde_derive;
3
4 extern crate bincode;
5 #[macro_use]
6 extern crate serde;
7 extern crate serde_bytes;
8
9 use std::borrow::Cow;
10 use std::collections::HashMap;
11 use std::fmt::{self, Debug};
12 use std::result::Result as StdResult;
13
14 use bincode::{
15 deserialize, deserialize_from, deserialize_in_place, serialize, serialized_size,
16 DefaultOptions, ErrorKind, Options, Result,
17 };
18 use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor};
19
20 const LEN_SIZE: u64 = 8;
21
the_same_impl<V, O>(element: V, options: &mut O) where V: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Debug + 'static, O: Options,22 fn the_same_impl<V, O>(element: V, options: &mut O)
23 where
24 V: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Debug + 'static,
25 O: Options,
26 {
27 let size = options.serialized_size(&element).unwrap();
28
29 {
30 let encoded = options.serialize(&element).unwrap();
31 let decoded: V = options.deserialize(&encoded[..]).unwrap();
32 let decoded_reader = options.deserialize_from(&mut &encoded[..]).unwrap();
33
34 assert_eq!(element, decoded);
35 assert_eq!(element, decoded_reader);
36 assert_eq!(size, encoded.len() as u64);
37 }
38 }
39
the_same<V>(element: V) where V: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Debug + Clone + 'static,40 fn the_same<V>(element: V)
41 where
42 V: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Debug + Clone + 'static,
43 {
44 // add a new macro which calls the previous when you add a new option set
45 macro_rules! all_endians {
46 ($element:expr, $options:expr) => {
47 the_same_impl($element.clone(), &mut $options.with_native_endian());
48 the_same_impl($element.clone(), &mut $options.with_big_endian());
49 the_same_impl($element.clone(), &mut $options.with_little_endian());
50 };
51 }
52
53 macro_rules! all_integer_encodings {
54 ($element:expr, $options:expr) => {
55 all_endians!($element, $options.with_fixint_encoding());
56 all_endians!($element, $options.with_varint_encoding());
57 };
58 }
59
60 all_integer_encodings!(element, DefaultOptions::new());
61 }
62
63 #[test]
test_numbers()64 fn test_numbers() {
65 // unsigned positive
66 the_same(5u8);
67 the_same(5u16);
68 the_same(5u32);
69 the_same(5u64);
70 the_same(5usize);
71 // signed positive
72 the_same(5i8);
73 the_same(5i16);
74 the_same(5i32);
75 the_same(5i64);
76 the_same(5isize);
77 // signed negative
78 the_same(-5i8);
79 the_same(-5i16);
80 the_same(-5i32);
81 the_same(-5i64);
82 the_same(-5isize);
83 // floating
84 the_same(-100f32);
85 the_same(0f32);
86 the_same(5f32);
87 the_same(-100f64);
88 the_same(5f64);
89 }
90
91 serde_if_integer128! {
92 #[test]
93 fn test_numbers_128bit() {
94 // unsigned positive
95 the_same(5u128);
96 the_same(u128::max_value());
97 // signed positive
98 the_same(5i128);
99 the_same(i128::max_value());
100 // signed negative
101 the_same(-5i128);
102 the_same(i128::min_value());
103 }
104 }
105
106 #[test]
test_string()107 fn test_string() {
108 the_same("".to_string());
109 the_same("a".to_string());
110 }
111
112 #[test]
test_tuple()113 fn test_tuple() {
114 the_same((1isize,));
115 the_same((1isize, 2isize, 3isize));
116 the_same((1isize, "foo".to_string(), ()));
117 }
118
119 #[test]
test_basic_struct()120 fn test_basic_struct() {
121 #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
122 struct Easy {
123 x: isize,
124 s: String,
125 y: usize,
126 }
127 the_same(Easy {
128 x: -4,
129 s: "foo".to_string(),
130 y: 10,
131 });
132 }
133
134 #[test]
test_nested_struct()135 fn test_nested_struct() {
136 #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
137 struct Easy {
138 x: isize,
139 s: String,
140 y: usize,
141 }
142 #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
143 struct Nest {
144 f: Easy,
145 b: usize,
146 s: Easy,
147 }
148
149 the_same(Nest {
150 f: Easy {
151 x: -1,
152 s: "foo".to_string(),
153 y: 20,
154 },
155 b: 100,
156 s: Easy {
157 x: -100,
158 s: "bar".to_string(),
159 y: 20,
160 },
161 });
162 }
163
164 #[test]
test_struct_newtype()165 fn test_struct_newtype() {
166 #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
167 struct NewtypeStr(usize);
168
169 the_same(NewtypeStr(5));
170 }
171
172 #[test]
test_struct_tuple()173 fn test_struct_tuple() {
174 #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
175 struct TubStr(usize, String, f32);
176
177 the_same(TubStr(5, "hello".to_string(), 3.2));
178 }
179
180 #[test]
test_option()181 fn test_option() {
182 the_same(Some(5usize));
183 the_same(Some("foo bar".to_string()));
184 the_same(None::<usize>);
185 }
186
187 #[test]
test_enum()188 fn test_enum() {
189 #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
190 enum TestEnum {
191 NoArg,
192 OneArg(usize),
193 Args(usize, usize),
194 AnotherNoArg,
195 StructLike { x: usize, y: f32 },
196 }
197 the_same(TestEnum::NoArg);
198 the_same(TestEnum::OneArg(4));
199 //the_same(TestEnum::Args(4, 5));
200 the_same(TestEnum::AnotherNoArg);
201 the_same(TestEnum::StructLike { x: 4, y: 3.14159 });
202 the_same(vec![
203 TestEnum::NoArg,
204 TestEnum::OneArg(5),
205 TestEnum::AnotherNoArg,
206 TestEnum::StructLike { x: 4, y: 1.4 },
207 ]);
208 }
209
210 #[test]
test_vec()211 fn test_vec() {
212 let v: Vec<u8> = vec![];
213 the_same(v);
214 the_same(vec![1u64]);
215 the_same(vec![1u64, 2, 3, 4, 5, 6]);
216 }
217
218 #[test]
test_map()219 fn test_map() {
220 let mut m = HashMap::new();
221 m.insert(4u64, "foo".to_string());
222 m.insert(0u64, "bar".to_string());
223 the_same(m);
224 }
225
226 #[test]
test_bool()227 fn test_bool() {
228 the_same(true);
229 the_same(false);
230 }
231
232 #[test]
test_unicode()233 fn test_unicode() {
234 the_same("å".to_string());
235 the_same("aåååååååa".to_string());
236 }
237
238 #[test]
test_fixed_size_array()239 fn test_fixed_size_array() {
240 the_same([24u32; 32]);
241 the_same([1u64, 2, 3, 4, 5, 6, 7, 8]);
242 the_same([0u8; 19]);
243 }
244
245 #[test]
deserializing_errors()246 fn deserializing_errors() {
247 match *deserialize::<bool>(&vec![0xA][..]).unwrap_err() {
248 ErrorKind::InvalidBoolEncoding(0xA) => {}
249 _ => panic!(),
250 }
251
252 let invalid_str = vec![1, 0, 0, 0, 0, 0, 0, 0, 0xFF];
253
254 match *deserialize::<String>(&invalid_str[..]).unwrap_err() {
255 ErrorKind::InvalidUtf8Encoding(_) => {}
256 _ => panic!(),
257 }
258
259 // Out-of-bounds variant
260 #[derive(Serialize, Deserialize, Debug)]
261 enum Test {
262 One,
263 Two,
264 };
265
266 let invalid_enum = vec![0, 0, 0, 5];
267
268 match *deserialize::<Test>(&invalid_enum[..]).unwrap_err() {
269 // Error message comes from serde
270 ErrorKind::Custom(_) => {}
271 _ => panic!(),
272 }
273 match *deserialize::<Option<u8>>(&vec![5, 0][..]).unwrap_err() {
274 ErrorKind::InvalidTagEncoding(_) => {}
275 _ => panic!(),
276 }
277 }
278
279 #[test]
trailing_bytes()280 fn trailing_bytes() {
281 match DefaultOptions::new()
282 .deserialize::<char>(b"1x")
283 .map_err(|e| *e)
284 {
285 Err(ErrorKind::Custom(_)) => {}
286 other => panic!("Expecting TrailingBytes, got {:?}", other),
287 }
288 }
289
290 #[test]
too_big_deserialize()291 fn too_big_deserialize() {
292 let serialized = vec![0, 0, 0, 3];
293 let deserialized: Result<u32> = DefaultOptions::new()
294 .with_fixint_encoding()
295 .with_limit(3)
296 .deserialize_from(&mut &serialized[..]);
297 assert!(deserialized.is_err());
298
299 let serialized = vec![0, 0, 0, 3];
300 let deserialized: Result<u32> = DefaultOptions::new()
301 .with_fixint_encoding()
302 .with_limit(4)
303 .deserialize_from(&mut &serialized[..]);
304 assert!(deserialized.is_ok());
305 }
306
307 #[test]
char_serialization()308 fn char_serialization() {
309 let chars = "Aa\0☺♪";
310 for c in chars.chars() {
311 let encoded = DefaultOptions::new()
312 .with_limit(4)
313 .serialize(&c)
314 .expect("serializing char failed");
315 let decoded: char = deserialize(&encoded).expect("deserializing failed");
316 assert_eq!(decoded, c);
317 }
318 }
319
320 #[test]
too_big_char_deserialize()321 fn too_big_char_deserialize() {
322 let serialized = vec![0x41];
323 let deserialized: Result<char> = DefaultOptions::new()
324 .with_limit(1)
325 .deserialize_from(&mut &serialized[..]);
326 assert!(deserialized.is_ok());
327 assert_eq!(deserialized.unwrap(), 'A');
328 }
329
330 #[test]
too_big_serialize()331 fn too_big_serialize() {
332 assert!(DefaultOptions::new()
333 .with_fixint_encoding()
334 .with_limit(3)
335 .serialize(&0u32)
336 .is_err());
337 assert!(DefaultOptions::new()
338 .with_fixint_encoding()
339 .with_limit(4)
340 .serialize(&0u32)
341 .is_ok());
342
343 assert!(DefaultOptions::new()
344 .with_fixint_encoding()
345 .with_limit(LEN_SIZE + 4)
346 .serialize(&"abcde")
347 .is_err());
348 assert!(DefaultOptions::new()
349 .with_fixint_encoding()
350 .with_limit(LEN_SIZE + 5)
351 .serialize(&"abcde")
352 .is_ok());
353 }
354
355 #[test]
test_serialized_size()356 fn test_serialized_size() {
357 assert!(serialized_size(&0u8).unwrap() == 1);
358 assert!(serialized_size(&0u16).unwrap() == 2);
359 assert!(serialized_size(&0u32).unwrap() == 4);
360 assert!(serialized_size(&0u64).unwrap() == 8);
361
362 // length isize stored as u64
363 assert!(serialized_size(&"").unwrap() == LEN_SIZE);
364 assert!(serialized_size(&"a").unwrap() == LEN_SIZE + 1);
365
366 assert!(serialized_size(&vec![0u32, 1u32, 2u32]).unwrap() == LEN_SIZE + 3 * (4));
367 }
368
369 #[test]
test_serialized_size_bounded()370 fn test_serialized_size_bounded() {
371 // JUST RIGHT
372 assert!(
373 DefaultOptions::new()
374 .with_fixint_encoding()
375 .with_limit(1)
376 .serialized_size(&0u8)
377 .unwrap()
378 == 1
379 );
380 assert!(
381 DefaultOptions::new()
382 .with_fixint_encoding()
383 .with_limit(2)
384 .serialized_size(&0u16)
385 .unwrap()
386 == 2
387 );
388 assert!(
389 DefaultOptions::new()
390 .with_fixint_encoding()
391 .with_limit(4)
392 .serialized_size(&0u32)
393 .unwrap()
394 == 4
395 );
396 assert!(
397 DefaultOptions::new()
398 .with_fixint_encoding()
399 .with_limit(8)
400 .serialized_size(&0u64)
401 .unwrap()
402 == 8
403 );
404 assert!(
405 DefaultOptions::new()
406 .with_fixint_encoding()
407 .with_limit(8)
408 .serialized_size(&"")
409 .unwrap()
410 == LEN_SIZE
411 );
412 assert!(
413 DefaultOptions::new()
414 .with_fixint_encoding()
415 .with_limit(8 + 1)
416 .serialized_size(&"a")
417 .unwrap()
418 == LEN_SIZE + 1
419 );
420 assert!(
421 DefaultOptions::new()
422 .with_fixint_encoding()
423 .with_limit(LEN_SIZE + 3 * 4)
424 .serialized_size(&vec![0u32, 1u32, 2u32])
425 .unwrap()
426 == LEN_SIZE + 3 * 4
427 );
428 // Below
429 assert!(DefaultOptions::new()
430 .with_fixint_encoding()
431 .with_limit(0)
432 .serialized_size(&0u8)
433 .is_err());
434 assert!(DefaultOptions::new()
435 .with_fixint_encoding()
436 .with_limit(1)
437 .serialized_size(&0u16)
438 .is_err());
439 assert!(DefaultOptions::new()
440 .with_fixint_encoding()
441 .with_limit(3)
442 .serialized_size(&0u32)
443 .is_err());
444 assert!(DefaultOptions::new()
445 .with_fixint_encoding()
446 .with_limit(7)
447 .serialized_size(&0u64)
448 .is_err());
449 assert!(DefaultOptions::new()
450 .with_fixint_encoding()
451 .with_limit(7)
452 .serialized_size(&"")
453 .is_err());
454 assert!(DefaultOptions::new()
455 .with_fixint_encoding()
456 .with_limit(8 + 0)
457 .serialized_size(&"a")
458 .is_err());
459 assert!(DefaultOptions::new()
460 .with_fixint_encoding()
461 .with_limit(8 + 3 * 4 - 1)
462 .serialized_size(&vec![0u32, 1u32, 2u32])
463 .is_err());
464 }
465
466 #[test]
encode_box()467 fn encode_box() {
468 the_same(Box::new(5));
469 }
470
471 #[test]
test_cow_serialize()472 fn test_cow_serialize() {
473 let large_object = vec![1u32, 2, 3, 4, 5, 6];
474 let mut large_map = HashMap::new();
475 large_map.insert(1, 2);
476
477 #[derive(Serialize, Deserialize, Debug)]
478 enum Message<'a> {
479 M1(Cow<'a, Vec<u32>>),
480 M2(Cow<'a, HashMap<u32, u32>>),
481 }
482
483 // Test 1
484 {
485 let serialized = serialize(&Message::M1(Cow::Borrowed(&large_object))).unwrap();
486 let deserialized: Message<'static> = deserialize_from(&mut &serialized[..]).unwrap();
487
488 match deserialized {
489 Message::M1(b) => assert!(&b.into_owned() == &large_object),
490 _ => assert!(false),
491 }
492 }
493
494 // Test 2
495 {
496 let serialized = serialize(&Message::M2(Cow::Borrowed(&large_map))).unwrap();
497 let deserialized: Message<'static> = deserialize_from(&mut &serialized[..]).unwrap();
498
499 match deserialized {
500 Message::M2(b) => assert!(&b.into_owned() == &large_map),
501 _ => assert!(false),
502 }
503 }
504 }
505
506 #[test]
test_strbox_serialize()507 fn test_strbox_serialize() {
508 let strx: &'static str = "hello world";
509 let serialized = serialize(&Cow::Borrowed(strx)).unwrap();
510 let deserialized: Cow<'static, String> = deserialize_from(&mut &serialized[..]).unwrap();
511 let stringx: String = deserialized.into_owned();
512 assert!(strx == &stringx[..]);
513 }
514
515 #[test]
test_slicebox_serialize()516 fn test_slicebox_serialize() {
517 let slice = [1u32, 2, 3, 4, 5];
518 let serialized = serialize(&Cow::Borrowed(&slice[..])).unwrap();
519 println!("{:?}", serialized);
520 let deserialized: Cow<'static, Vec<u32>> = deserialize_from(&mut &serialized[..]).unwrap();
521 {
522 let sb: &[u32] = &deserialized;
523 assert!(slice == sb);
524 }
525 let vecx: Vec<u32> = deserialized.into_owned();
526 assert!(slice == &vecx[..]);
527 }
528
529 #[test]
test_multi_strings_serialize()530 fn test_multi_strings_serialize() {
531 assert!(serialize(&("foo", "bar", "baz")).is_ok());
532 }
533
534 #[test]
test_oom_protection()535 fn test_oom_protection() {
536 use std::io::Cursor;
537 #[derive(Serialize, Deserialize, PartialEq, Debug)]
538 struct FakeVec {
539 len: u64,
540 byte: u8,
541 }
542 let x = DefaultOptions::new()
543 .with_limit(10)
544 .serialize(&FakeVec {
545 len: 0xffffffffffffffffu64,
546 byte: 1,
547 })
548 .unwrap();
549 let y: Result<Vec<u8>> = DefaultOptions::new()
550 .with_limit(10)
551 .deserialize_from(&mut Cursor::new(&x[..]));
552 assert!(y.is_err());
553 }
554
555 #[test]
path_buf()556 fn path_buf() {
557 use std::path::{Path, PathBuf};
558 let path = Path::new("foo").to_path_buf();
559 let serde_encoded = serialize(&path).unwrap();
560 let decoded: PathBuf = deserialize(&serde_encoded).unwrap();
561 assert!(path.to_str() == decoded.to_str());
562 }
563
564 #[test]
bytes()565 fn bytes() {
566 use serde_bytes::Bytes;
567
568 let data = b"abc\0123";
569 let s = serialize(&data[..]).unwrap();
570 let s2 = serialize(&Bytes::new(data)).unwrap();
571 assert_eq!(s[..], s2[..]);
572 }
573
574 #[test]
serde_bytes()575 fn serde_bytes() {
576 use serde_bytes::ByteBuf;
577 the_same(ByteBuf::from(vec![1, 2, 3, 4, 5]));
578 }
579
580 #[test]
endian_difference()581 fn endian_difference() {
582 let x = 10u64;
583 let little = serialize(&x).unwrap();
584 let big = DefaultOptions::new()
585 .with_big_endian()
586 .serialize(&x)
587 .unwrap();
588 assert_ne!(little, big);
589 }
590
591 #[test]
test_zero_copy_parse()592 fn test_zero_copy_parse() {
593 #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
594 struct Foo<'a> {
595 borrowed_str: &'a str,
596 borrowed_bytes: &'a [u8],
597 }
598
599 let f = Foo {
600 borrowed_str: "hi",
601 borrowed_bytes: &[0, 1, 2, 3],
602 };
603 {
604 let encoded = serialize(&f).unwrap();
605 let out: Foo = deserialize(&encoded[..]).unwrap();
606 assert_eq!(out, f);
607 }
608 }
609
610 #[test]
test_zero_copy_parse_deserialize_into()611 fn test_zero_copy_parse_deserialize_into() {
612 use bincode::BincodeRead;
613 use std::io;
614
615 /// A BincodeRead implementation for byte slices
616 pub struct SliceReader<'storage> {
617 slice: &'storage [u8],
618 }
619
620 impl<'storage> SliceReader<'storage> {
621 #[inline(always)]
622 fn unexpected_eof() -> Box<::ErrorKind> {
623 return Box::new(::ErrorKind::Io(io::Error::new(
624 io::ErrorKind::UnexpectedEof,
625 "",
626 )));
627 }
628 }
629
630 impl<'storage> io::Read for SliceReader<'storage> {
631 #[inline(always)]
632 fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
633 (&mut self.slice).read(out)
634 }
635 #[inline(always)]
636 fn read_exact(&mut self, out: &mut [u8]) -> io::Result<()> {
637 (&mut self.slice).read_exact(out)
638 }
639 }
640
641 impl<'storage> BincodeRead<'storage> for SliceReader<'storage> {
642 #[inline(always)]
643 fn forward_read_str<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
644 where
645 V: serde::de::Visitor<'storage>,
646 {
647 use ErrorKind;
648 if length > self.slice.len() {
649 return Err(SliceReader::unexpected_eof());
650 }
651
652 let string = match ::std::str::from_utf8(&self.slice[..length]) {
653 Ok(s) => s,
654 Err(e) => return Err(ErrorKind::InvalidUtf8Encoding(e).into()),
655 };
656 let r = visitor.visit_borrowed_str(string);
657 self.slice = &self.slice[length..];
658 r
659 }
660
661 #[inline(always)]
662 fn get_byte_buffer(&mut self, length: usize) -> Result<Vec<u8>> {
663 if length > self.slice.len() {
664 return Err(SliceReader::unexpected_eof());
665 }
666
667 let r = &self.slice[..length];
668 self.slice = &self.slice[length..];
669 Ok(r.to_vec())
670 }
671
672 #[inline(always)]
673 fn forward_read_bytes<V>(&mut self, length: usize, visitor: V) -> Result<V::Value>
674 where
675 V: serde::de::Visitor<'storage>,
676 {
677 if length > self.slice.len() {
678 return Err(SliceReader::unexpected_eof());
679 }
680
681 let r = visitor.visit_borrowed_bytes(&self.slice[..length]);
682 self.slice = &self.slice[length..];
683 r
684 }
685 }
686
687 #[derive(Serialize, Deserialize, Eq, PartialEq, Debug)]
688 struct Foo<'a> {
689 borrowed_str: &'a str,
690 borrowed_bytes: &'a [u8],
691 }
692
693 let f = Foo {
694 borrowed_str: "hi",
695 borrowed_bytes: &[0, 1, 2, 3],
696 };
697
698 {
699 let encoded = serialize(&f).unwrap();
700 let mut target = Foo {
701 borrowed_str: "hello",
702 borrowed_bytes: &[10, 11, 12, 13],
703 };
704 deserialize_in_place(
705 SliceReader {
706 slice: &encoded[..],
707 },
708 &mut target,
709 )
710 .unwrap();
711 assert_eq!(target, f);
712 }
713 }
714
715 #[test]
not_human_readable()716 fn not_human_readable() {
717 use std::net::Ipv4Addr;
718 let ip = Ipv4Addr::new(1, 2, 3, 4);
719 the_same(ip);
720 assert_eq!(&ip.octets()[..], &serialize(&ip).unwrap()[..]);
721 assert_eq!(
722 ::std::mem::size_of::<Ipv4Addr>() as u64,
723 serialized_size(&ip).unwrap()
724 );
725 }
726
727 // The example is taken from serde::de::DeserializeSeed.
728 struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>);
729
730 impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T>
731 where
732 T: Deserialize<'de>,
733 {
734 // The return type of the `deserialize` method. This implementation
735 // appends onto an existing vector but does not create any new data
736 // structure, so the return type is ().
737 type Value = ();
738
deserialize<D>(self, deserializer: D) -> StdResult<Self::Value, D::Error> where D: Deserializer<'de>,739 fn deserialize<D>(self, deserializer: D) -> StdResult<Self::Value, D::Error>
740 where
741 D: Deserializer<'de>,
742 {
743 // Visitor implementation that will walk an inner array of the JSON
744 // input.
745 struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>);
746
747 impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T>
748 where
749 T: Deserialize<'de>,
750 {
751 type Value = ();
752
753 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
754 write!(formatter, "an array of integers")
755 }
756
757 fn visit_seq<A>(self, mut seq: A) -> StdResult<(), A::Error>
758 where
759 A: SeqAccess<'de>,
760 {
761 // Visit each element in the inner array and push it onto
762 // the existing vector.
763 while let Some(elem) = seq.next_element()? {
764 self.0.push(elem);
765 }
766 Ok(())
767 }
768 }
769
770 deserializer.deserialize_seq(ExtendVecVisitor(self.0))
771 }
772 }
773
774 #[test]
test_default_deserialize_seed()775 fn test_default_deserialize_seed() {
776 let config = DefaultOptions::new();
777
778 let data: Vec<_> = (10..100).collect();
779 let bytes = config.serialize(&data).expect("Config::serialize failed");
780
781 let mut seed_data: Vec<_> = (0..10).collect();
782 {
783 let seed = ExtendVec(&mut seed_data);
784 config
785 .deserialize_seed(seed, &bytes)
786 .expect("Config::deserialize_seed failed");
787 }
788
789 assert_eq!(seed_data, (0..100).collect::<Vec<_>>());
790 }
791
792 #[test]
test_big_endian_deserialize_seed()793 fn test_big_endian_deserialize_seed() {
794 let config = DefaultOptions::new().with_big_endian();
795
796 let data: Vec<_> = (10..100).collect();
797 let bytes = config.serialize(&data).expect("Config::serialize failed");
798
799 let mut seed_data: Vec<_> = (0..10).collect();
800 {
801 let seed = ExtendVec(&mut seed_data);
802 config
803 .deserialize_seed(seed, &bytes)
804 .expect("Config::deserialize_seed failed");
805 }
806
807 assert_eq!(seed_data, (0..100).collect::<Vec<_>>());
808 }
809
810 #[test]
test_default_deserialize_from_seed()811 fn test_default_deserialize_from_seed() {
812 let config = DefaultOptions::new();
813
814 let data: Vec<_> = (10..100).collect();
815 let bytes = config.serialize(&data).expect("Config::serialize failed");
816
817 let mut seed_data: Vec<_> = (0..10).collect();
818 {
819 let seed = ExtendVec(&mut seed_data);
820 config
821 .deserialize_from_seed(seed, &mut &*bytes)
822 .expect("Config::deserialize_from_seed failed");
823 }
824
825 assert_eq!(seed_data, (0..100).collect::<Vec<_>>());
826 }
827
828 #[test]
test_big_endian_deserialize_from_seed()829 fn test_big_endian_deserialize_from_seed() {
830 let config = DefaultOptions::new().with_big_endian();
831
832 let data: Vec<_> = (10..100).collect();
833 let bytes = config.serialize(&data).expect("Config::serialize failed");
834
835 let mut seed_data: Vec<_> = (0..10).collect();
836 {
837 let seed = ExtendVec(&mut seed_data);
838 config
839 .deserialize_from_seed(seed, &mut &*bytes)
840 .expect("Config::deserialize_from_seed failed");
841 }
842
843 assert_eq!(seed_data, (0..100).collect::<Vec<_>>());
844 }
845
846 #[test]
test_varint_length_prefixes()847 fn test_varint_length_prefixes() {
848 let a = vec![(); 127]; // should be a single byte
849 let b = vec![(); 250]; // also should be a single byte
850 let c = vec![(); 251];
851 let d = vec![(); u16::max_value() as usize + 1];
852
853 assert_eq!(
854 DefaultOptions::new()
855 .with_varint_encoding()
856 .serialized_size(&a[..])
857 .unwrap(),
858 1
859 ); // 2 ** 7 - 1
860 assert_eq!(
861 DefaultOptions::new()
862 .with_varint_encoding()
863 .serialized_size(&b[..])
864 .unwrap(),
865 1
866 ); // 250
867 assert_eq!(
868 DefaultOptions::new()
869 .with_varint_encoding()
870 .serialized_size(&c[..])
871 .unwrap(),
872 (1 + std::mem::size_of::<u16>()) as u64
873 ); // 251
874 assert_eq!(
875 DefaultOptions::new()
876 .with_varint_encoding()
877 .serialized_size(&d[..])
878 .unwrap(),
879 (1 + std::mem::size_of::<u32>()) as u64
880 ); // 2 ** 16 + 1
881 }
882
883 #[test]
test_byte_vec_struct()884 fn test_byte_vec_struct() {
885 #[derive(PartialEq, Eq, Clone, Serialize, Deserialize, Debug)]
886 struct ByteVecs {
887 a: Vec<u8>,
888 b: Vec<u8>,
889 c: Vec<u8>,
890 };
891
892 let byte_struct = ByteVecs {
893 a: vec![2; 20],
894 b: vec![3; 30],
895 c: vec![1; 10],
896 };
897
898 the_same(byte_struct);
899 }
900