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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use std::cmp::Ordering;
use std::fmt;
use addr::ipv6::{IpAddr, MAX_PREFIXLEN};
use addr::{IpAddrVersion, Ipv6};
#[derive(Copy, Clone, Show, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub struct IpNetwork(pub IpAddr, pub uint);
impl IpNetwork {
pub fn version(&self) -> IpAddrVersion {
Ipv6
}
pub fn address(&self) -> IpAddr {
let &IpNetwork(addr, _) = self;
addr & self.mask()
}
pub fn broadcast_address(&self) -> IpAddr {
self.address() | !self.mask()
}
pub fn prefix(&self) -> uint {
let &IpNetwork(_, prefix) = self;
prefix
}
pub fn host_prefix(&self) -> uint {
MAX_PREFIXLEN - self.prefix()
}
pub fn num_addresses(&self) -> uint {
use std::num::Int;
2u.pow(self.host_prefix())
}
pub fn mask(&self) -> IpAddr {
IpAddr::with_prefixlen(self.prefix())
}
pub fn range(&self) -> (IpAddr, IpAddr) {
(self.address(), self.broadcast_address())
}
pub fn contains(&self, ip: IpAddr) -> bool {
let (start, stop) = self.range();
start <= ip && ip <= stop
}
pub fn overlaps(&self, other: IpNetwork) -> bool {
other.contains(self.address()) || other.contains(self.broadcast_address())
|| self.contains(other.address()) || self.contains(other.broadcast_address())
}
pub fn iter(&self) -> Hosts {
let (start, stop) = self.range();
Hosts {
state: start,
stop: stop,
}
}
pub fn hosts_iter(&self) -> Hosts {
let (start, stop) = self.range();
Hosts {
state: start + 1,
stop: stop - 1,
}
}
}
impl PartialOrd for IpNetwork {
fn partial_cmp(&self, other: &IpNetwork) -> Option<Ordering> {
self.address().partial_cmp(&other.address())
}
}
impl Ord for IpNetwork {
fn cmp(&self, other: &IpNetwork) -> Ordering {
self.address().cmp(&other.address())
}
}
impl fmt::String for IpNetwork {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}/{}", self.address(), self.prefix())
}
}
#[derive(Copy, Clone)]
pub struct Hosts {
state: IpAddr,
stop: IpAddr,
}
impl Iterator for Hosts {
type Item = IpAddr;
fn next(&mut self) -> Option<IpAddr> {
if self.state <= self.stop {
let result = self.state;
self.state = self.state + 1;
Some(result)
} else {
None
}
}
}
impl DoubleEndedIterator for Hosts {
fn next_back(&mut self) -> Option<IpAddr> {
if self.stop >= self.state {
self.stop = self.stop - 1;
Some(self.stop)
} else {
None
}
}
}