Skip to main content

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/// The decoded struct of a `DoIP` packet.
49///
50/// Each `DoIP` packet contains a header which describes the message, this is outlined
51/// in `DoipHeader`.
52///
53/// Some Payload Types available in `DoIP` require a payload which is covered by
54/// `DoipPayload`.
55#[cfg(feature = "std")]
56#[derive(Debug, PartialEq, Clone)]
57pub struct DoipMessage {
58    /// Defined by `DoipHeader`, the header supplies the information for programs
59    /// to understand the payload.
60    pub header: DoipHeader,
61
62    /// Takes any struct implementing `DoipPayload`.
63    pub payload: DoipPayload,
64}
65
66#[cfg(feature = "std")]
67impl TryFrom<DoipMessage> for Vec<u8> {
68    type Error = Error;
69
70    fn try_from(value: DoipMessage) -> Result<Self> {
71        let mut buffer = Vec::<u8>::new();
72
73        let header: [u8; 8] = value.header.into();
74        buffer[0..8].copy_from_slice(&header);
75
76        let payload: Vec<u8> = value.payload.into();
77        buffer[8..].copy_from_slice(&payload);
78
79        Ok(buffer)
80    }
81}