1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use crate::{EtherPayloadSlice, EtherType, LinuxSllProtocolType};

/// Payload of Linux Cooked Capture v1 (SLL) packet
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LinuxSllPayloadSlice<'a> {
    /// Identifying content of the payload.
    pub protocol_type: LinuxSllProtocolType,

    /// Payload
    pub payload: &'a [u8],
}

impl<'a> From<EtherPayloadSlice<'a>> for LinuxSllPayloadSlice<'a> {
    fn from(value: EtherPayloadSlice<'a>) -> LinuxSllPayloadSlice<'a> {
        LinuxSllPayloadSlice {
            protocol_type: LinuxSllProtocolType::EtherType(value.ether_type),
            payload: value.payload,
        }
    }
}

impl<'a> TryFrom<LinuxSllPayloadSlice<'a>> for EtherPayloadSlice<'a> {
    type Error = ();

    fn try_from(value: LinuxSllPayloadSlice<'a>) -> Result<EtherPayloadSlice<'a>, Self::Error> {
        match value.protocol_type {
            LinuxSllProtocolType::LinuxNonstandardEtherType(nonstandard_ether_type) => {
                Ok(EtherPayloadSlice {
                    ether_type: EtherType(nonstandard_ether_type.into()),
                    payload: value.payload,
                })
            }
            LinuxSllProtocolType::EtherType(ether_type) => Ok(EtherPayloadSlice {
                ether_type,
                payload: value.payload,
            }),
            _ => Err(()),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use alloc::format;

    #[test]
    fn debug() {
        let s = LinuxSllPayloadSlice {
            protocol_type: LinuxSllProtocolType::EtherType(EtherType::IPV4),
            payload: &[],
        };
        assert_eq!(
            format!(
                "LinuxSllPayloadSlice {{ protocol_type: {:?}, payload: {:?} }}",
                s.protocol_type, s.payload
            ),
            format!("{:?}", s)
        );
    }

    #[test]
    fn clone_eq() {
        let s = LinuxSllPayloadSlice {
            protocol_type: LinuxSllProtocolType::EtherType(EtherType::IPV4),
            payload: &[],
        };
        assert_eq!(s.clone(), s);
    }
}