net_lattice_model/
ifaddr.rs1use net_lattice_core::Id;
2
3use crate::IpAddress;
4use crate::address::Network;
5use crate::interface::InterfaceId;
6use net_lattice_ip::Ipv4Address;
7
8pub type InterfaceAddressId = Id<InterfaceAddress>;
10
11#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub struct NewInterfaceAddress {
22 pub interface_id: InterfaceId,
24 pub address: Network,
26 pub broadcast: Option<Ipv4Address>,
28}
29
30impl NewInterfaceAddress {
31 pub fn new(interface_id: InterfaceId, address: Network) -> Self {
32 Self {
33 interface_id,
34 address,
35 broadcast: None,
36 }
37 }
38
39 pub fn with_broadcast(mut self, broadcast: Ipv4Address) -> Self {
40 self.broadcast = Some(broadcast);
41 self
42 }
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Hash)]
62#[non_exhaustive]
63pub struct InterfaceAddress {
64 pub id: InterfaceAddressId,
65 pub interface_index: u32,
68 pub address: Network,
70 pub broadcast: Option<IpAddress>,
73}
74
75impl InterfaceAddress {
76 pub fn new(id: InterfaceAddressId, interface_index: u32, address: Network) -> Self {
77 Self {
78 id,
79 interface_index,
80 address,
81 broadcast: None,
82 }
83 }
84
85 pub fn with_broadcast(mut self, broadcast: IpAddress) -> Self {
86 self.broadcast = Some(broadcast);
87 self
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use super::*;
94 use net_lattice_ip::{Ipv4Address, Ipv4Network, Ipv4PrefixLength};
95
96 fn sample_network() -> Network {
97 Network::from(Ipv4Network::new(
98 Ipv4Address::new(192, 168, 1, 10),
99 Ipv4PrefixLength::new(24).unwrap(),
100 ))
101 }
102
103 #[test]
104 fn new_address_has_no_broadcast() {
105 let addr = InterfaceAddress::new(InterfaceAddressId::new(1), 1, sample_network());
106 assert!(addr.broadcast.is_none());
107 }
108
109 #[test]
110 fn with_broadcast_sets_the_field() {
111 let broadcast = IpAddress::from(Ipv4Address::new(192, 168, 1, 255));
112 let addr = InterfaceAddress::new(InterfaceAddressId::new(1), 1, sample_network())
113 .with_broadcast(broadcast);
114 assert_eq!(addr.broadcast, Some(broadcast));
115 }
116
117 #[test]
118 fn new_address_intent_keeps_interface_identity_separate_from_output_id() {
119 let intent = NewInterfaceAddress::new(InterfaceId::new(7), sample_network())
120 .with_broadcast(Ipv4Address::new(192, 168, 1, 255));
121 assert_eq!(intent.interface_id, InterfaceId::new(7));
122 assert_eq!(intent.broadcast, Some(Ipv4Address::new(192, 168, 1, 255)));
123 }
124}