iso14229_1/common/
dynamically_define_did.rs

1//! Commons of Service 2C
2
3use crate::{DataIdentifier, enum_to_vec, Error, utils};
4
5enum_to_vec!(
6    pub enum DefinitionType {
7        DefineByIdentifier = 0x01,
8        DefineByMemoryAddress = 0x02,
9        ClearDynamicallyDefinedDataIdentifier = 0x03,
10    }, u8);
11
12#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
13pub struct DynamicallyDID(pub(crate) u16);
14
15impl TryFrom<u16> for DynamicallyDID {
16    type Error = Error;
17    fn try_from(value: u16) -> Result<Self, Self::Error> {
18        match DataIdentifier::from(value) {
19            DataIdentifier::Periodic(_) |
20            DataIdentifier::DynamicallyDefined(_) => {
21                Ok(Self(value))
22            },
23            _ => Err(Error::InvalidDynamicallyDefinedDID(value))
24        }
25    }
26}
27
28impl Into<u16> for DynamicallyDID {
29    #[inline]
30    fn into(self) -> u16 {
31        self.0
32    }
33}
34
35impl Into<Vec<u8>> for DynamicallyDID {
36    #[inline]
37    fn into(self) -> Vec<u8> {
38        self.0.to_be_bytes().to_vec()
39    }
40}
41
42#[derive(Debug, Clone, Eq, PartialEq)]
43pub struct DynamicallyMemAddr {
44    pub did: u16,
45    pub position: u8,
46    pub mem_size: u8,
47}
48
49impl<'a> TryFrom<&'a [u8]> for DynamicallyMemAddr {
50    type Error = Error;
51    fn try_from(data: &'a [u8]) -> Result<Self, Self::Error> {
52        let data_len = data.len();
53        utils::data_length_check(data_len, 4, false)?;
54
55        let mut offset = 0;
56        let did = u16::from_be_bytes([data[offset], data[offset + 1]]);
57        offset += 2;
58        let position = data[offset];
59        offset += 1;
60        let mem_size = data[offset];
61
62        Ok(Self { did, position, mem_size })
63    }
64}
65
66impl Into<Vec<u8>> for DynamicallyMemAddr {
67    fn into(self) -> Vec<u8> {
68        let mut result = self.did.to_be_bytes().to_vec();
69        result.push(self.position);
70        result.push(self.mem_size);
71        result
72    }
73}