doip_definitions/doip_message/
mod.rs

1use crate::{
2    error::{Error, Result},
3    header::DoipHeader,
4    payload::DoipPayload,
5};
6
7/// The decoded struct of a `DoIP` packet.
8///
9/// Each `DoIP` packet contains a header which describes the message, this is outlined
10/// in `DoipHeader`.
11///
12/// Some Payload Types available in `DoIP` require a payload which is covered by
13/// `DoipPayload`.
14#[cfg(not(feature = "std"))]
15#[derive(Debug, PartialEq, Clone)]
16pub struct DoipMessage<const N: usize> {
17    /// Defined by `DoipHeader`, the header supplies the information for programs
18    /// to understand the payload.
19    pub header: DoipHeader,
20
21    /// Takes any struct implementing `DoipPayload`.
22    pub payload: DoipPayload<N>,
23}
24
25#[cfg(not(feature = "std"))]
26impl<const N: usize> TryFrom<DoipMessage<N>> for [u8; N] {
27    type Error = Error;
28
29    fn try_from(value: DoipMessage<N>) -> Result<Self> {
30        let mut buffer = [0u8; N];
31
32        let payload_len = value.header.payload_length;
33
34        let header: [u8; 8] = value.header.into();
35        buffer[0..8].copy_from_slice(&header);
36
37        if N < 8 + (payload_len as usize) {
38            return Err(Error::BufferTooSmall { size: N });
39        }
40
41        let payload: [u8; N] = value.payload.into();
42        buffer[8..].copy_from_slice(&payload);
43
44        Ok(buffer)
45    }
46}
47
48
49/// The decoded struct of a `DoIP` packet.
50///
51/// Each `DoIP` packet contains a header which describes the message, this is outlined
52/// in `DoipHeader`.
53///
54/// Some Payload Types available in `DoIP` require a payload which is covered by
55/// `DoipPayload`.
56#[cfg(feature = "std")]
57#[derive(Debug, PartialEq, Clone)]
58pub struct DoipMessage {
59    /// Defined by `DoipHeader`, the header supplies the information for programs
60    /// to understand the payload.
61    pub header: DoipHeader,
62
63    /// Takes any struct implementing `DoipPayload`.
64    pub payload: DoipPayload,
65}
66
67#[cfg(feature = "std")]
68impl<const N: usize> TryFrom<DoipMessage> for [u8; N] {
69    type Error = Error;
70
71    fn try_from(value: DoipMessage) -> Result<Self> {
72        let mut buffer = [0u8; N];
73
74        let payload_len = value.header.payload_length;
75
76        let header: [u8; 8] = value.header.into();
77        buffer[0..8].copy_from_slice(&header);
78
79        if N < 8 + (payload_len as usize) {
80            return Err(Error::BufferTooSmall { size: N });
81        }
82
83        let payload: [u8; N] = value.payload.into();
84        buffer[8..].copy_from_slice(&payload);
85
86        Ok(buffer)
87    }
88}