Skip to main content

c_its_parser/transport/
encode.rs

1use alloc::string::ToString;
2
3#[allow(dead_code)]
4#[derive(Debug)]
5pub enum EncodeError {
6    Unsupported(alloc::string::String),
7    #[cfg(feature = "json")]
8    Json(alloc::string::String),
9}
10
11pub trait Encode: Sized {
12    fn encode(&self) -> Result<alloc::vec::Vec<u8>, EncodeError>;
13}
14
15impl Encode for super::BasicTransportAHeader {
16    fn encode(&self) -> Result<alloc::vec::Vec<u8>, EncodeError> {
17        Ok([
18            self.destination_port.to_be_bytes(),
19            self.source_port.to_be_bytes(),
20        ]
21        .concat())
22    }
23}
24
25impl super::BasicTransportAHeader {
26    #[cfg(feature = "json")]
27    /// Encodes a BTP-A as a JSON representation
28    ///
29    /// # Errors
30    /// Returns an error when encoding failed.
31    pub fn encode_to_json(&self) -> Result<alloc::string::String, EncodeError> {
32        serde_json::to_string(&self)
33            .map_err(|e| EncodeError::Json(alloc::format!("Error encoding to JSON: {e:?}")))
34    }
35}
36
37impl Encode for super::BasicTransportBHeader {
38    fn encode(&self) -> Result<alloc::vec::Vec<u8>, EncodeError> {
39        Ok([
40            self.destination_port.to_be_bytes(),
41            self.destination_port_info.to_be_bytes(),
42        ]
43        .concat())
44    }
45}
46
47impl super::BasicTransportBHeader {
48    #[cfg(feature = "json")]
49    /// Encodes a BTP-B as a JSON representation
50    ///
51    /// # Errors
52    /// Returns an error when encoding failed.
53    pub fn encode_to_json(&self) -> Result<alloc::string::String, EncodeError> {
54        serde_json::to_string(&self)
55            .map_err(|e| EncodeError::Json(alloc::format!("Error encoding to JSON: {e:?}")))
56    }
57}
58
59impl Encode for super::IPv6Header {
60    fn encode(&self) -> Result<alloc::vec::Vec<u8>, EncodeError> {
61        Err(EncodeError::Unsupported(
62            "Encoding IPv6 headers is currently unsupported.".to_string(),
63        ))
64    }
65}