virtio_drivers/device/net/
net_buf.rs
1use super::{VirtioNetHdr, NET_HDR_SIZE};
2use alloc::{vec, vec::Vec};
3use core::{convert::TryInto, mem::size_of};
4use zerocopy::AsBytes;
5
6pub struct TxBuffer(pub(crate) Vec<u8>);
8
9pub struct RxBuffer {
11 pub(crate) buf: Vec<usize>, pub(crate) packet_len: usize,
13 pub(crate) idx: u16,
14}
15
16impl TxBuffer {
17 pub fn from(buf: &[u8]) -> Self {
19 Self(Vec::from(buf))
20 }
21
22 pub fn packet_len(&self) -> usize {
24 self.0.len()
25 }
26
27 pub fn packet(&self) -> &[u8] {
29 self.0.as_slice()
30 }
31
32 pub fn packet_mut(&mut self) -> &mut [u8] {
34 self.0.as_mut_slice()
35 }
36}
37
38impl RxBuffer {
39 pub(crate) fn new(idx: usize, buf_len: usize) -> Self {
41 Self {
42 buf: vec![0; buf_len / size_of::<usize>()],
43 packet_len: 0,
44 idx: idx.try_into().unwrap(),
45 }
46 }
47
48 pub(crate) fn set_packet_len(&mut self, packet_len: usize) {
50 self.packet_len = packet_len
51 }
52
53 pub const fn packet_len(&self) -> usize {
55 self.packet_len
56 }
57
58 pub fn as_bytes(&self) -> &[u8] {
60 self.buf.as_bytes()
61 }
62
63 pub fn as_bytes_mut(&mut self) -> &mut [u8] {
66 self.buf.as_bytes_mut()
67 }
68
69 pub fn header(&self) -> &VirtioNetHdr {
71 unsafe { &*(self.buf.as_ptr() as *const VirtioNetHdr) }
72 }
73
74 pub fn packet(&self) -> &[u8] {
76 &self.buf.as_bytes()[NET_HDR_SIZE..NET_HDR_SIZE + self.packet_len]
77 }
78
79 pub fn packet_mut(&mut self) -> &mut [u8] {
81 &mut self.buf.as_bytes_mut()[NET_HDR_SIZE..NET_HDR_SIZE + self.packet_len]
82 }
83}