aboutsummaryrefslogtreecommitdiff
path: root/embassy-net/src/packet_pool.rs
blob: b43ae2eb21aae8d2eefa3b306d2564a99ed9bddc (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use as_slice::{AsMutSlice, AsSlice};
use core::ops::{Deref, DerefMut, Range};

use atomic_pool::{pool, Box};

pub const MTU: usize = 1516;

#[cfg(feature = "pool-4")]
pub const PACKET_POOL_SIZE: usize = 4;

#[cfg(feature = "pool-8")]
pub const PACKET_POOL_SIZE: usize = 8;

#[cfg(feature = "pool-16")]
pub const PACKET_POOL_SIZE: usize = 16;

#[cfg(feature = "pool-32")]
pub const PACKET_POOL_SIZE: usize = 32;

pool!(pub PacketPool: [Packet; PACKET_POOL_SIZE]);
pub type PacketBox = Box<PacketPool>;

#[repr(align(4))]
pub struct Packet(pub [u8; MTU]);

impl Packet {
    pub const fn new() -> Self {
        Self([0; MTU])
    }
}

pub trait PacketBoxExt {
    fn slice(self, range: Range<usize>) -> PacketBuf;
}

impl PacketBoxExt for PacketBox {
    fn slice(self, range: Range<usize>) -> PacketBuf {
        PacketBuf {
            packet: self,
            range,
        }
    }
}

impl AsSlice for Packet {
    type Element = u8;

    fn as_slice(&self) -> &[Self::Element] {
        &self.deref()[..]
    }
}

impl AsMutSlice for Packet {
    fn as_mut_slice(&mut self) -> &mut [Self::Element] {
        &mut self.deref_mut()[..]
    }
}

impl Deref for Packet {
    type Target = [u8; MTU];

    fn deref(&self) -> &[u8; MTU] {
        &self.0
    }
}

impl DerefMut for Packet {
    fn deref_mut(&mut self) -> &mut [u8; MTU] {
        &mut self.0
    }
}

pub struct PacketBuf {
    packet: PacketBox,
    range: Range<usize>,
}

impl AsSlice for PacketBuf {
    type Element = u8;

    fn as_slice(&self) -> &[Self::Element] {
        &self.packet[self.range.clone()]
    }
}

impl AsMutSlice for PacketBuf {
    fn as_mut_slice(&mut self) -> &mut [Self::Element] {
        &mut self.packet[self.range.clone()]
    }
}

impl Deref for PacketBuf {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        &self.packet[self.range.clone()]
    }
}

impl DerefMut for PacketBuf {
    fn deref_mut(&mut self) -> &mut [u8] {
        &mut self.packet[self.range.clone()]
    }
}