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
use base::DataType;
use byteorder::{ReadBytesExt, WriteBytesExt};
use std::io;
use std::io::{Read, Write};
use {PreliminaryTryFrom, WithFixedPayloadLength};

impl WithFixedPayloadLength for DataType {
    const FIXED_PAYLOAD_LENGTH: u16 = u8::FIXED_PAYLOAD_LENGTH;
}

impl PreliminaryTryFrom<u8> for DataType {
    type Error = io::Error;
    fn try_from(value: u8) -> io::Result<Self> {
        use base::DataType::*;
        match value {
            0x00 => Ok(Boolean),
            0x01 => Ok(Int8),
            0x02 => Ok(Int16),
            0x03 => Ok(Int32),
            0x04 => Ok(Int64),
            0x05 => Ok(UInt8),
            0x06 => Ok(UInt16),
            0x07 => Ok(UInt32),
            0x08 => Ok(UInt64),
            0x09 => Ok(ParameterMask),
            _ => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Invalid DataType enum value {}", value),
            )),
        }
    }
}

pub(crate) trait DataTypeWriterExt: Write {
    fn write_data_type(&mut self, t: DataType) -> io::Result<()> {
        self.write_u8(t as u8)
    }

    fn write_data_types(&mut self, t: &[DataType]) -> io::Result<()> {
        for v in t {
            self.write_data_type(v.clone())?;
        }
        Ok(())
    }
}

impl<B: Write + ?Sized> DataTypeWriterExt for B {}

pub(crate) trait DataTypeReaderExt: Read {
    fn read_data_type(&mut self) -> io::Result<DataType> {
        let value = self.read_u8()?;
        DataType::try_from(value)
    }

    fn read_data_types(
        &mut self,
        count: usize,
    ) -> io::Result<Vec<DataType>> {
        (0usize..count)
            .map(|_| self.read_data_type())
            .collect::<io::Result<Vec<DataType>>>()
    }
}

impl<B: Read + ?Sized> DataTypeReaderExt for B {}