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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::net::{AddrParseError, IpAddr, Ipv4Addr};
use std::str::FromStr;
use multistr::StringVec;
use multistr::vec::Iter as SVIter;
static INVALID_CHARS: &[char] = &[
'\0', '\u{0009}', '\u{000a}', '\u{000d}', '\u{0020}',
'#', '%', '/', ':', '?', '@', '[', '\\', ']'
];
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct DataLine {
ip: IpAddr,
hosts: StringVec,
}
impl DataLine {
pub fn from_raw(ip: IpAddr, hosts: StringVec) -> DataLine {
DataLine { ip, hosts }
}
pub fn ip(&self) -> IpAddr {
self.ip
}
pub fn hosts(&self) -> Hosts {
Hosts { inner: Some(self.hosts.iter()) }
}
}
pub fn minify_lines(lines: &mut Vec<DataLine>) {
let mut min = BTreeMap::new();
for line in lines.drain(..) {
min.entry(line.ip()).or_insert_with(Vec::new).extend(line.hosts().map(ToOwned::to_owned));
}
for (ip, mut hosts) in min {
hosts.sort();
hosts.dedup();
lines.push(DataLine::from_raw(ip, hosts.iter().collect()));
}
}
pub fn empty_hosts() -> Hosts<'static> {
Hosts { inner: None }
}
pub struct Hosts<'a> {
inner: Option<SVIter<'a>>,
}
impl<'a> Iterator for Hosts<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
self.inner.as_mut().and_then(|inner| inner.next())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DataParseError {
NoInternalSpace,
HostWasIp(Ipv4Addr),
BadHost(char, String),
BadIp(AddrParseError, String),
}
impl Error for DataParseError {
fn description(&self) -> &str {
match *self {
DataParseError::NoInternalSpace => {
"line had no space between IP and hosts"
}
DataParseError::HostWasIp(_) => {
"an IP was given where a domain should have been"
}
DataParseError::BadHost(_, _) => {
"a host was invalid because it contains an invalid character"
}
DataParseError::BadIp(_, _) => {
"could not parse IP"
}
}
}
fn cause(&self) -> Option<&Error> {
if let DataParseError::BadIp(ref err, _) = *self {
Some(err)
} else {
None
}
}
}
impl fmt::Display for DataParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
DataParseError::NoInternalSpace => {
write!(f, "line had no space between IP and hosts")
}
DataParseError::HostWasIp(ref ip) => {
write!(f, "the IP {} was given instead of a domain", ip)
}
DataParseError::BadHost(ref ch, ref host) => {
write!(f, "the host {:?} is invalid because it contains {:?}", host, ch)
}
DataParseError::BadIp(_, ref ip) => {
write!(f, "could not parse {:?} as an IP", ip)
}
}
}
}
impl FromStr for DataLine {
type Err = DataParseError;
fn from_str(s: &str) -> Result<DataLine, DataParseError> {
let s = s.trim();
if let Some(idx) = s.find(char::is_whitespace) {
let ip = s[..idx].parse().map_err(|err| DataParseError::BadIp(err,
s[..idx].to_owned()))?;
let mut hosts = StringVec::new();
for host in s[idx..].split_whitespace() {
if let Some(idx) = host.find(INVALID_CHARS) {
return Err(DataParseError::BadHost(host[idx..].chars().next().unwrap(),
host.to_owned()))
} else if let Ok(ipv4) = host.parse(): Result<Ipv4Addr, _> {
return Err(DataParseError::HostWasIp(ipv4))
} else {
hosts.push(host);
}
}
Ok(DataLine { ip, hosts })
} else {
Err(DataParseError::NoInternalSpace)
}
}
}
impl fmt::Display for DataLine {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} ", self.ip())?;
for host in self.hosts() {
write!(f, " {}", host)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use super::*;
#[test]
fn only_ip() {
let line: Result<DataLine, _> = " ::1 ".parse();
assert_eq!(line, Err(DataParseError::NoInternalSpace))
}
#[test]
fn wrong_order() {
let line: Result<DataLine, _> = "localhost ::1".parse();
if let Err(DataParseError::BadIp(_, ip)) = line {
assert_eq!(ip, "localhost");
} else {
panic!("not a bad IP: {:?}", line);
}
}
#[test]
fn two_ipv4() {
let line: Result<DataLine, _> = "127.0.0.1 0.0.0.0".parse();
if let Err(DataParseError::HostWasIp(ip)) = line {
assert_eq!(ip, Ipv4Addr::new(0, 0, 0, 0));
} else {
panic!("not host-was-IP: {:?}", line);
}
}
#[test]
fn two_ipv6() {
let line: Result<DataLine, _> = "::1 localhost ::1".parse();
if let Err(DataParseError::BadHost(':', host)) = line {
assert_eq!(host, "::1");
} else {
panic!("not a bad host: {:?}", line);
}
}
#[test]
fn good() {
let line: DataLine = "::1 localhost localhost.localdomain lh".parse().unwrap();
assert_eq!(line.ip(), IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
let hosts: Vec<&str> = line.hosts().collect();
assert_eq!(hosts, &["localhost", "localhost.localdomain", "lh"]);
}
#[test]
fn ascii_host() {
let line: DataLine = "::1 the-quick-brown-fox-jumped-over-the-lazy-dog-0123456789.com".parse().unwrap();
assert_eq!(line.ip(), IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
let hosts: Vec<&str> = line.hosts().collect();
assert_eq!(hosts, &["the-quick-brown-fox-jumped-over-the-lazy-dog-0123456789.com"]);
}
}