icmp_packet/
types.rs

1use crate::ICMP_HEADER_SIZE;
2
3//
4wrapping_macro::wrapping_int! {
5    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6    pub struct Identifier(pub u16);
7}
8impl Identifier {
9    pub fn gen() -> Self {
10        let pid = std::process::id();
11        if pid <= u16::MAX as u32 {
12            Self(pid as u16)
13        } else {
14            #[cfg(feature = "rand")]
15            let id = rand::random();
16            #[cfg(not(feature = "rand"))]
17            let id = 0;
18            Self(id)
19        }
20    }
21}
22
23//
24wrapping_macro::wrapping_int! {
25    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
26    pub struct SequenceNumber(pub u16);
27}
28
29//
30wrapping_macro::wrapping! {
31    #[derive(Debug, Clone, Default, PartialEq, Eq)]
32    pub struct Payload(pub Vec<u8>);
33}
34
35//
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
37pub struct LenWithPayloadLengthDelimited(u16);
38impl LenWithPayloadLengthDelimited {
39    pub const fn size() -> usize {
40        core::mem::size_of::<u16>()
41    }
42
43    pub const fn max() -> u16 {
44        u16::MAX - ICMP_HEADER_SIZE as u16 - core::mem::size_of::<u16>() as u16
45    }
46
47    pub fn new(v: usize) -> Self {
48        assert!(v <= Self::max() as usize);
49        Self(v as u16)
50    }
51
52    pub fn inner(&self) -> &u16 {
53        &self.0
54    }
55
56    pub fn to_bytes(&self) -> [u8; 2] {
57        self.0.to_be_bytes()
58    }
59
60    pub fn from_bytes(bytes: [u8; 2]) -> Self {
61        Self(u16::from_be_bytes(bytes))
62    }
63}