ed/
lib.rs

1#![feature(fundamental)]
2
3//! *`ed` is a minimalist crate for deterministic binary encodings.*
4//!
5//! ## Overview
6//!
7//! This crate provides `Encode` and `Decode` traits which can be implemented for any
8//! type that can be converted to or from bytes, and implements these traits for
9//! many built-in Rust types. It also provides derive macros so that `Encode`
10//! and `Decode` can be easily derived for structs.
11//!
12//! `ed` is far simpler than `serde` because it does not attempt to create an
13//! abstraction which allows arbitrary kinds of encoding (JSON, MessagePack,
14//! etc.), and instead forces focuses on binary encodings. It is also
15//! significantly faster than [`bincode`](https://docs.rs/bincode), the leading
16//! binary `serde` serializer.
17//!
18//! One aim of `ed` is to force top-level type authors to design their own
19//! encoding, rather than attempting to provide a one-size-fits-all encoding
20//! scheme. This lets users of `ed` be sure their encodings are as effiient as
21//! possible, and makes it easier to understand the encoding for compatability
22//! in other languages or libraries (contrasted with something like `bincode`,
23//! where it is not obvious how a type is being encoded without understanding
24//! the internals of `bincode`).
25//!
26//! Another property of this crate is a focus on determinism (important for
27//! cryptographically hashed types) - built-in encodings are always big-endian
28//! and there are no provided encodings for floating point numbers or `usize`.
29//!
30//! ## Usage
31//!
32//! ```rust
33//! #![feature(trivial_bounds)]
34//! use ed::{Encode, Decode};
35//!
36//! # fn main() -> ed::Result<()> {
37//! // traits are implemented for built-in types
38//! let bytes = 123u32.encode()?; // `bytes` is a Vec<u8>
39//! let n = u32::decode(bytes.as_slice())?; // `n` is a u32
40//!
41//! // derive macros are available
42//! #[derive(Encode, Decode)]
43//! # #[derive(PartialEq, Eq, Debug)]
44//! struct Foo {
45//!   bar: (u32, u32),
46//!   baz: Vec<u8>
47//! }
48//!
49//! // encoding and decoding can be done in-place to reduce allocations
50//!
51//! let mut bytes = vec![0xba; 40];
52//! let mut foo = Foo {
53//!   bar: (0, 0),
54//!   baz: Vec::with_capacity(32)
55//! };
56//!
57//! // in-place decode, re-using pre-allocated `foo.baz` vec
58//! foo.decode_into(bytes.as_slice())?;
59//! assert_eq!(foo, Foo {
60//!   bar: (0xbabababa, 0xbabababa),
61//!   baz: vec![0xba; 32]
62//! });
63//!
64//! // in-place encode, into pre-allocated `bytes` vec
65//! bytes.clear();
66//! foo.encode_into(&mut bytes)?;
67//!
68//! # Ok(())
69//! # }
70//! ```
71
72use std::convert::TryInto;
73use std::io::{Read, Write};
74
75pub use ed_derive::*;
76
77/// An enum that defines the `ed` error types.
78#[derive(thiserror::Error, Debug)]
79pub enum Error {
80    #[error("Unexpected byte: {0}")]
81    UnexpectedByte(u8),
82    #[error("Unencodable variant")]
83    UnencodableVariant,
84    #[error(transparent)]
85    IOError(#[from] std::io::Error),
86}
87
88/// A Result bound to the standard `ed` error type.
89pub type Result<T> = std::result::Result<T, Error>;
90
91/// A trait for values that can be encoded into bytes deterministically.
92#[fundamental]
93pub trait Encode {
94    /// Writes the encoded representation of the value to the destination
95    /// writer. Can error due to either a write error from `dest`, or an
96    /// encoding error for types where invalid values are possible.
97    ///
98    /// It may be more convenient to call [`encode`](#method.encode) which
99    /// returns bytes, however `encode_into` will often be more efficient since
100    /// it can write the encoding without necessarily allocating a new
101    /// `Vec<u8>`.
102    fn encode_into<W: Write>(&self, dest: &mut W) -> Result<()>;
103
104    /// Calculates the length of the encoding for this value. Can error for
105    /// types where invalid values are possible.
106    fn encoding_length(&self) -> Result<usize>;
107
108    /// Returns the encoded representation of the value as a `Vec<u8>`.
109    ///
110    /// While this method is convenient, it will often be more efficient to call
111    /// [`encode_into`](#method.encode_into) since `encode` usually involves
112    /// allocating a new `Vec<u8>`.
113    #[inline]
114    #[cfg_attr(test, mutate)]
115    fn encode(&self) -> Result<Vec<u8>> {
116        let length = self.encoding_length()?;
117        let mut bytes = Vec::with_capacity(length);
118        self.encode_into(&mut bytes)?;
119        Ok(bytes)
120    }
121}
122
123/// A trait for values that can be decoded from bytes deterministically.
124#[fundamental]
125pub trait Decode: Sized {
126    /// Reads bytes from the reader and returns the decoded value.
127    ///
128    /// When possible, calling [`decode_into`](#method.decode_into) will often
129    /// be more efficient since it lets the caller reuse memory to avoid
130    /// allocating for fields with types such as `Vec<T>`.
131    fn decode<R: Read>(input: R) -> Result<Self>;
132
133    /// Reads bytes from the reader and mutates self to the decoded value.
134    ///
135    /// This is often more efficient than calling [`decode`](#method.decode)
136    /// when reading fields with heap-allocated types such as `Vec<T>` since it
137    /// can reuse the memory already allocated in self.
138    ///
139    /// When possible, implementations should recursively call `decode_into` on
140    /// any child fields.
141    ///
142    /// The default implementation of `decode_into` simply calls
143    /// [`decode`](#method.decode) for ease of implementation, but should be
144    /// overridden when in-place decoding is possible.
145    #[inline]
146    #[cfg_attr(test, mutate)]
147    fn decode_into<R: Read>(&mut self, input: R) -> Result<()> {
148        let value = Self::decode(input)?;
149        *self = value;
150        Ok(())
151    }
152}
153
154/// A type is `Terminated` the length of the value being read can be determined
155/// when decoding.
156///
157/// Since `Terminated` is an auto trait, it is automatically present for any
158/// type made of fields which are all `Terminated`.
159///
160/// Consider a type like `u32` - it is always 4 bytes long. If a slice of length
161/// 5 was passed to its `decode` method, it would know to stop reading after the
162/// 4th byte, which means it is `Terminated`.
163///
164/// For an example of something which is NOT terminated, consider `Vec<u8>`. Its
165/// encoding and decoding do not use a length prefix or end with a null byte, so
166/// `decode` would have no way to know where to stop reading.
167pub trait Terminated {}
168
169macro_rules! int_impl {
170    ($type:ty, $length:expr) => {
171        impl Encode for $type {
172            #[doc = "Encodes the integer as fixed-size big-endian bytes."]
173            #[inline]
174            fn encode_into<W: Write>(&self, dest: &mut W) -> Result<()> {
175                let bytes = self.to_be_bytes();
176                dest.write_all(&bytes[..])?;
177                Ok(())
178            }
179
180            #[doc = "Returns the size of the integer in bytes. Will always"]
181            #[doc = " return an `Ok` result."]
182            #[inline]
183            fn encoding_length(&self) -> Result<usize> {
184                Ok($length)
185            }
186        }
187
188        impl Decode for $type {
189            #[doc = "Decodes the integer from fixed-size big-endian bytes."]
190            #[inline]
191            fn decode<R: Read>(mut input: R) -> Result<Self> {
192                let mut bytes = [0; $length];
193                input.read_exact(&mut bytes[..])?;
194                Ok(Self::from_be_bytes(bytes))
195            }
196        }
197
198        impl Terminated for $type {}
199    };
200}
201
202int_impl!(u8, 1);
203int_impl!(u16, 2);
204int_impl!(u32, 4);
205int_impl!(u64, 8);
206int_impl!(u128, 16);
207int_impl!(i8, 1);
208int_impl!(i16, 2);
209int_impl!(i32, 4);
210int_impl!(i64, 8);
211int_impl!(i128, 16);
212
213impl Encode for bool {
214    /// Encodes the boolean as a single byte: 0 for false or 1 for true.
215    #[inline]
216    #[cfg_attr(test, mutate)]
217    fn encode_into<W: Write>(&self, dest: &mut W) -> Result<()> {
218        let bytes = [*self as u8];
219        dest.write_all(&bytes[..])?;
220        Ok(())
221    }
222
223    /// Always returns Ok(1).
224    #[inline]
225    #[cfg_attr(test, mutate)]
226    fn encoding_length(&self) -> Result<usize> {
227        Ok(1)
228    }
229}
230
231impl Decode for bool {
232    /// Decodes the boolean from a single byte: 0 for false or 1 for true.
233    /// Errors for any other value.
234    #[inline]
235    #[cfg_attr(test, mutate)]
236    fn decode<R: Read>(mut input: R) -> Result<Self> {
237        let mut buf = [0; 1];
238        input.read_exact(&mut buf[..])?;
239        match buf[0] {
240            0 => Ok(false),
241            1 => Ok(true),
242            byte => Err(Error::UnexpectedByte(byte)),
243        }
244    }
245}
246
247impl Terminated for bool {}
248
249impl<T: Encode> Encode for Option<T> {
250    /// Encodes as a 0 byte for `None`, or as a 1 byte followed by the encoding of
251    /// the inner value for `Some`.
252    #[inline]
253    #[cfg_attr(test, mutate)]
254    fn encode_into<W: Write>(&self, dest: &mut W) -> Result<()> {
255        match self {
256            None => dest.write_all(&[0]).map_err(Error::IOError),
257            Some(value) => {
258                dest.write_all(&[1]).map_err(Error::IOError)?;
259                value.encode_into(dest)
260            }
261        }
262    }
263
264    /// Length will be 1 for `None`, or 1 plus the encoding length of the inner
265    /// value for `Some`.
266    #[inline]
267    #[cfg_attr(test, mutate)]
268    fn encoding_length(&self) -> Result<usize> {
269        match self {
270            None => Ok(1),
271            Some(value) => Ok(1 + value.encoding_length()?),
272        }
273    }
274}
275
276impl<T: Decode> Decode for Option<T> {
277    /// Decodes a 0 byte as `None`, or a 1 byte followed by the encoding of the
278    /// inner value as `Some`. Errors for all other values.
279    #[inline]
280    #[cfg_attr(test, mutate)]
281    fn decode<R: Read>(input: R) -> Result<Self> {
282        let mut option: Option<T> = None;
283        option.decode_into(input)?;
284        Ok(option)
285    }
286
287    /// Decodes a 0 byte as `None`, or a 1 byte followed by the encoding of the
288    /// inner value as `Some`. Errors for all other values.
289    //
290    // When the first byte is 1 and self is `Some`, `decode_into` will be called
291    // on the inner type. When the first byte is 1 and self is `None`, `decode`
292    // will be called for the inner type.
293    #[inline]
294    #[cfg_attr(test, mutate)]
295    fn decode_into<R: Read>(&mut self, mut input: R) -> Result<()> {
296        let mut byte = [0; 1];
297        input.read_exact(&mut byte[..])?;
298
299        match byte[0] {
300            0 => *self = None,
301            1 => match self {
302                None => *self = Some(T::decode(input)?),
303                Some(value) => value.decode_into(input)?,
304            },
305            byte => {
306                return Err(Error::UnexpectedByte(byte));
307            }
308        };
309
310        Ok(())
311    }
312}
313
314impl<T: Terminated> Terminated for Option<T> {}
315
316impl Encode for () {
317    /// Encoding a unit tuple is a no-op.
318    #[inline]
319    #[cfg_attr(test, mutate)]
320    fn encode_into<W: Write>(&self, _: &mut W) -> Result<()> {
321        Ok(())
322    }
323
324    /// Always returns Ok(0).
325    #[inline]
326    #[cfg_attr(test, mutate)]
327    fn encoding_length(&self) -> Result<usize> {
328        Ok(0)
329    }
330}
331
332impl Decode for () {
333    /// Returns a unit tuple without reading any bytes.
334    #[inline]
335    #[cfg_attr(test, mutate)]
336    fn decode<R: Read>(_: R) -> Result<Self> {
337        Ok(())
338    }
339}
340
341impl Terminated for () {}
342
343macro_rules! tuple_impl {
344    ($( $type:ident ),*; $last_type:ident) => {
345        impl<$($type: Encode + Terminated,)* $last_type: Encode> Encode for ($($type,)* $last_type,) {
346            #[doc = "Encodes the fields of the tuple one after another, in"]
347            #[doc = " order."]
348            #[allow(non_snake_case, unused_mut)]
349            #[inline]
350            fn encode_into<W: Write>(&self, mut dest: &mut W) -> Result<()> {
351                let ($($type,)* $last_type,) = self;
352                $($type.encode_into(&mut dest)?;)*
353                $last_type.encode_into(dest)
354            }
355
356            #[doc = "Returns the sum of the encoding lengths of the fields of"]
357            #[doc = " the tuple."]
358            #[allow(non_snake_case)]
359            #[allow(clippy::needless_question_mark)]
360            #[inline]
361            fn encoding_length(&self) -> Result<usize> {
362                let ($($type,)* $last_type,) = self;
363                Ok(
364                    $($type.encoding_length()? +)*
365                    $last_type.encoding_length()?
366                )
367            }
368        }
369
370        impl<$($type: Decode + Terminated,)* $last_type: Decode> Decode for ($($type,)* $last_type,) {
371            #[doc = "Decodes the fields of the tuple one after another, in"]
372            #[doc = " order."]
373            #[allow(unused_mut)]
374            #[inline]
375            fn decode<R: Read>(mut input: R) -> Result<Self> {
376                Ok((
377                    $($type::decode(&mut input)?,)*
378                    $last_type::decode(input)?,
379                ))
380            }
381
382            #[doc = "Decodes the fields of the tuple one after another, in"]
383            #[doc = " order."]
384            #[doc = ""]
385            #[doc = "Recursively calls `decode_into` for each field."]
386            #[allow(non_snake_case, unused_mut)]
387            #[inline]
388            fn decode_into<R: Read>(&mut self, mut input: R) -> Result<()> {
389                let ($($type,)* $last_type,) = self;
390                $($type.decode_into(&mut input)?;)*
391                $last_type.decode_into(input)?;
392                Ok(())
393            }
394        }
395
396        impl<$($type: Terminated,)* $last_type: Terminated> Terminated for ($($type,)* $last_type,) {}
397    }
398}
399
400tuple_impl!(; A);
401tuple_impl!(A; B);
402tuple_impl!(A, B; C);
403tuple_impl!(A, B, C; D);
404tuple_impl!(A, B, C, D; E);
405tuple_impl!(A, B, C, D, E; F);
406tuple_impl!(A, B, C, D, E, F; G);
407tuple_impl!(A, B, C, D, E, F, G; H);
408tuple_impl!(A, B, C, D, E, F, G, H; I);
409tuple_impl!(A, B, C, D, E, F, G, H, I; J);
410tuple_impl!(A, B, C, D, E, F, G, H, I, J; K);
411tuple_impl!(A, B, C, D, E, F, G, H, I, J, K; L);
412
413impl<T: Encode + Terminated, const N: usize> Encode for [T; N] {
414    #[inline]
415    fn encode_into<W: Write>(&self, mut dest: &mut W) -> Result<()> {
416        for element in self[..].iter() {
417            element.encode_into(&mut dest)?;
418        }
419        Ok(())
420    }
421
422    #[inline]
423    fn encoding_length(&self) -> Result<usize> {
424        let mut sum = 0;
425        for element in self[..].iter() {
426            sum += element.encoding_length()?;
427        }
428        Ok(sum)
429    }
430}
431
432impl<T: Decode + Terminated, const N: usize> Decode for [T; N] {
433    #[allow(unused_variables, unused_mut)]
434    #[inline]
435    fn decode<R: Read>(mut input: R) -> Result<Self> {
436        let mut v: Vec<T> = Vec::with_capacity(N);
437        for i in 0..N {
438            v.push(T::decode(&mut input)?);
439        }
440        Ok(v.try_into()
441            .unwrap_or_else(|v: Vec<T>| panic!("Input Vec not of length {}", N)))
442    }
443
444    #[inline]
445    fn decode_into<R: Read>(&mut self, mut input: R) -> Result<()> {
446        for item in self.iter_mut().take(N) {
447            T::decode_into(item, &mut input)?;
448        }
449        Ok(())
450    }
451}
452
453impl<T: Terminated, const N: usize> Terminated for [T; N] {}
454
455impl<T: Encode + Terminated> Encode for Vec<T> {
456    #[doc = "Encodes the elements of the vector one after another, in order."]
457    #[inline]
458    fn encode_into<W: Write>(&self, dest: &mut W) -> Result<()> {
459        for element in self.iter() {
460            element.encode_into(dest)?;
461        }
462        Ok(())
463    }
464
465    #[doc = "Returns the sum of the encoding lengths of all elements."]
466    #[cfg_attr(test, mutate)]
467    #[inline]
468    fn encoding_length(&self) -> Result<usize> {
469        let mut sum = 0;
470        for element in self.iter() {
471            sum += element.encoding_length()?;
472        }
473        Ok(sum)
474    }
475}
476
477impl<T: Decode + Terminated> Decode for Vec<T> {
478    #[doc = "Decodes the elements of the vector one after another, in order."]
479    #[cfg_attr(test, mutate)]
480    #[inline]
481    fn decode<R: Read>(input: R) -> Result<Self> {
482        let mut vec = Vec::with_capacity(128);
483        vec.decode_into(input)?;
484        Ok(vec)
485    }
486
487    #[doc = "Encodes the elements of the vector one after another, in order."]
488    #[doc = ""]
489    #[doc = "Recursively calls `decode_into` for each element."]
490    #[cfg_attr(test, mutate)]
491    #[inline]
492    fn decode_into<R: Read>(&mut self, mut input: R) -> Result<()> {
493        let old_len = self.len();
494
495        let mut bytes = Vec::with_capacity(256);
496        input.read_to_end(&mut bytes)?;
497
498        let mut slice = bytes.as_slice();
499        let mut i = 0;
500        while !slice.is_empty() {
501            if i < old_len {
502                self[i].decode_into(&mut slice)?;
503            } else {
504                let el = T::decode(&mut slice)?;
505                self.push(el);
506            }
507
508            i += 1;
509        }
510
511        if i < old_len {
512            self.truncate(i);
513        }
514
515        Ok(())
516    }
517}
518
519impl<T: Encode + Terminated> Encode for [T] {
520    #[doc = "Encodes the elements of the slice one after another, in order."]
521    #[cfg_attr(test, mutate)]
522    #[inline]
523    fn encode_into<W: Write>(&self, mut dest: &mut W) -> Result<()> {
524        for element in self[..].iter() {
525            element.encode_into(&mut dest)?;
526        }
527        Ok(())
528    }
529
530    #[doc = "Returns the sum of the encoding lengths of all elements."]
531    #[cfg_attr(test, mutate)]
532    #[inline]
533    fn encoding_length(&self) -> Result<usize> {
534        let mut sum = 0;
535        for element in self[..].iter() {
536            sum += element.encoding_length()?;
537        }
538        Ok(sum)
539    }
540}
541
542impl<T: Encode> Encode for Box<T> {
543    #[doc = "Encodes the inner value."]
544    #[cfg_attr(test, mutate)]
545    #[inline]
546    fn encode_into<W: Write>(&self, dest: &mut W) -> Result<()> {
547        (**self).encode_into(dest)
548    }
549
550    #[doc = "Returns the encoding length of the inner value."]
551    #[cfg_attr(test, mutate)]
552    #[inline]
553    fn encoding_length(&self) -> Result<usize> {
554        (**self).encoding_length()
555    }
556}
557
558impl<T: Decode> Decode for Box<T> {
559    #[doc = "Decodes the inner value into a new Box."]
560    #[cfg_attr(test, mutate)]
561    #[inline]
562    fn decode<R: Read>(input: R) -> Result<Self> {
563        T::decode(input).map(|v| v.into())
564    }
565
566    #[doc = "Decodes the inner value into the existing Box."]
567    #[doc = ""]
568    #[doc = "Recursively calls `decode_into` on the inner value."]
569    #[cfg_attr(test, mutate)]
570    #[inline]
571    fn decode_into<R: Read>(&mut self, input: R) -> Result<()> {
572        (**self).decode_into(input)
573    }
574}
575
576impl<T> Encode for std::marker::PhantomData<T> {
577    /// Encoding PhantomData is a no-op.
578    #[inline]
579    #[cfg_attr(test, mutate)]
580    fn encode_into<W: Write>(&self, _: &mut W) -> Result<()> {
581        Ok(())
582    }
583
584    /// Always returns Ok(0).
585    #[inline]
586    #[cfg_attr(test, mutate)]
587    fn encoding_length(&self) -> Result<usize> {
588        Ok(0)
589    }
590}
591
592impl<T> Decode for std::marker::PhantomData<T> {
593    /// Returns a PhantomData without reading any bytes.
594    #[inline]
595    #[cfg_attr(test, mutate)]
596    fn decode<R: Read>(_: R) -> Result<Self> {
597        Ok(Self {})
598    }
599}
600
601impl<T> Terminated for std::marker::PhantomData<T> {}
602
603#[cfg(test)]
604use mutagen::mutate;
605mod tests {
606    #[allow(unused_imports)]
607    use super::*;
608
609    #[test]
610    fn encode_decode_u8() {
611        let value = 0x12u8;
612        let bytes = value.encode().unwrap();
613        assert_eq!(bytes.as_slice(), &[0x12]);
614        let decoded_value = u8::decode(bytes.as_slice()).unwrap();
615        assert_eq!(decoded_value, value);
616    }
617
618    #[test]
619    fn encode_decode_u64() {
620        let value = 0x1234567890u64;
621        let bytes = value.encode().unwrap();
622        assert_eq!(bytes.as_slice(), &[0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x90]);
623        let decoded_value = u64::decode(bytes.as_slice()).unwrap();
624        assert_eq!(decoded_value, value);
625    }
626
627    #[test]
628    fn encode_decode_option() {
629        let value = Some(0x1234567890u64);
630        let bytes = value.encode().unwrap();
631        assert_eq!(
632            bytes.as_slice(),
633            &[1, 0, 0, 0, 0x12, 0x34, 0x56, 0x78, 0x90]
634        );
635        let decoded_value: Option<u64> = Decode::decode(bytes.as_slice()).unwrap();
636        assert_eq!(decoded_value, value);
637
638        let value: Option<u64> = None;
639        let bytes = value.encode().unwrap();
640        assert_eq!(bytes.as_slice(), &[0]);
641        let decoded_value: Option<u64> = Decode::decode(bytes.as_slice()).unwrap();
642        assert_eq!(decoded_value, None);
643    }
644
645    #[test]
646    fn encode_decode_tuple() {
647        let value: (u16, u16) = (1, 2);
648        let bytes = value.encode().unwrap();
649        assert_eq!(bytes.as_slice(), &[0, 1, 0, 2]);
650        let decoded_value: (u16, u16) = Decode::decode(bytes.as_slice()).unwrap();
651        assert_eq!(decoded_value, value);
652
653        let value = ();
654        let bytes = value.encode().unwrap();
655        assert_eq!(bytes.as_slice().len(), 0);
656        let decoded_value: () = Decode::decode(bytes.as_slice()).unwrap();
657        assert_eq!(decoded_value, value);
658    }
659
660    #[test]
661    fn encode_decode_array() {
662        let value: [u16; 4] = [1, 2, 3, 4];
663        let bytes = value.encode().unwrap();
664        assert_eq!(bytes.as_slice(), &[0, 1, 0, 2, 0, 3, 0, 4]);
665        let decoded_value: [u16; 4] = Decode::decode(bytes.as_slice()).unwrap();
666        assert_eq!(decoded_value, value);
667    }
668
669    #[test]
670    #[should_panic(expected = "failed to fill whole buffer")]
671    fn encode_decode_array_eof_length() {
672        let bytes = [0, 1, 0, 2, 0, 3];
673        let _: [u16; 4] = Decode::decode(&bytes[..]).unwrap();
674    }
675
676    #[test]
677    #[should_panic(expected = "failed to fill whole buffer")]
678    fn encode_decode_array_eof_element() {
679        let bytes = [0, 1, 0, 2, 0, 3, 0];
680        let _: [u16; 4] = Decode::decode(&bytes[..]).unwrap();
681    }
682
683    #[test]
684    fn encode_decode_vec() {
685        let value: Vec<u16> = vec![1, 2, 3, 4];
686        let bytes = value.encode().unwrap();
687        assert_eq!(bytes.as_slice(), &[0, 1, 0, 2, 0, 3, 0, 4]);
688        let decoded_value: Vec<u16> = Decode::decode(bytes.as_slice()).unwrap();
689        assert_eq!(decoded_value, value);
690    }
691
692    #[test]
693    #[should_panic(expected = "failed to fill whole buffer")]
694    fn encode_decode_vec_eof_element() {
695        let bytes = [0, 1, 0, 2, 0, 3, 0];
696        let _: Vec<u16> = Decode::decode(&bytes[..]).unwrap();
697    }
698
699    #[test]
700    fn test_encode_bool() {
701        let value: bool = true;
702        let bytes = value.encode().unwrap();
703        assert_eq!(bytes.as_slice(), &[1]);
704    }
705
706    #[test]
707    fn test_encoding_length_bool() {
708        let value: bool = true;
709        let enc_length = value.encoding_length().unwrap();
710        assert!(enc_length == 1);
711    }
712    #[test]
713    fn test_decode_bool_true() {
714        let bytes = vec![1];
715        let decoded_value: bool = Decode::decode(bytes.as_slice()).unwrap();
716        assert_eq!(decoded_value, true);
717    }
718
719    #[test]
720    fn test_decode_bool_false() {
721        let bytes = vec![0];
722        let decoded_value: bool = Decode::decode(bytes.as_slice()).unwrap();
723        assert_eq!(decoded_value, false);
724    }
725
726    #[test]
727    fn test_decode_bool_bail() {
728        let bytes = vec![42];
729        let result: Result<bool> = Decode::decode(bytes.as_slice());
730        assert_eq!(result.unwrap_err().to_string(), "Unexpected byte: 42");
731    }
732
733    #[test]
734    fn test_encode_decode_phantom_data() {
735        use std::marker::PhantomData;
736        let pd: PhantomData<u8> = PhantomData;
737        let bytes = pd.encode().unwrap();
738        assert_eq!(bytes.len(), 0);
739        let decoded_value: PhantomData<u8> = Decode::decode(bytes.as_slice()).unwrap();
740        assert_eq!(decoded_value, PhantomData);
741    }
742
743    #[test]
744    fn test_default_decode() {
745        struct Foo {
746            bar: u8,
747        }
748
749        impl Decode for Foo {
750            fn decode<R: Read>(_input: R) -> Result<Self> {
751                Ok(Foo { bar: 42 })
752            }
753        }
754
755        let bytes = vec![42, 12, 68];
756        let mut foo: Foo = Foo { bar: 41 };
757        foo.decode_into(bytes.as_slice()).unwrap();
758        assert_eq!(foo.bar, 42);
759    }
760
761    #[test]
762    fn test_option_encode_into() {
763        let option = Some(0x12u8);
764        let mut vec: Vec<u8> = vec![];
765        option.encode_into(&mut vec).unwrap();
766        assert_eq!(vec, vec![1, 18]);
767    }
768
769    #[test]
770    fn test_option_encoding_length() {
771        let val = 0x12u8;
772        let option = Some(val);
773        let option_length = option.encoding_length().unwrap();
774        let val_length = val.encoding_length().unwrap();
775        assert!(option_length == val_length + 1);
776    }
777    #[test]
778    fn test_option_none_encode_into() {
779        let option: Option<u8> = None;
780        let mut vec: Vec<u8> = vec![];
781        option.encode_into(&mut vec).unwrap();
782        assert_eq!(vec, vec![0]);
783    }
784
785    #[test]
786    fn test_option_none_encoding_length() {
787        let option: Option<u8> = None;
788        let length = option.encoding_length().unwrap();
789        assert!(length == 1);
790    }
791
792    #[test]
793    fn test_bail_option_decode_into() {
794        let mut option: Option<u8> = Some(42);
795        let bytes = vec![42];
796        let err = option.decode_into(bytes.as_slice()).unwrap_err();
797        assert_eq!(err.to_string(), "Unexpected byte: 42");
798    }
799
800    #[test]
801    fn test_some_option_decode_into() {
802        let mut option: Option<u8> = Some(0);
803        let bytes = vec![1, 0x12u8];
804        option.decode_into(bytes.as_slice()).unwrap();
805        assert_eq!(option.unwrap(), 18);
806    }
807
808    #[test]
809    fn test_vec_decode_into() {
810        let mut vec: Vec<u8> = vec![42, 42, 42];
811        let bytes = vec![12, 13];
812        vec.decode_into(bytes.as_slice()).unwrap();
813        assert_eq!(vec, vec![12, 13]);
814    }
815
816    #[test]
817    fn test_vec_encoding_length() {
818        let forty_two: u8 = 42;
819        let vec: Vec<u8> = vec![42, 42, 42];
820        let vec_length = vec.encoding_length().unwrap();
821        let indv_num_length = forty_two.encoding_length().unwrap();
822        assert!(vec_length == indv_num_length * 3);
823    }
824
825    #[test]
826    fn test_box_encoding_length() {
827        let forty_two = Box::new(42);
828        let length = forty_two.encoding_length().unwrap();
829        assert_eq!(length, 4);
830    }
831
832    #[test]
833    fn test_box_encode_into() {
834        let test = Box::new(42);
835        let mut vec = vec![12];
836        test.encode_into(&mut vec).unwrap();
837        assert_eq!(*test, 42);
838    }
839
840    #[test]
841    fn test_box_decode() {
842        let bytes = vec![1];
843        let test = Box::new(bytes.as_slice());
844        let decoded_value: Box<bool> = Decode::decode(test).unwrap();
845        assert_eq!(*decoded_value, true);
846    }
847
848    #[test]
849    fn test_box_decode_into() {
850        let mut test = Box::new(false);
851        let bytes = vec![1];
852        test.decode_into(bytes.as_slice()).unwrap();
853        assert_eq!(*test, true);
854    }
855
856    #[test]
857    fn test_slice_encode_into() {
858        let vec = vec![1, 2, 1];
859        let slice = &vec[0..3];
860        let mut vec: Vec<u8> = vec![];
861        slice.encode_into(&mut vec).unwrap();
862        assert_eq!(vec, vec![0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1]);
863    }
864
865    #[test]
866    fn test_slice_encoding_length() {
867        let vec = vec![1, 2, 1];
868        let slice = &vec[0..3];
869        let size = slice.encoding_length().unwrap();
870        assert_eq!(size, 12);
871    }
872
873    #[test]
874    fn test_unit_encoding_length() {
875        let unit = ();
876        let length = unit.encoding_length().unwrap();
877        assert!(length == 0);
878    }
879
880    #[test]
881    fn test_phantom_data_encoding_length() {
882        use std::marker::PhantomData;
883        let pd: PhantomData<u8> = PhantomData;
884        let length = pd.encoding_length().unwrap();
885        assert_eq!(length, 0);
886    }
887}