virtio_drivers/device/net/
net_buf.rs

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
use super::{VirtioNetHdr, NET_HDR_SIZE};
use alloc::{vec, vec::Vec};
use core::{convert::TryInto, mem::size_of};
use zerocopy::AsBytes;

/// A buffer used for transmitting.
pub struct TxBuffer(pub(crate) Vec<u8>);

/// A buffer used for receiving.
pub struct RxBuffer {
    pub(crate) buf: Vec<usize>, // for alignment
    pub(crate) packet_len: usize,
    pub(crate) idx: u16,
}

impl TxBuffer {
    /// Constructs the buffer from the given slice.
    pub fn from(buf: &[u8]) -> Self {
        Self(Vec::from(buf))
    }

    /// Returns the network packet length.
    pub fn packet_len(&self) -> usize {
        self.0.len()
    }

    /// Returns the network packet as a slice.
    pub fn packet(&self) -> &[u8] {
        self.0.as_slice()
    }

    /// Returns the network packet as a mutable slice.
    pub fn packet_mut(&mut self) -> &mut [u8] {
        self.0.as_mut_slice()
    }
}

impl RxBuffer {
    /// Allocates a new buffer with length `buf_len`.
    pub(crate) fn new(idx: usize, buf_len: usize) -> Self {
        Self {
            buf: vec![0; buf_len / size_of::<usize>()],
            packet_len: 0,
            idx: idx.try_into().unwrap(),
        }
    }

    /// Set the network packet length.
    pub(crate) fn set_packet_len(&mut self, packet_len: usize) {
        self.packet_len = packet_len
    }

    /// Returns the network packet length (witout header).
    pub const fn packet_len(&self) -> usize {
        self.packet_len
    }

    /// Returns all data in the buffer, including both the header and the packet.
    pub fn as_bytes(&self) -> &[u8] {
        self.buf.as_bytes()
    }

    /// Returns all data in the buffer with the mutable reference,
    /// including both the header and the packet.
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        self.buf.as_bytes_mut()
    }

    /// Returns the reference of the header.
    pub fn header(&self) -> &VirtioNetHdr {
        unsafe { &*(self.buf.as_ptr() as *const VirtioNetHdr) }
    }

    /// Returns the network packet as a slice.
    pub fn packet(&self) -> &[u8] {
        &self.buf.as_bytes()[NET_HDR_SIZE..NET_HDR_SIZE + self.packet_len]
    }

    /// Returns the network packet as a mutable slice.
    pub fn packet_mut(&mut self) -> &mut [u8] {
        &mut self.buf.as_bytes_mut()[NET_HDR_SIZE..NET_HDR_SIZE + self.packet_len]
    }
}