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
use std::net::Ipv4Addr;
use crate::Ipv4Mask;
pub trait IpBitwiseExt<Rhs = Self> {
type Output;
fn bitand(self, rhs: Rhs) -> Self::Output;
fn bitor(self, rhs: Rhs) -> Self::Output;
fn bitxor(self, rhs: Rhs) -> Self::Output;
}
pub trait IpBitwiseNotExt {
fn bitnot(self) -> Self;
}
impl IpBitwiseNotExt for Ipv4Addr {
fn bitnot(self) -> Self {
let bytes = self.octets();
Self::new(!bytes[0], !bytes[1], !bytes[2], !bytes[3])
}
}
impl IpBitwiseExt<[u8; 4]> for Ipv4Addr {
type Output = Self;
fn bitand(self, rhs: [u8; 4]) -> Self {
let lhs = self.octets();
Ipv4Addr::new(
lhs[0] & rhs[0],
lhs[1] & rhs[1],
lhs[2] & rhs[2],
lhs[3] & rhs[3],
)
}
fn bitor(self, rhs: [u8; 4]) -> Self {
let lhs = self.octets();
Ipv4Addr::new(
lhs[0] | rhs[0],
lhs[1] | rhs[1],
lhs[2] | rhs[2],
lhs[3] | rhs[3],
)
}
fn bitxor(self, rhs: [u8; 4]) -> Self {
let lhs = self.octets();
Ipv4Addr::new(
lhs[0] ^ rhs[0],
lhs[1] ^ rhs[1],
lhs[2] ^ rhs[2],
lhs[3] ^ rhs[3],
)
}
}
impl IpBitwiseExt<Self> for Ipv4Addr {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
self.bitand(rhs.octets())
}
fn bitor(self, rhs: Self) -> Self {
self.bitor(rhs.octets())
}
fn bitxor(self, rhs: Self) -> Self {
self.bitxor(rhs.octets())
}
}
impl IpBitwiseExt<Ipv4Mask> for Ipv4Addr {
type Output = Self;
fn bitand(self, rhs: Ipv4Mask) -> Self {
self.bitand(rhs.octets())
}
fn bitor(self, rhs: Ipv4Mask) -> Self {
self.bitor(rhs.octets())
}
fn bitxor(self, rhs: Ipv4Mask) -> Self {
self.bitxor(rhs.octets())
}
}
impl IpBitwiseExt<u32> for Ipv4Addr {
type Output = Self;
fn bitand(self, rhs: u32) -> Self {
self.bitand(rhs.to_be_bytes())
}
fn bitor(self, rhs: u32) -> Self {
self.bitor(rhs.to_be_bytes())
}
fn bitxor(self, rhs: u32) -> Self {
self.bitxor(rhs.to_be_bytes())
}
}