awdl_frame_parser/
data_frame.rs1use ether_type::EtherType;
2use scroll::{
3 ctx::{MeasureWith, TryFromCtx, TryIntoCtx},
4 Endian, Pread, Pwrite,
5};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub struct AWDLDataFrame<P> {
9 pub sequence_number: u16,
10 pub ether_type: EtherType,
11 pub payload: P,
12}
13impl<P: MeasureWith<()>> MeasureWith<()> for AWDLDataFrame<P> {
14 fn measure_with(&self, ctx: &()) -> usize {
15 8 + self.payload.measure_with(ctx)
16 }
17}
18impl<'a> TryFromCtx<'a> for AWDLDataFrame<&'a [u8]> {
19 type Error = scroll::Error;
20 fn try_from_ctx(from: &'a [u8], _ctx: ()) -> Result<(Self, usize), Self::Error> {
21 let mut offset = 0;
22 let header_data = from.gread::<[u8; 2]>(&mut offset)?;
23 if header_data != [0x03, 0x04] {
24 return Err(scroll::Error::BadInput {
25 size: offset,
26 msg: "Unknown header format.",
27 });
28 }
29 let sequence_number = from.gread_with(&mut offset, Endian::Little)?;
30 offset += 2;
31 let ether_type = EtherType::from_bits(from.gread_with(&mut offset, Endian::Big)?);
32 let payload_len = from.len() - offset;
33 let payload = from.gread_with(&mut offset, payload_len)?;
34 Ok((
35 Self {
36 sequence_number,
37 ether_type,
38 payload,
39 },
40 offset,
41 ))
42 }
43}
44impl<P: TryIntoCtx<Error = scroll::Error>> TryIntoCtx for AWDLDataFrame<P> {
45 type Error = scroll::Error;
46 fn try_into_ctx(self, buf: &mut [u8], _ctx: ()) -> Result<usize, Self::Error> {
47 let mut offset = 0;
48
49 buf.gwrite::<[u8; 2]>([0x03, 0x04], &mut offset)?;
50 buf.gwrite_with(self.sequence_number, &mut offset, Endian::Little)?;
51 offset += 2;
52 buf.gwrite_with(
53 self.ether_type.into_bits(),
54 &mut offset,
55 Endian::Big,
56 )?;
57 buf.gwrite(self.payload, &mut offset)?;
58
59 Ok(offset)
60 }
61}
62#[test]
63fn test_data_frame() {
64 use alloc::vec;
65 let bytes = include_bytes!("../test_bins/data_frame.bin");
66 let data_frame = bytes.pread::<AWDLDataFrame<&[u8]>>(0).unwrap();
67 assert_eq!(
68 data_frame,
69 AWDLDataFrame {
70 sequence_number: 2981,
71 ether_type: EtherType::IPv6,
72 payload: &bytes[8..]
73 }
74 );
75 let mut buf = vec![0x00u8; data_frame.measure_with(&())];
76 buf.pwrite(data_frame, 0).unwrap();
77 assert_eq!(bytes, buf.as_slice());
78}