1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use bitstream_io::{BigEndian, BitReader, BitWriter, LittleEndian};

use crate::{BitRead, BitWrite, ByteOrder, Error};
use core::any::Any;
use std::io;

/// A trait for bit-level co/dec.
pub trait Protocol: Sized {
    /// Reads self from a stream.
    ///
    /// Blocks until a value is received.
    fn read(
        read: &mut dyn BitRead,
        byte_order: ByteOrder,
        ctx: &mut dyn Any,
    ) -> Result<Self, Error>;

    /// Writes a value to a stream.
    fn write(
        &self,
        write: &mut dyn BitWrite,
        byte_order: ByteOrder,
        ctx: &mut dyn Any,
    ) -> Result<(), Error>;

    /// Parses a new value from its raw byte representation without context.
    fn from_bytes(bytes: &[u8], byte_order: ByteOrder) -> Result<Self, Error> {
        Self::from_bytes_ctx(bytes, byte_order, &mut ())
    }

    /// Parses a new value from its raw byte representation with additional context.
    fn from_bytes_ctx(
        bytes: &[u8],
        byte_order: ByteOrder,
        ctx: &mut dyn Any,
    ) -> Result<Self, Error> {
        match byte_order {
            crate::ByteOrder::LittleEndian => {
                let mut buffer = BitReader::endian(io::Cursor::new(bytes), LittleEndian);
                Self::read(&mut buffer, byte_order, ctx)
            }
            crate::ByteOrder::BigEndian => {
                let mut buffer = BitReader::endian(io::Cursor::new(bytes), BigEndian);
                Self::read(&mut buffer, byte_order, ctx)
            }
        }
    }

    /// Gets the raw bytes of this type without context.
    fn bytes(&self, byte_order: ByteOrder) -> Result<Vec<u8>, Error> {
        self.bytes_ctx(byte_order, &mut ())
    }

    /// Gets the raw bytes of this type with provided context.
    fn bytes_ctx(&self, byte_order: ByteOrder, ctx: &mut dyn Any) -> Result<Vec<u8>, Error> {
        let mut data = Vec::new();
        match byte_order {
            crate::ByteOrder::LittleEndian => {
                let mut writer = BitWriter::endian(&mut data, LittleEndian);
                self.write(&mut writer, byte_order, ctx)?;
                writer.byte_align()?;
            }
            crate::ByteOrder::BigEndian => {
                let mut writer = BitWriter::endian(&mut data, BigEndian);
                self.write(&mut writer, byte_order, ctx)?;
                writer.byte_align()?;
            }
        };

        Ok(data)
    }
}

#[cfg(test)]
macro_rules! test_protocol {
    ($t:ty => [$bytes:expr, $value:expr]) => {
        #[test]
        fn read_protocol() {
            let bytes: &[u8] = $bytes.as_slice();
            assert_eq!(
                <$t as crate::Protocol>::read(
                    &mut bitstream_io::BitReader::endian(bytes, bitstream_io::BigEndian),
                    crate::ByteOrder::BigEndian,
                    &mut ()
                )
                .unwrap(),
                $value
            )
        }

        #[test]
        fn write_protocol() {
            let mut buffer: Vec<u8> = Vec::new();
            let value: $t = $value;
            crate::Protocol::write(
                &value,
                &mut bitstream_io::BitWriter::endian(&mut buffer, bitstream_io::BigEndian),
                crate::ByteOrder::BigEndian,
                &mut (),
            )
            .unwrap();
            assert_eq!(buffer.as_slice(), $bytes)
        }
    };
}