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
use crate::{
ethernet::{EtherType, EthernetHeader, EthernetPacket},
packet::Packet,
};
use bytes::Bytes;
use nex_core::mac::MacAddr;
/// Builder for constructing Ethernet packets.
#[derive(Debug, Clone)]
pub struct EthernetPacketBuilder {
packet: EthernetPacket,
}
impl Default for EthernetPacketBuilder {
fn default() -> Self {
Self::new()
}
}
impl EthernetPacketBuilder {
/// Create a new builder instance.
pub fn new() -> Self {
Self {
packet: EthernetPacket {
header: EthernetHeader {
destination: MacAddr::zero(),
source: MacAddr::zero(),
ethertype: EtherType::Ipv4,
},
payload: Bytes::new(),
},
}
}
/// Set the destination MAC address.
pub fn destination(mut self, mac: MacAddr) -> Self {
self.packet.header.destination = mac;
self
}
/// Set the source MAC address.
pub fn source(mut self, mac: MacAddr) -> Self {
self.packet.header.source = mac;
self
}
/// Set the EtherType (IPv4, ARP, IPv6, etc.).
pub fn ethertype(mut self, ether_type: EtherType) -> Self {
self.packet.header.ethertype = ether_type;
self
}
/// Set the payload bytes.
pub fn payload(mut self, payload: Bytes) -> Self {
self.packet.payload = payload;
self
}
/// Consume the builder and produce an `EthernetPacket`.
///
/// This finalizer is infallible because Ethernet II uses a fixed-size
/// header and does not encode the payload length in the frame.
pub fn build(self) -> EthernetPacket {
self.packet
}
/// Serialize the packet into raw bytes.
pub fn to_bytes(self) -> Bytes {
self.packet.to_bytes()
}
/// Retrieve only the header bytes.
pub fn header_bytes(&self) -> Bytes {
self.packet.header.to_bytes()
}
}