Skip to main content

zond_engine/model/ip/
range.rs

1// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
2//
3// This file is part of Zond Engine, licensed under the GNU Affero General
4// Public License, version 3 or later. See the LICENSE file for details, or
5// <https://www.gnu.org/licenses/agpl-3.0.html>.
6//
7// SPDX-License-Identifier: AGPL-3.0-or-later
8
9//! # Contiguous runs of addresses
10//!
11//! A range is two addresses and everything between them, inclusive at both ends: how a
12//! `/8` is held without holding its addresses. It is the unit
13//! [`IpSet`](super::set::IpSet) is built from.
14//!
15//! [`Ipv4Range`] and [`Ipv6Range`] are separate types because the arithmetic differs: a
16//! v4 range's length always fits a `u64`, a v6 range's can exceed a `u128`. [`IpRange`]
17//! is the enum over both.
18//!
19//! The families never compare: `::ffff:192.0.2.1` is an IPv6 address here. Membership
20//! across families is `false`, not an error, since callers are filtering received
21//! packets.
22
23use std::{
24    net::{IpAddr, Ipv4Addr, Ipv6Addr},
25    str::FromStr,
26};
27use thiserror::Error;
28
29/// Why a range could not be built or read.
30///
31/// [`InvalidFormat`](Self::InvalidFormat), [`AddrParse`](Self::AddrParse) and
32/// [`PrefixParse`](Self::PrefixParse) mean "not a range" (which a hostname also looks
33/// like); the other two mean "a range, but wrong". [`parse::ip`](crate::model::parse::ip)
34/// depends on that split.
35#[non_exhaustive]
36#[derive(Debug, Clone, PartialEq, Eq, Error)]
37pub enum IpError {
38    /// The start address is above the end. Both are named.
39    #[error("Invalid range: start address {0} is greater than end address {1}")]
40    InvalidRange(IpAddr, IpAddr),
41
42    /// A CIDR prefix longer than its family allows.
43    ///
44    /// The message omits the bound, since the family is not carried;
45    /// [`IpParseError::InvalidPrefix`](crate::model::parse::ip::IpParseError::InvalidPrefix)
46    /// names both.
47    #[error("Invalid CIDR prefix: {0}")]
48    InvalidPrefix(u8),
49
50    /// Not an address at all, on either side of a separator.
51    #[error("Failed to parse IP address: {0}")]
52    AddrParse(#[from] std::net::AddrParseError),
53
54    /// Recognisably a range, having a separator, but not one this grammar
55    /// accepts.
56    #[error("Invalid IP range format: {0}")]
57    InvalidFormat(String),
58
59    /// The text after `/` was not a number.
60    #[error("Invalid prefix number format: {0}")]
61    PrefixParse(#[from] std::num::ParseIntError),
62}
63
64// ══════════════════════════════════════════════════════════════════════════════
65// IPv4 Range
66// ══════════════════════════════════════════════════════════════════════════════
67
68/// A contiguous run of IPv4 addresses, inclusive at both ends.
69///
70/// Eight bytes, whatever the range covers. [`new`](Self::new) guarantees the start is
71/// never above the end.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub struct Ipv4Range {
74    /// The inclusive starting address of the range.
75    start_addr: Ipv4Addr,
76    /// The inclusive ending address of the range.
77    end_addr: Ipv4Addr,
78}
79
80impl Ipv4Range {
81    /// Creates a new `Ipv4Range`.
82    ///
83    /// # Errors
84    ///
85    /// Returns [`IpError::InvalidRange`] if `start` is numerically greater than `end`.
86    pub fn new(start: Ipv4Addr, end: Ipv4Addr) -> Result<Self, IpError> {
87        if u32::from(start) <= u32::from(end) {
88            Ok(Self {
89                start_addr: start,
90                end_addr: end,
91            })
92        } else {
93            Err(IpError::InvalidRange(IpAddr::V4(start), IpAddr::V4(end)))
94        }
95    }
96
97    /// Returns an iterator over every [`IpAddr`] within the range.
98    ///
99    /// # Performance
100    ///
101    /// Iterating over large ranges (e.g., /8) is fast, but collecting the results
102    /// into a `Vec` will consume significant memory.
103    pub fn iter(&self) -> impl Iterator<Item = IpAddr> {
104        let start: u32 = self.start_addr.into();
105        let end: u32 = self.end_addr.into();
106        (start..=end).map(|ip| IpAddr::V4(Ipv4Addr::from(ip)))
107    }
108
109    /// A range covering the single address `addr`.
110    ///
111    /// Infallible, unlike [`new`](Self::new).
112    pub const fn single(addr: Ipv4Addr) -> Self {
113        Self {
114            start_addr: addr,
115            end_addr: addr,
116        }
117    }
118
119    /// The inclusive first address.
120    pub fn start_addr(&self) -> Ipv4Addr {
121        self.start_addr
122    }
123
124    /// The inclusive last address, never lower than
125    /// [`start_addr`](Self::start_addr).
126    pub fn end_addr(&self) -> Ipv4Addr {
127        self.end_addr
128    }
129
130    /// Extends this range to reach `end`, if it does not already.
131    ///
132    /// The only mutation a range allows, used to merge adjacent ranges. Growing the end
133    /// cannot invert the range.
134    pub fn extend_end_to(&mut self, end: Ipv4Addr) {
135        if end > self.end_addr {
136            self.end_addr = end;
137        }
138    }
139
140    /// Checks if the given [`Ipv4Addr`] falls within this range (inclusive).
141    pub fn contains(&self, ip: &Ipv4Addr) -> bool {
142        (u32::from(self.start_addr)..=u32::from(self.end_addr)).contains(&u32::from(*ip))
143    }
144
145    /// How many addresses the range covers, never fewer than one.
146    ///
147    /// No `is_empty`: a range always holds at least one address, unlike an
148    /// [`IpSet`](crate::model::ip::set::IpSet::is_empty).
149    #[allow(clippy::len_without_is_empty)]
150    pub fn len(&self) -> u64 {
151        let s_u32: u64 = u32::from(self.start_addr) as u64;
152        let e_u32: u64 = u32::from(self.end_addr) as u64;
153        (e_u32 - s_u32) + 1
154    }
155}
156
157// ══════════════════════════════════════════════════════════════════════════════
158// IPv6 Range
159// ══════════════════════════════════════════════════════════════════════════════
160
161/// A contiguous run of IPv6 addresses, inclusive at both ends, together with the
162/// interface they are valid on if they need one.
163///
164/// The start is never above the end, for the reason [`Ipv4Range`] gives.
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
166pub struct Ipv6Range {
167    /// The inclusive starting address of the range.
168    start_addr: Ipv6Addr,
169    /// The inclusive ending address of the range.
170    end_addr: Ipv6Addr,
171    /// The interface these addresses are valid on, as a scope id, for a range
172    /// of link-local addresses.
173    ///
174    /// The index only, so this type stays `Copy`; the index is all a socket needs. The
175    /// name lives on [`Zone`](crate::model::ip::scoped::Zone).
176    ///
177    /// `None` except for link-local ranges. See
178    /// [`ScopedIp`](crate::model::ip::scoped::ScopedIp).
179    zone: Option<u32>,
180}
181
182impl Ipv6Range {
183    /// Creates a new `Ipv6Range`.
184    ///
185    /// # Errors
186    ///
187    /// Returns [`IpError::InvalidRange`] if `start` is numerically greater than `end`.
188    pub fn new(start: Ipv6Addr, end: Ipv6Addr) -> Result<Self, IpError> {
189        Self::scoped(start, end, None)
190    }
191
192    /// Creates an `Ipv6Range` valid on the interface with scope id `zone`.
193    ///
194    /// `Some(0)` is read as `None`: zero is a failed name lookup (see
195    /// [`Zone::new`](crate::model::ip::scoped::Zone::new)), and kept it would hide the
196    /// problem from [`is_ambiguous`](Self::is_ambiguous).
197    ///
198    /// # Errors
199    ///
200    /// Returns [`IpError::InvalidRange`] if `start` is numerically greater than
201    /// `end`.
202    pub fn scoped(start: Ipv6Addr, end: Ipv6Addr, zone: Option<u32>) -> Result<Self, IpError> {
203        if u128::from(start) <= u128::from(end) {
204            Ok(Self {
205                start_addr: start,
206                end_addr: end,
207                zone: zone.filter(|index| *index != 0),
208            })
209        } else {
210            Err(IpError::InvalidRange(IpAddr::V6(start), IpAddr::V6(end)))
211        }
212    }
213
214    /// A range covering the single address `addr`, on no particular interface.
215    /// The counterpart of [`Ipv4Range::single`].
216    pub const fn single(addr: Ipv6Addr) -> Self {
217        Self {
218            start_addr: addr,
219            end_addr: addr,
220            zone: None,
221        }
222    }
223
224    /// The inclusive first address.
225    pub fn start_addr(&self) -> Ipv6Addr {
226        self.start_addr
227    }
228
229    /// The inclusive last address, never lower than
230    /// [`start_addr`](Self::start_addr).
231    pub fn end_addr(&self) -> Ipv6Addr {
232        self.end_addr
233    }
234
235    /// Extends this range to reach `end`, if it does not already. See
236    /// [`Ipv4Range::extend_end_to`].
237    pub fn extend_end_to(&mut self, end: Ipv6Addr) {
238        if end > self.end_addr {
239            self.end_addr = end;
240        }
241    }
242
243    /// The interface these addresses are valid on, as a scope id, if they need
244    /// one.
245    pub fn zone(&self) -> Option<u32> {
246        self.zone
247    }
248
249    /// Whether these addresses are meaningless without an interface to
250    /// interpret them against, and none is recorded.
251    ///
252    /// Such a range cannot be probed: every interface holds an `fe80::/64`, so which
253    /// segment was meant cannot be told.
254    ///
255    /// True where *any* of the range is link-local, so `fe00::-fe80::5`, which starts
256    /// outside it, counts.
257    pub fn is_ambiguous(&self) -> bool {
258        self.zone.is_none() && self.covers_link_local()
259    }
260
261    /// Whether any address in the range is in `fe80::/10`.
262    pub fn covers_link_local(&self) -> bool {
263        u128::from(self.start_addr) <= LINK_LOCAL_LAST
264            && u128::from(self.end_addr) >= LINK_LOCAL_FIRST
265    }
266
267    /// Whether every address in the range is in `fe80::/10`.
268    ///
269    /// What a `%zone` suffix requires of the range it is written on.
270    pub fn is_link_local(&self) -> bool {
271        u128::from(self.start_addr) >= LINK_LOCAL_FIRST
272            && u128::from(self.end_addr) <= LINK_LOCAL_LAST
273    }
274
275    /// The IPv4 range this range spells, when it lies wholly inside the
276    /// IPv4-mapped block `::ffff:0:0/96`.
277    ///
278    /// RFC 4291 §2.5.5.2 writes an IPv4 address inside an IPv6 one that way, and a
279    /// dual-stack socket handed `::ffff:192.0.2.1` connects to `192.0.2.1`.
280    ///
281    /// [`None`] when either end lies outside the block, including a range like `::/0`
282    /// that merely contains it.
283    pub(crate) fn spelled_ipv4(&self) -> Option<Ipv4Range> {
284        // The block is contiguous, so both ends inside means the whole range is.
285        let start = self.start_addr.to_ipv4_mapped()?;
286        let end = self.end_addr.to_ipv4_mapped()?;
287        Ipv4Range::new(start, end).ok()
288    }
289
290    /// Returns an iterator over every [`IpAddr`] within the range.
291    ///
292    /// # Warning
293    ///
294    /// IPv6 ranges can be astronomically large: iterating a `/64` does not finish. For
295    /// small ranges.
296    pub fn iter(&self) -> impl Iterator<Item = IpAddr> {
297        let start: u128 = self.start_addr.into();
298        let end: u128 = self.end_addr.into();
299        (start..=end).map(|ip| IpAddr::V6(Ipv6Addr::from(ip)))
300    }
301
302    /// Checks if the given [`Ipv6Addr`] falls within this range (inclusive).
303    ///
304    /// Ignores the zone, like [`IpSet::contains`](super::set::IpSet::contains): a
305    /// received packet carries a bare address.
306    pub fn contains(&self, ip: &Ipv6Addr) -> bool {
307        (u128::from(self.start_addr)..=u128::from(self.end_addr)).contains(&u128::from(*ip))
308    }
309
310    /// Whether any address falls in both ranges.
311    ///
312    /// Ignores the zone, as [`contains`](Self::contains) does, so a caller can compare
313    /// zones of overlapping ranges.
314    pub fn overlaps(&self, other: &Self) -> bool {
315        u128::from(self.start_addr) <= u128::from(other.end_addr)
316            && u128::from(other.start_addr) <= u128::from(self.end_addr)
317    }
318
319    /// How many addresses the range covers, never fewer than one. See
320    /// [`Ipv4Range::len`] for why there is no `is_empty` beside it.
321    ///
322    /// `::/0` covers 2^128 addresses, one more than a `u128` holds, so the count
323    /// saturates at [`u128::MAX`]. Wrapping would report the whole of IPv6 as zero and
324    /// pass a budget check.
325    #[allow(clippy::len_without_is_empty)]
326    pub fn len(&self) -> u128 {
327        let s_u128: u128 = u128::from(self.start_addr);
328        let e_u128: u128 = u128::from(self.end_addr);
329        (e_u128 - s_u128).saturating_add(1)
330    }
331}
332
333/// The first and last address of `fe80::/10`, the block
334/// [`Ipv6Addr::is_unicast_link_local`] answers for.
335///
336/// Written out because the predicate takes one address and a range is two. A test
337/// checks they agree at all four boundaries.
338const LINK_LOCAL_FIRST: u128 = 0xfe80 << 112;
339const LINK_LOCAL_LAST: u128 = (0xfebf << 112) | ((1u128 << 112) - 1);
340
341// ══════════════════════════════════════════════════════════════════════════════
342// Unified IpRange API
343// ══════════════════════════════════════════════════════════════════════════════
344
345/// Either family's range, for a caller that does not care which it was handed.
346///
347/// What [`FromStr`] produces, since the text decides the family.
348///
349/// Not `#[non_exhaustive]`: there is no third address family, so matching both arms is
350/// exhaustive.
351#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
352pub enum IpRange {
353    /// An IPv4 address range.
354    V4(Ipv4Range),
355    /// An IPv6 address range.
356    V6(Ipv6Range),
357}
358
359impl IpRange {
360    /// Every address the range holds, ascending.
361    ///
362    /// Boxed, since the families iterate as different types, as in
363    /// [`IpSet::iter`](super::set::IpSet::iter). Iterating a wide IPv6 range does not
364    /// finish.
365    pub fn iter(&self) -> Box<dyn Iterator<Item = IpAddr> + Send + '_> {
366        match self {
367            IpRange::V4(range) => Box::new(range.iter()),
368            IpRange::V6(range) => Box::new(range.iter()),
369        }
370    }
371
372    /// Returns the start address of the range as an [`IpAddr`].
373    pub fn start_addr(&self) -> IpAddr {
374        match self {
375            IpRange::V4(r) => IpAddr::V4(r.start_addr),
376            IpRange::V6(r) => IpAddr::V6(r.start_addr),
377        }
378    }
379
380    /// Returns the end address of the range as an [`IpAddr`].
381    pub fn end_addr(&self) -> IpAddr {
382        match self {
383            IpRange::V4(r) => IpAddr::V4(r.end_addr),
384            IpRange::V6(r) => IpAddr::V6(r.end_addr),
385        }
386    }
387
388    /// Checks if the given [`IpAddr`] falls within this range.
389    ///
390    /// Returns `false` if the protocol versions do not match (e.g., checking
391    /// if a V6 address is in a V4 range).
392    pub fn contains(&self, ip: &IpAddr) -> bool {
393        match (self, ip) {
394            (IpRange::V4(r), IpAddr::V4(ip)) => r.contains(ip),
395            (IpRange::V6(r), IpAddr::V6(ip)) => r.contains(ip),
396            _ => false,
397        }
398    }
399
400    /// How many addresses the range covers, never fewer than one. See
401    /// [`Ipv4Range::len`] for why there is no `is_empty` beside it.
402    #[allow(clippy::len_without_is_empty)]
403    pub fn len(&self) -> u128 {
404        match self {
405            IpRange::V4(r) => r.len() as u128,
406            IpRange::V6(r) => r.len(),
407        }
408    }
409}
410
411impl FromStr for IpRange {
412    type Err = IpError;
413
414    /// Parses an IP range from a string.
415    ///
416    /// Supports:
417    /// - CIDR notation: `192.0.2.0/24`, `2001:db8::/32`
418    /// - Hyphenated ranges: `198.51.100.1-198.51.100.5`, `::1-::f`
419    /// - Shortened IPv4 ranges, where the end continues the start's octets:
420    ///   `10.0.0.1-50`, `192.168.1.1-2.254`
421    /// - Single IPs: `1.1.1.1`, `::1`
422    ///
423    /// The whole range grammar: everything in the crate that reads a written range ends
424    /// here.
425    fn from_str(s: &str) -> Result<Self, Self::Err> {
426        let s = s.trim();
427
428        // CIDR
429        if let Some(pos) = s.find('/') {
430            let ip = s[..pos].parse::<IpAddr>()?;
431            let prefix = s[pos + 1..].parse::<u8>()?;
432            return cidr_range(ip, prefix);
433        }
434
435        // Hyphenated range
436        if let Some(pos) = s.find('-') {
437            // Not trimmed around the separator: `IpSet` splits on spaces, so
438            // `192.0.2.1 - 192.0.2.5` arrives as three tokens there, and trimming
439            // here would make a second dialect.
440            let start_str = &s[..pos];
441            let end_str = &s[pos + 1..];
442
443            if let Ok(start) = start_str.parse::<Ipv4Addr>() {
444                let end = expand_v4_end(start, end_str)
445                    .ok_or_else(|| IpError::InvalidFormat(s.to_string()))?;
446                return Ok(IpRange::V4(Ipv4Range::new(start, end)?));
447            } else if let Ok(start) = start_str.parse::<Ipv6Addr>() {
448                let end = end_str.parse::<Ipv6Addr>()?;
449                return Ok(IpRange::V6(Ipv6Range::new(start, end)?));
450            }
451            return Err(IpError::InvalidFormat(s.to_string()));
452        }
453
454        // Single address
455        match s.parse::<IpAddr>()? {
456            IpAddr::V4(v4) => Ok(IpRange::V4(Ipv4Range::single(v4))),
457            IpAddr::V6(v6) => Ok(IpRange::V6(Ipv6Range::single(v6))),
458        }
459    }
460}
461
462/// Reads the end of an IPv4 range, which may be written in full or as however
463/// many trailing octets differ from the start.
464///
465/// `10.0.0.1-50` ends at `10.0.0.50` and `192.168.1.1-2.254` at `192.168.2.254`: the
466/// octets given replace as many octets at the end of the start address.
467///
468/// IPv4 only: an IPv6 form would make `::1-5` ambiguous with a hex group.
469fn expand_v4_end(start: Ipv4Addr, end_str: &str) -> Option<Ipv4Addr> {
470    if let Ok(full) = end_str.parse::<Ipv4Addr>() {
471        return Some(full);
472    }
473
474    let suffix: Vec<u8> = end_str.split('.').map(octet).collect::<Option<_>>()?;
475
476    if suffix.is_empty() || suffix.len() > 4 {
477        return None;
478    }
479
480    let mut octets = start.octets();
481    octets[4 - suffix.len()..].copy_from_slice(&suffix);
482    Some(Ipv4Addr::from(octets))
483}
484
485/// One octet of a shortened range's end, read as strictly as an address's own.
486///
487/// `u8::from_str` accepts a leading `+` and a leading zero, but `Ipv4Addr::from_str`
488/// refuses a leading zero since 1.53, because `010` is octal to enough software to
489/// matter. Both halves of a range must use the same rules.
490fn octet(part: &str) -> Option<u8> {
491    if part.len() > 1 && part.starts_with('0') {
492        return None;
493    }
494    if !part.bytes().all(|byte| byte.is_ascii_digit()) {
495        return None;
496    }
497    part.parse().ok()
498}
499
500/// Constructs an [`IpRange`] from an IP address and a CIDR prefix length.
501///
502/// # Examples
503///
504/// ```
505/// use zond_engine::model::ip::range::{cidr_range, IpRange};
506/// use std::net::IpAddr;
507///
508/// let range = cidr_range("192.0.2.5".parse().unwrap(), 24).unwrap();
509/// assert_eq!(range.len(), 256);
510/// ```
511pub fn cidr_range(ip: IpAddr, prefix: u8) -> Result<IpRange, IpError> {
512    match ip {
513        IpAddr::V4(v4) => {
514            if prefix > 32 {
515                return Err(IpError::InvalidPrefix(prefix));
516            }
517
518            // `/0` needs no special case: `checked_shr(0)` is the whole mask.
519            let ip_u32 = u32::from(v4);
520            let mask = !u32::MAX.checked_shr(u32::from(prefix)).unwrap_or(0);
521
522            let network = ip_u32 & mask;
523            let broadcast = ip_u32 | !mask;
524
525            Ok(IpRange::V4(
526                Ipv4Range::new(Ipv4Addr::from(network), Ipv4Addr::from(broadcast)).unwrap_or_else(
527                    |_| unreachable!("a network address is never above its own broadcast"),
528                ),
529            ))
530        }
531        IpAddr::V6(v6) => {
532            if prefix > 128 {
533                return Err(IpError::InvalidPrefix(prefix));
534            }
535
536            let ip_u128 = u128::from(v6);
537            let mask = !u128::MAX.checked_shr(u32::from(prefix)).unwrap_or(0);
538
539            let network = ip_u128 & mask;
540            let broadcast = ip_u128 | !mask;
541
542            Ok(IpRange::V6(
543                Ipv6Range::new(Ipv6Addr::from(network), Ipv6Addr::from(broadcast)).unwrap_or_else(
544                    |_| unreachable!("a network address is never above its own broadcast"),
545                ),
546            ))
547        }
548    }
549}
550
551// ╔════════════════════════════════════════════╗
552// ║ ████████╗███████╗███████╗████████╗███████╗ ║
553// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
554// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
555// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
556// ║    ██║   ███████╗███████║   ██║   ███████║ ║
557// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
558// ╚════════════════════════════════════════════╝
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563
564    /// A range holds nothing beyond its inclusive endpoints.
565    #[test]
566    fn a_range_holds_both_its_bounds_and_nothing_outside_them() {
567        let v4 = Ipv4Range::new(
568            Ipv4Addr::new(203, 0, 113, 10),
569            Ipv4Addr::new(203, 0, 113, 20),
570        )
571        .unwrap();
572        assert!(v4.contains(&Ipv4Addr::new(203, 0, 113, 10)));
573        assert!(v4.contains(&Ipv4Addr::new(203, 0, 113, 20)));
574        assert!(!v4.contains(&Ipv4Addr::new(203, 0, 113, 9)));
575        assert!(!v4.contains(&Ipv4Addr::new(203, 0, 113, 21)));
576
577        let v6 = Ipv6Range::new(Ipv6Addr::from(100), Ipv6Addr::from(200)).unwrap();
578        assert_eq!(v6.len(), 101, "inclusive at both ends");
579        assert!(v6.contains(&Ipv6Addr::from(100)));
580        assert!(v6.contains(&Ipv6Addr::from(200)));
581        assert!(!v6.contains(&Ipv6Addr::from(201)));
582    }
583
584    /// The ends of each address space, where the arithmetic that counts a range
585    /// is one step from overflowing.
586    ///
587    /// `::/0` saturates at `u128::MAX`.
588    #[test]
589    fn the_extremes_of_each_address_space_saturate_rather_than_wrap() {
590        let top_of_v4 = Ipv4Range::new(
591            Ipv4Addr::new(255, 255, 255, 254),
592            Ipv4Addr::new(255, 255, 255, 255),
593        )
594        .unwrap();
595        assert_eq!(top_of_v4.len(), 2);
596
597        let sixty_four = cidr_range(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 64).unwrap();
598        assert_eq!(sixty_four.len(), 1u128 << 64);
599
600        let everything = cidr_range(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0).unwrap();
601        assert_eq!(everything.len(), u128::MAX, "saturated, never zero");
602    }
603
604    /// Ascending, with no address skipped or repeated.
605    #[test]
606    fn iteration_yields_every_address_in_ascending_order() {
607        let v4 = Ipv4Range::new(Ipv4Addr::new(1, 1, 1, 1), Ipv4Addr::new(1, 1, 1, 3)).unwrap();
608        assert_eq!(
609            v4.iter().collect::<Vec<_>>(),
610            [
611                IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
612                IpAddr::V4(Ipv4Addr::new(1, 1, 1, 2)),
613                IpAddr::V4(Ipv4Addr::new(1, 1, 1, 3)),
614            ]
615        );
616
617        let v6 = Ipv6Range::new(Ipv6Addr::from(1), Ipv6Addr::from(3)).unwrap();
618        assert_eq!(
619            v6.iter().collect::<Vec<_>>(),
620            [
621                IpAddr::V6(Ipv6Addr::from(1)),
622                IpAddr::V6(Ipv6Addr::from(2)),
623                IpAddr::V6(Ipv6Addr::from(3)),
624            ]
625        );
626    }
627
628    /// Every form the grammar accepts, and what each covers.
629    ///
630    /// Target files, imported reports and command lines all read ranges here.
631    #[test]
632    fn every_written_form_names_the_range_it_says_it_does() {
633        for (written, first, last) in [
634            ("8.8.8.8", "8.8.8.8", "8.8.8.8"),
635            ("198.51.100.0/24", "198.51.100.0", "198.51.100.255"),
636            ("192.0.2.5/24", "192.0.2.0", "192.0.2.255"),
637            ("1.1.1.1-1.1.1.5", "1.1.1.1", "1.1.1.5"),
638            ("198.51.100.1-50", "198.51.100.1", "198.51.100.50"),
639            ("192.168.1.1-2.254", "192.168.1.1", "192.168.2.254"),
640            ("::1", "::1", "::1"),
641            ("::1/120", "::", "::ff"),
642            ("2001:db8::1-2001:db8::5", "2001:db8::1", "2001:db8::5"),
643        ] {
644            let range: IpRange = written.parse().unwrap_or_else(|e| panic!("{written}: {e}"));
645
646            assert_eq!(range.start_addr().to_string(), first, "{written} starts");
647            assert_eq!(range.end_addr().to_string(), last, "{written} ends");
648        }
649    }
650
651    /// One grammar for both halves of a range.
652    ///
653    /// A leading zero or sign is refused on either side of the hyphen.
654    #[test]
655    fn both_halves_of_a_range_read_octets_the_same_way() {
656        for spelling in [
657            "010.0.0.1",             // as a start
658            "198.51.100.1-010",      // as an end
659            "198.51.100.1-0.0.0.50", // in a longer suffix
660            "198.51.100.1-+50",      // a sign is not an octet either
661            "198.51.100.1- 50",      // nor is one with space around it
662        ] {
663            assert!(
664                spelling.parse::<IpRange>().is_err(),
665                "`{spelling}` was read as a range"
666            );
667        }
668
669        // A single zero is fine, as are the ordinary forms.
670        for (spelling, last) in [
671            ("198.51.100.0-0", "198.51.100.0"),
672            ("198.51.100.1-50", "198.51.100.50"),
673            ("192.168.1.1-2.254", "192.168.2.254"),
674        ] {
675            let range: IpRange = spelling
676                .parse()
677                .unwrap_or_else(|e| panic!("{spelling}: {e}"));
678            assert_eq!(range.end_addr().to_string(), last, "{spelling}");
679        }
680    }
681
682    /// A range has no spaces in it, whichever door it arrives through.
683    ///
684    /// `IpSet::from_str` splits on spaces, so trimming around the separator here would
685    /// make a second dialect.
686    #[test]
687    fn a_range_written_with_spaces_is_not_a_range() {
688        assert!("198.51.100.1 - 198.51.100.5".parse::<IpRange>().is_err());
689        assert!("198.51.100.1 -198.51.100.5".parse::<IpRange>().is_err());
690
691        // The whole token is still trimmed.
692        let padded: IpRange = "  198.51.100.1-198.51.100.5  "
693            .parse()
694            .expect("trimmed as a whole");
695        assert_eq!(padded.len(), 5);
696    }
697
698    /// The link-local bounds agree with the predicate std answers for one
699    /// address, at all four edges.
700    #[test]
701    fn the_link_local_bounds_are_the_block_std_recognises() {
702        let first = Ipv6Addr::from(LINK_LOCAL_FIRST);
703        let last = Ipv6Addr::from(LINK_LOCAL_LAST);
704        assert!(first.is_unicast_link_local(), "{first}");
705        assert!(last.is_unicast_link_local(), "{last}");
706
707        let below = Ipv6Addr::from(LINK_LOCAL_FIRST - 1);
708        let above = Ipv6Addr::from(LINK_LOCAL_LAST + 1);
709        assert!(!below.is_unicast_link_local(), "{below}");
710        assert!(!above.is_unicast_link_local(), "{above}");
711    }
712
713    /// A range is two addresses, and whether it is link-local is a question
714    /// about both.
715    ///
716    /// Covering *some* link-local space makes a range ambiguous; covering *only*
717    /// link-local space is what a `%zone` suffix needs.
718    #[test]
719    fn whether_a_range_is_link_local_is_a_question_about_all_of_it() {
720        let range = |first: &str, last: &str| {
721            Ipv6Range::new(
722                first.parse().expect("an address"),
723                last.parse().expect("an address"),
724            )
725            .expect("in order")
726        };
727
728        // Runs into the block from below: some of it needs a zone.
729        let into = range("fe00::", "fe80::5");
730        assert!(into.covers_link_local());
731        assert!(!into.is_link_local(), "most of it is not link-local");
732        assert!(into.is_ambiguous(), "and the part that is has no interface");
733
734        // Runs out of the block from within: same answer, other direction.
735        let out_of = range("fe80::1", "fec0::1");
736        assert!(out_of.covers_link_local());
737        assert!(!out_of.is_link_local());
738        assert!(out_of.is_ambiguous());
739
740        // Entirely inside, where a zone may be written.
741        let inside = range("fe80::1", "fe80::5");
742        assert!(inside.covers_link_local() && inside.is_link_local());
743        assert!(inside.is_ambiguous(), "until an interface is named");
744
745        // Entirely outside, at both ends of the block.
746        for (first, last) in [("2001:db8::", "2001:db8::ff"), ("fec0::", "fec0::ff")] {
747            let elsewhere = range(first, last);
748            assert!(!elsewhere.covers_link_local(), "{first}-{last}");
749            assert!(!elsewhere.is_link_local(), "{first}-{last}");
750            assert!(!elsewhere.is_ambiguous(), "{first}-{last}");
751        }
752    }
753
754    /// A scope id of zero names no interface, so a range carrying one is not
755    /// scoped and has to say so.
756    ///
757    /// Otherwise `is_ambiguous` would treat it as answered.
758    #[test]
759    fn a_zone_of_zero_is_no_zone_at_all() {
760        let link_local: Ipv6Addr = "fe80::1".parse().expect("literal");
761        let range = Ipv6Range::scoped(link_local, link_local, Some(0)).expect("one address");
762
763        assert_eq!(range.zone(), None);
764        assert!(
765            range.is_ambiguous(),
766            "a link-local range nothing resolved is ambiguous"
767        );
768
769        // A real index is untouched.
770        let found = Ipv6Range::scoped(link_local, link_local, Some(7)).expect("one address");
771        assert_eq!(found.zone(), Some(7));
772        assert!(!found.is_ambiguous());
773    }
774
775    /// `new` refuses an inverted range.
776    #[test]
777    fn a_range_can_only_be_built_in_order() {
778        let low = Ipv4Addr::new(198, 51, 100, 1);
779        let high = Ipv4Addr::new(198, 51, 100, 5);
780
781        assert!(matches!(
782            Ipv4Range::new(high, low),
783            Err(IpError::InvalidRange(_, _))
784        ));
785
786        assert!(matches!(
787            Ipv6Range::new(Ipv6Addr::from(2), Ipv6Addr::from(1)),
788            Err(IpError::InvalidRange(_, _))
789        ));
790
791        let range = Ipv4Range::new(low, high).expect("in order");
792        assert_eq!(range.len(), 5);
793        assert_eq!(range.iter().count() as u64, range.len());
794    }
795
796    /// `extend_end_to` only grows the end.
797    #[test]
798    fn extending_a_range_never_inverts_it() {
799        let mut range = Ipv4Range::new(
800            Ipv4Addr::new(198, 51, 100, 1),
801            Ipv4Addr::new(198, 51, 100, 5),
802        )
803        .unwrap();
804
805        range.extend_end_to(Ipv4Addr::new(198, 51, 100, 9));
806        assert_eq!(range.end_addr(), Ipv4Addr::new(198, 51, 100, 9));
807
808        // A shorter end does not shrink it.
809        range.extend_end_to(Ipv4Addr::new(198, 51, 100, 2));
810        assert_eq!(range.end_addr(), Ipv4Addr::new(198, 51, 100, 9));
811        assert!(range.end_addr() >= range.start_addr());
812        assert_eq!(range.iter().count() as u64, range.len());
813    }
814
815    /// The messages name the value that was wrong.
816    #[test]
817    fn an_error_names_the_input_that_produced_it() {
818        let prefix_err = IpError::InvalidPrefix(40);
819        assert_eq!(format!("{prefix_err}"), "Invalid CIDR prefix: 40");
820
821        let range_err = IpError::InvalidRange(
822            IpAddr::V4(Ipv4Addr::new(1, 1, 1, 2)),
823            IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
824        );
825        assert!(format!("{range_err}").contains("is greater than"));
826    }
827}
828
829#[cfg(test)]
830mod property_tests {
831    use super::*;
832    use proptest::prelude::*;
833
834    fn any_ipv4() -> impl Strategy<Value = Ipv4Addr> {
835        proptest::prelude::any::<u32>().prop_map(Ipv4Addr::from)
836    }
837
838    fn any_ipv6() -> impl Strategy<Value = Ipv6Addr> {
839        proptest::prelude::any::<u128>().prop_map(Ipv6Addr::from)
840    }
841
842    fn any_ipv4_range() -> impl Strategy<Value = Ipv4Range> {
843        (any_ipv4(), 0..5000u32).prop_map(|(start, len)| {
844            let start_u32 = u32::from(start);
845            let end_u32 = start_u32.saturating_add(len);
846            Ipv4Range::new(start, Ipv4Addr::from(end_u32)).unwrap()
847        })
848    }
849
850    fn any_ipv6_range() -> impl Strategy<Value = Ipv6Range> {
851        (any_ipv6(), 0..5000u128).prop_map(|(start, len)| {
852            let start_u128 = u128::from(start);
853            let end_u128 = start_u128.saturating_add(len);
854            Ipv6Range::new(start, Ipv6Addr::from(end_u128)).unwrap()
855        })
856    }
857
858    proptest::proptest! {
859        #[test]
860        fn ipv4_range_invariant(a in any_ipv4(), b in any_ipv4()) {
861            let start = std::cmp::min(a, b);
862            let end = std::cmp::max(a, b);
863            let range = Ipv4Range::new(start, end).unwrap();
864            prop_assert!(range.contains(&start));
865            prop_assert!(range.contains(&end));
866            prop_assert_eq!(range.len(), (u32::from(end) - u32::from(start)) as u64 + 1);
867        }
868
869        #[test]
870        fn ipv6_range_invariant(a in any_ipv6(), b in any_ipv6()) {
871            let start = std::cmp::min(a, b);
872            let end = std::cmp::max(a, b);
873            let range = Ipv6Range::new(start, end).unwrap();
874            prop_assert!(range.contains(&start));
875            prop_assert!(range.contains(&end));
876            prop_assert_eq!(range.len(), (u128::from(end) - u128::from(start)) + 1);
877        }
878
879        #[test]
880        fn ipv4_iterator_consistency(range in any_ipv4_range()) {
881            prop_assert_eq!(range.iter().count() as u64, range.len());
882        }
883
884        #[test]
885        fn ipv6_iterator_consistency(range in any_ipv6_range()) {
886            prop_assert_eq!(range.iter().count() as u128, range.len());
887        }
888
889        /// From zero, the prefix an implementation is tempted to special-case.
890        #[test]
891        fn cidr_v4_roundtrip(v4 in any_ipv4(), prefix in 0..=32u8) {
892            let range = cidr_range(IpAddr::V4(v4), prefix).unwrap();
893            prop_assert_eq!(range.len(), 1u128 << (32 - prefix));
894        }
895
896        #[test]
897        fn cidr_v6_roundtrip(v6 in any_ipv6(), prefix in 0..=128u8) {
898            let range = cidr_range(IpAddr::V6(v6), prefix).unwrap();
899            // `/0` saturates; every other prefix is the shift.
900            let expected = 1u128.checked_shl(u32::from(128 - prefix)).unwrap_or(u128::MAX);
901            prop_assert_eq!(range.len(), expected);
902        }
903    }
904}