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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use core::{
	fmt,
	str::FromStr,
};
use std::net::IpAddr;

use super::from_str::cidr_from_str;
use crate::{
	errors::*,
	Family,
	IpCidr,
	IpInet,
	Ipv4Cidr,
	Ipv6Cidr,
};

/// Represents either an IPv4 or an IPv6 network or "any".
///
/// Allows for a bit string representation which treats "any" as the
/// empty string, IPv4 as starting with `false` and IPv6 as starting
/// with `true`. After the first bit the normal represenation for the
/// picked address-family follows.
///
/// Setting the first bit (using the `bitstring` API) always truncates
/// the bit string to length 1 (i.e. `/0` in the resulting family).
///
/// The [`Cidr`] trait cannot be implemented for this type.
///
/// [`Cidr`]: crate::Cidr
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum AnyIpCidr {
	/// "any" network containing all IPv4 and IPv6 addresses
	Any,
	/// IPv4 network
	V4(Ipv4Cidr),
	/// IPv6 network
	V6(Ipv6Cidr),
}

impl AnyIpCidr {
	/// Whether representing any address
	pub const fn is_any(&self) -> bool {
		match self {
			Self::Any => true,
			_ => false,
		}
	}

	/// Whether representing an IPv4 network
	pub const fn is_ipv4(&self) -> bool {
		match self {
			Self::V4(_) => true,
			_ => false,
		}
	}

	/// Whether representing an IPv6 network
	pub const fn is_ipv6(&self) -> bool {
		match self {
			Self::V4(_) => false,
			_ => true,
		}
	}
}

// "Cidr" functions
impl AnyIpCidr {
	/// Create new network from address and prefix length.  If the
	/// network length exceeds the address length or the address is not
	/// the first address in the network ("host part not zero") an error
	/// is returned.
	pub const fn new(addr: IpAddr, len: u8) -> Result<Self, NetworkParseError> {
		match addr {
			IpAddr::V4(a) => match Ipv4Cidr::new(a, len) {
				Ok(cidr) => Ok(Self::V4(cidr)),
				Err(e) => Err(e),
			},
			IpAddr::V6(a) => match Ipv6Cidr::new(a, len) {
				Ok(cidr) => Ok(Self::V6(cidr)),
				Err(e) => Err(e),
			},
		}
	}

	/// Create a network containing a single address (network length =
	/// address length).
	pub const fn new_host(addr: IpAddr) -> Self {
		match addr {
			IpAddr::V4(a) => Self::V4(Ipv4Cidr::new_host(a)),
			IpAddr::V6(a) => Self::V6(Ipv6Cidr::new_host(a)),
		}
	}

	/// first address in the network as plain address
	///
	/// returns [`None`] for [`Any`]
	///
	/// [`Any`]: Self::Any
	pub const fn first_address(&self) -> Option<IpAddr> {
		match self {
			Self::Any => None,
			Self::V4(c) => Some(IpAddr::V4(c.first_address())),
			Self::V6(c) => Some(IpAddr::V6(c.first_address())),
		}
	}

	/// first address in the network
	///
	/// returns [`None`] for [`Any`]
	///
	/// [`Any`]: Self::Any
	pub const fn first(&self) -> Option<IpInet> {
		match self {
			Self::Any => None,
			Self::V4(c) => Some(IpInet::V4(c.first())),
			Self::V6(c) => Some(IpInet::V6(c.first())),
		}
	}

	/// last address in the network as plain address
	///
	/// returns [`None`] for [`Any`]
	///
	/// [`Any`]: Self::Any
	pub const fn last_address(&self) -> Option<IpAddr> {
		match self {
			Self::Any => None,
			Self::V4(c) => Some(IpAddr::V4(c.last_address())),
			Self::V6(c) => Some(IpAddr::V6(c.last_address())),
		}
	}

	/// last address in the network
	///
	/// returns [`None`] for [`Any`]
	///
	/// [`Any`]: Self::Any
	pub const fn last(&self) -> Option<IpInet> {
		match self {
			Self::Any => None,
			Self::V4(c) => Some(IpInet::V4(c.last())),
			Self::V6(c) => Some(IpInet::V6(c.last())),
		}
	}

	/// length in bits of the shared prefix of the contained addresses
	///
	/// returns [`None`] for [`Any`]
	///
	/// [`Any`]: Self::Any
	pub const fn network_length(&self) -> Option<u8> {
		match self {
			Self::Any => None,
			Self::V4(c) => Some(c.network_length()),
			Self::V6(c) => Some(c.network_length()),
		}
	}

	/// IP family of the contained address ([`Ipv4`] or [`Ipv6`]).
	///
	/// returns [`None`] for [`Any`]
	///
	/// [`Any`]: Self::Any
	/// [`Ipv4`]: Family::Ipv4
	/// [`Ipv6`]: Family::Ipv6
	pub const fn family(&self) -> Option<Family> {
		match self {
			Self::Any => None,
			Self::V4(_) => Some(Family::Ipv4),
			Self::V6(_) => Some(Family::Ipv6),
		}
	}

	/// whether network represents a single host address
	pub const fn is_host_address(&self) -> bool {
		match self {
			Self::Any => false,
			Self::V4(c) => c.is_host_address(),
			Self::V6(c) => c.is_host_address(),
		}
	}

	/// network mask: an pseudo address which has the first `network
	/// length` bits set to 1 and the remaining to 0.
	///
	/// returns [`None`] for [`Any`]
	///
	/// [`Any`]: Self::Any
	pub const fn mask(&self) -> Option<IpAddr> {
		match self {
			Self::Any => None,
			Self::V4(c) => Some(IpAddr::V4(c.mask())),
			Self::V6(c) => Some(IpAddr::V6(c.mask())),
		}
	}

	/// check whether an address is contained in the network
	pub const fn contains(&self, addr: &IpAddr) -> bool {
		match self {
			Self::Any => true,
			Self::V4(c) => match addr {
				IpAddr::V4(a) => c.contains(a),
				IpAddr::V6(_) => false,
			},
			Self::V6(c) => match addr {
				IpAddr::V4(_) => false,
				IpAddr::V6(a) => c.contains(a),
			},
		}
	}
}

impl fmt::Display for AnyIpCidr {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::Any => write!(f, "any"),
			Self::V4(c) => fmt::Display::fmt(c, f),
			Self::V6(c) => fmt::Display::fmt(c, f),
		}
	}
}

impl From<AnyIpCidr> for Option<IpCidr> {
	fn from(value: AnyIpCidr) -> Option<IpCidr> {
		match value {
			AnyIpCidr::Any => None,
			AnyIpCidr::V4(c) => Some(IpCidr::V4(c)),
			AnyIpCidr::V6(c) => Some(IpCidr::V6(c)),
		}
	}
}

impl From<Option<IpCidr>> for AnyIpCidr {
	fn from(a: Option<IpCidr>) -> Self {
		match a {
			None => Self::Any,
			Some(IpCidr::V4(c)) => Self::V4(c),
			Some(IpCidr::V6(c)) => Self::V6(c),
		}
	}
}

impl FromStr for AnyIpCidr {
	type Err = NetworkParseError;

	fn from_str(s: &str) -> Result<Self, NetworkParseError> {
		if s == "any" {
			Ok(Self::Any)
		} else {
			cidr_from_str::<IpCidr>(s).map(Self::from)
		}
	}
}

impl From<IpCidr> for AnyIpCidr {
	fn from(c: IpCidr) -> Self {
		match c {
			IpCidr::V4(c) => Self::V4(c),
			IpCidr::V6(c) => Self::V6(c),
		}
	}
}

impl From<Ipv4Cidr> for AnyIpCidr {
	fn from(c: Ipv4Cidr) -> Self {
		Self::V4(c)
	}
}

impl From<Ipv6Cidr> for AnyIpCidr {
	fn from(c: Ipv6Cidr) -> Self {
		Self::V6(c)
	}
}

#[cfg(feature = "bitstring")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "bitstring")))]
impl bitstring::BitString for AnyIpCidr {
	fn get(&self, ndx: usize) -> bool {
		assert!(!self.is_any());
		if 0 == ndx {
			self.is_ipv6()
		} else {
			match self {
				Self::Any => unreachable!(),
				Self::V4(c) => c.get(ndx - 1),
				Self::V6(c) => c.get(ndx - 1),
			}
		}
	}

	fn set(&mut self, ndx: usize, bit: bool) {
		assert!(!self.is_any());
		if 0 == ndx {
			if bit {
				*self = Self::V6(Ipv6Cidr::null());
			} else {
				*self = Self::V4(Ipv4Cidr::null());
			}
		} else {
			match self {
				Self::Any => unreachable!(),
				Self::V4(ref mut c) => c.set(ndx - 1, bit),
				Self::V6(ref mut c) => c.set(ndx - 1, bit),
			}
		}
	}

	fn flip(&mut self, ndx: usize) {
		assert!(!self.is_any());
		if 0 == ndx {
			if self.is_ipv6() {
				*self = Self::V4(Ipv4Cidr::null())
			} else {
				*self = Self::V6(Ipv6Cidr::null())
			}
		} else {
			match self {
				Self::Any => unreachable!(),
				Self::V4(ref mut c) => c.flip(ndx - 1),
				Self::V6(ref mut c) => c.flip(ndx - 1),
			}
		}
	}

	fn len(&self) -> usize {
		match self {
			Self::Any => 0,
			Self::V4(c) => c.len() + 1,
			Self::V6(c) => c.len() + 1,
		}
	}

	fn clip(&mut self, len: usize) {
		// max length is 129 (len(IPv6) + 1)
		if len > 128 {
			return;
		}
		if 0 == len {
			*self = Self::Any;
		} else {
			match self {
				Self::Any => (),
				Self::V4(ref mut c) => c.clip(len - 1),
				Self::V6(ref mut c) => c.clip(len - 1),
			}
		}
	}

	fn append(&mut self, bit: bool) {
		match self {
			Self::Any => {
				if bit {
					*self = Self::V6(Ipv6Cidr::null());
				} else {
					*self = Self::V4(Ipv4Cidr::null());
				}
			},
			Self::V4(ref mut c) => c.append(bit),
			Self::V6(ref mut c) => c.append(bit),
		}
	}

	fn null() -> Self {
		Self::Any
	}

	fn shared_prefix_len(&self, other: &Self) -> usize {
		match (self, other) {
			(Self::V4(a), Self::V4(b)) => 1 + a.shared_prefix_len(b),
			(Self::V6(a), Self::V6(b)) => 1 + a.shared_prefix_len(b),
			_ => 0,
		}
	}
}