zond-engine 0.12.0

A lightweight, fast, and highly concurrent networking backend for packet crafting, protocol fingerprinting, and host discovery.
Documentation
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # Contiguous runs of addresses
//!
//! A range is two addresses and everything between them, inclusive at both
//! ends. It is how this engine holds a `/24` or a `/8` without holding the
//! addresses themselves. It is the unit [`IpSet`](super::set::IpSet) is built
//! out of, and the reason a target set naming sixteen million addresses costs
//! two words.
//!
//! [`Ipv4Range`] and [`Ipv6Range`] are separate rather than one type over
//! `IpAddr` because the arithmetic differs in kind: a v4 range is 8 bytes and
//! its length always fits a `u64`, a v6 range is 32 and its length can exceed
//! what a `u128` holds. [`IpRange`] is the enum over the two, for callers that
//! do not care which family they were handed.
//!
//! **The two families are never comparable.** A v4 address is not in a v6 range
//! whatever the numbers say, and `::ffff:10.0.0.1` is an IPv6 address here even
//! though it names an IPv4 one. Membership across families is `false` rather
//! than an error, because the callers are filtering received packets and a
//! packet of the wrong family is simply not one they asked about.

use std::{
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
    str::FromStr,
};
use thiserror::Error;

/// Why a range could not be built or read.
///
/// The distinction [`parse::ip`](crate::model::parse::ip) depends on runs
/// through these: [`InvalidFormat`](Self::InvalidFormat),
/// [`AddrParse`](Self::AddrParse) and [`PrefixParse`](Self::PrefixParse) mean
/// "this is not a range", which is also what a hostname looks like from here,
/// while the other two mean "this is a range, and it is wrong".
#[non_exhaustive]
#[derive(Debug, Error, PartialEq)]
pub enum IpError {
    /// The start address is above the end. Both are named, since which of the
    /// two was mistyped is the reader's to work out.
    #[error("Invalid range: start address {0} is greater than end address {1}")]
    InvalidRange(IpAddr, IpAddr),

    /// A CIDR prefix longer than its family allows.
    ///
    /// The bound is not in the message because this type does not carry the
    /// family it was written against;
    /// [`IpParseError::InvalidPrefix`](crate::model::parse::ip::IpParseError::InvalidPrefix)
    /// is the one a user reads, and it names both.
    #[error("Invalid CIDR prefix: {0}")]
    InvalidPrefix(u8),

    /// Not an address at all, on either side of a separator.
    #[error("Failed to parse IP address: {0}")]
    AddrParse(#[from] std::net::AddrParseError),

    /// Recognisably a range — it has a separator — but not one this grammar
    /// accepts.
    #[error("Invalid IP range format: {0}")]
    InvalidFormat(String),

    /// The text after `/` was not a number.
    #[error("Invalid prefix number format: {0}")]
    PrefixParse(#[from] std::num::ParseIntError),
}

// ══════════════════════════════════════════════════════════════════════════════
// IPv4 Range
// ══════════════════════════════════════════════════════════════════════════════

/// A contiguous run of IPv4 addresses, inclusive at both ends.
///
/// Eight bytes, whatever the range covers. The start is never above the end,
/// which [`new`](Self::new) is the only way to construct one in order to
/// guarantee: an inverted range has a length that cannot be represented and
/// yields nothing when iterated, so the two would disagree about what it holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Ipv4Range {
    /// The inclusive starting address of the range.
    start_addr: Ipv4Addr,
    /// The inclusive ending address of the range.
    end_addr: Ipv4Addr,
}

impl Ipv4Range {
    /// Creates a new `Ipv4Range`.
    ///
    /// # Errors
    ///
    /// Returns [`IpError::InvalidRange`] if `start` is numerically greater than `end`.
    pub fn new(start: Ipv4Addr, end: Ipv4Addr) -> Result<Self, IpError> {
        if u32::from(start) <= u32::from(end) {
            Ok(Self {
                start_addr: start,
                end_addr: end,
            })
        } else {
            Err(IpError::InvalidRange(IpAddr::V4(start), IpAddr::V4(end)))
        }
    }

    /// Returns an iterator over every [`IpAddr`] within the range.
    ///
    /// # Performance
    ///
    /// Iterating over large ranges (e.g., /8) is fast, but collecting the results
    /// into a `Vec` will consume significant memory.
    pub fn iter(&self) -> impl Iterator<Item = IpAddr> {
        let start: u32 = self.start_addr.into();
        let end: u32 = self.end_addr.into();
        (start..=end).map(|ip| IpAddr::V4(Ipv4Addr::from(ip)))
    }

    /// A range covering the single address `addr`.
    ///
    /// Infallible, because one address is trivially in order with itself. That
    /// is what keeps the callers that hold one address from writing
    /// `new(addr, addr).unwrap()` and teaching a reader that constructing a
    /// range can panic.
    pub const fn single(addr: Ipv4Addr) -> Self {
        Self {
            start_addr: addr,
            end_addr: addr,
        }
    }

    /// The inclusive first address.
    pub fn start_addr(&self) -> Ipv4Addr {
        self.start_addr
    }

    /// The inclusive last address, never lower than
    /// [`start_addr`](Self::start_addr).
    pub fn end_addr(&self) -> Ipv4Addr {
        self.end_addr
    }

    /// Extends this range to reach `end`, if it does not already.
    ///
    /// The only mutation a range allows, and the one merging adjacent ranges
    /// needs. Growing the end cannot put it below the start, so the ordering
    /// invariant survives without a check.
    pub fn extend_end_to(&mut self, end: Ipv4Addr) {
        if end > self.end_addr {
            self.end_addr = end;
        }
    }

    /// Checks if the given [`Ipv4Addr`] falls within this range (inclusive).
    pub fn contains(&self, ip: &Ipv4Addr) -> bool {
        (u32::from(self.start_addr)..=u32::from(self.end_addr)).contains(&u32::from(*ip))
    }

    /// How many addresses the range covers, never fewer than one.
    ///
    /// There is deliberately no `is_empty`: both bounds are inclusive and
    /// [`new`](Self::new) refuses an inverted range, so a range always holds at
    /// least one address and the answer would be `false` every time it was
    /// asked. [`IpSet::is_empty`](crate::model::ip::set::IpSet::is_empty) next
    /// door means something real, which is exactly what makes an always-false
    /// one here a trap.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> u64 {
        let s_u32: u64 = u32::from(self.start_addr) as u64;
        let e_u32: u64 = u32::from(self.end_addr) as u64;
        (e_u32 - s_u32) + 1
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// IPv6 Range
// ══════════════════════════════════════════════════════════════════════════════

/// A contiguous run of IPv6 addresses, inclusive at both ends, together with the
/// interface they are valid on if they need one.
///
/// The start is never above the end, for the reason [`Ipv4Range`] gives.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Ipv6Range {
    /// The inclusive starting address of the range.
    start_addr: Ipv6Addr,
    /// The inclusive ending address of the range.
    end_addr: Ipv6Addr,
    /// The interface these addresses are valid on, as a scope id, for a range
    /// of link-local addresses.
    ///
    /// The index alone rather than the whole
    /// [`Zone`](crate::model::ip::scoped::Zone), so this type stays
    /// `Copy`: a scan expands ranges into millions of targets, and the index is
    /// all a socket ever needs. The interface *name* is a display concern and
    /// belongs where a person reads the output.
    ///
    /// `None` for every range that does not need one, which is all of them
    /// except link-local. See
    /// [`ScopedIp`](crate::model::ip::scoped::ScopedIp) for why an
    /// address that needs a zone and lacks one cannot be probed at all.
    zone: Option<u32>,
}

impl Ipv6Range {
    /// Creates a new `Ipv6Range`.
    ///
    /// # Errors
    ///
    /// Returns [`IpError::InvalidRange`] if `start` is numerically greater than `end`.
    pub fn new(start: Ipv6Addr, end: Ipv6Addr) -> Result<Self, IpError> {
        Self::scoped(start, end, None)
    }

    /// Creates an `Ipv6Range` valid on the interface with scope id `zone`.
    ///
    /// # Errors
    ///
    /// Returns [`IpError::InvalidRange`] if `start` is numerically greater than
    /// `end`.
    pub fn scoped(start: Ipv6Addr, end: Ipv6Addr, zone: Option<u32>) -> Result<Self, IpError> {
        if u128::from(start) <= u128::from(end) {
            Ok(Self {
                start_addr: start,
                end_addr: end,
                zone,
            })
        } else {
            Err(IpError::InvalidRange(IpAddr::V6(start), IpAddr::V6(end)))
        }
    }

    /// A range covering the single address `addr`, on no particular interface.
    /// The counterpart of [`Ipv4Range::single`].
    pub const fn single(addr: Ipv6Addr) -> Self {
        Self {
            start_addr: addr,
            end_addr: addr,
            zone: None,
        }
    }

    /// The inclusive first address.
    pub fn start_addr(&self) -> Ipv6Addr {
        self.start_addr
    }

    /// The inclusive last address, never lower than
    /// [`start_addr`](Self::start_addr).
    pub fn end_addr(&self) -> Ipv6Addr {
        self.end_addr
    }

    /// Extends this range to reach `end`, if it does not already. See
    /// [`Ipv4Range::extend_end_to`].
    pub fn extend_end_to(&mut self, end: Ipv6Addr) {
        if end > self.end_addr {
            self.end_addr = end;
        }
    }

    /// The interface these addresses are valid on, as a scope id, if they need
    /// one.
    pub fn zone(&self) -> Option<u32> {
        self.zone
    }

    /// Whether these addresses are meaningless without an interface to
    /// interpret them against, and none is recorded.
    ///
    /// A range spanning link-local addresses without a zone cannot be probed:
    /// every interface holds an `fe80::/64`, so there is no way to tell which
    /// segment was meant, and picking one is a guess a scan must not make
    /// silently.
    pub fn is_ambiguous(&self) -> bool {
        self.zone.is_none() && self.start_addr.is_unicast_link_local()
    }

    /// Returns an iterator over every [`IpAddr`] within the range.
    ///
    /// # Warning
    ///
    /// IPv6 ranges can be astronomically large. Iterating over a typical CIDR (like a /64)
    /// will take millions of years. This method is provided for small, manually
    /// defined ranges.
    pub fn iter(&self) -> impl Iterator<Item = IpAddr> {
        let start: u128 = self.start_addr.into();
        let end: u128 = self.end_addr.into();
        (start..=end).map(|ip| IpAddr::V6(Ipv6Addr::from(ip)))
    }

    /// Checks if the given [`Ipv6Addr`] falls within this range (inclusive).
    ///
    /// Blind to the zone, like [`IpSet::contains`](super::set::IpSet::contains)
    /// above it: a received packet carries a bare address with no interface
    /// attached to compare against.
    pub fn contains(&self, ip: &Ipv6Addr) -> bool {
        (u128::from(self.start_addr)..=u128::from(self.end_addr)).contains(&u128::from(*ip))
    }

    /// How many addresses the range covers, never fewer than one. See
    /// [`Ipv4Range::len`] for why there is no `is_empty` beside it.
    ///
    /// `::/0` covers 2^128 addresses, which is one more than a `u128` can hold,
    /// so the count saturates at [`u128::MAX`]. That is an undercount of one
    /// address in the single case where the range is the entire address space -
    /// a quantity no caller can act on differently at either value, and the only
    /// alternative to a wrapping subtraction that reports the whole of IPv6 as
    /// *nothing*. A budget check is the main reader of this, and reporting zero
    /// would wave through precisely the target it exists to stop.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> u128 {
        let s_u128: u128 = u128::from(self.start_addr);
        let e_u128: u128 = u128::from(self.end_addr);
        (e_u128 - s_u128).saturating_add(1)
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// Unified IpRange API
// ══════════════════════════════════════════════════════════════════════════════

/// Either family's range, for a caller that does not care which it was handed.
///
/// What [`FromStr`] produces, since the text decides the family and the caller
/// writing it usually has no reason to branch on the answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IpRange {
    /// An IPv4 address range.
    V4(Ipv4Range),
    /// An IPv6 address range.
    V6(Ipv6Range),
}

impl IpRange {
    /// Returns the start address of the range as an [`IpAddr`].
    pub fn start_addr(&self) -> IpAddr {
        match self {
            IpRange::V4(r) => IpAddr::V4(r.start_addr),
            IpRange::V6(r) => IpAddr::V6(r.start_addr),
        }
    }

    /// Returns the end address of the range as an [`IpAddr`].
    pub fn end_addr(&self) -> IpAddr {
        match self {
            IpRange::V4(r) => IpAddr::V4(r.end_addr),
            IpRange::V6(r) => IpAddr::V6(r.end_addr),
        }
    }

    /// Checks if the given [`IpAddr`] falls within this range.
    ///
    /// Returns `false` if the protocol versions do not match (e.g., checking
    /// if a V6 address is in a V4 range).
    pub fn contains(&self, ip: &IpAddr) -> bool {
        match (self, ip) {
            (IpRange::V4(r), IpAddr::V4(ip)) => r.contains(ip),
            (IpRange::V6(r), IpAddr::V6(ip)) => r.contains(ip),
            _ => false,
        }
    }

    /// How many addresses the range covers, never fewer than one. See
    /// [`Ipv4Range::len`] for why there is no `is_empty` beside it.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> u128 {
        match self {
            IpRange::V4(r) => r.len() as u128,
            IpRange::V6(r) => r.len(),
        }
    }
}

impl FromStr for IpRange {
    type Err = IpError;

    /// Parses an IP range from a string.
    ///
    /// Supports:
    /// - CIDR notation: `192.168.1.0/24`, `2001:db8::/32`
    /// - Hyphenated ranges: `10.0.0.1-10.0.0.5`, `::1-::f`
    /// - Shortened IPv4 ranges, where the end continues the start's octets:
    ///   `10.0.0.1-50`, `192.168.1.1-2.254`
    /// - Single IPs: `1.1.1.1`, `::1`
    ///
    /// This is the whole of the range grammar. Everything in the crate that
    /// reads a written range ends here, so no two entry points can accept
    /// different spellings of the same thing.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();

        // Handle CIDR
        if let Some(pos) = s.find('/') {
            let ip = s[..pos].parse::<IpAddr>()?;
            let prefix = s[pos + 1..].parse::<u8>()?;
            return cidr_range(ip, prefix);
        }

        // Handle hyphenated range
        if let Some(pos) = s.find('-') {
            let start_str = s[..pos].trim();
            let end_str = s[pos + 1..].trim();

            if let Ok(start) = start_str.parse::<Ipv4Addr>() {
                let end = expand_v4_end(start, end_str)
                    .ok_or_else(|| IpError::InvalidFormat(s.to_string()))?;
                return Ok(IpRange::V4(Ipv4Range::new(start, end)?));
            } else if let Ok(start) = start_str.parse::<Ipv6Addr>() {
                let end = end_str.parse::<Ipv6Addr>()?;
                return Ok(IpRange::V6(Ipv6Range::new(start, end)?));
            }
            return Err(IpError::InvalidFormat(s.to_string()));
        }

        // Handle single IP
        match s.parse::<IpAddr>()? {
            IpAddr::V4(v4) => Ok(IpRange::V4(Ipv4Range::single(v4))),
            IpAddr::V6(v6) => Ok(IpRange::V6(Ipv6Range::single(v6))),
        }
    }
}

/// Reads the end of an IPv4 range, which may be written in full or as however
/// many trailing octets differ from the start.
///
/// `10.0.0.1-50` ends at `10.0.0.50` and `192.168.1.1-2.254` at
/// `192.168.2.254`: the octets given replace the same number of octets at the
/// end of the start address. A shorthand exists because the alternative is
/// writing an address twice to name a range within one subnet, which is the
/// common case.
///
/// IPv4 only. IPv6 has no comparable form, and inventing one would make `::1-5`
/// ambiguous with an address whose last group is hex.
fn expand_v4_end(start: Ipv4Addr, end_str: &str) -> Option<Ipv4Addr> {
    if let Ok(full) = end_str.parse::<Ipv4Addr>() {
        return Some(full);
    }

    let suffix: Vec<u8> = end_str
        .split('.')
        .map(|part| part.parse::<u8>())
        .collect::<Result<_, _>>()
        .ok()?;

    if suffix.is_empty() || suffix.len() > 4 {
        return None;
    }

    let mut octets = start.octets();
    octets[4 - suffix.len()..].copy_from_slice(&suffix);
    Some(Ipv4Addr::from(octets))
}

/// Constructs an [`IpRange`] from an IP address and a CIDR prefix length.
///
/// # Examples
///
/// ```
/// use zond_engine::model::ip::range::{cidr_range, IpRange};
/// use std::net::IpAddr;
///
/// let range = cidr_range("192.168.1.5".parse().unwrap(), 24).unwrap();
/// assert_eq!(range.len(), 256);
/// ```
pub fn cidr_range(ip: IpAddr, prefix: u8) -> Result<IpRange, IpError> {
    match ip {
        IpAddr::V4(v4) => {
            if prefix > 32 {
                return Err(IpError::InvalidPrefix(prefix));
            }

            let ip_u32 = u32::from(v4);
            let mask = if prefix == 0 {
                0
            } else {
                !u32::MAX.checked_shr(prefix as u32).unwrap_or(0)
            };

            let network = ip_u32 & mask;
            let broadcast = ip_u32 | !mask;

            Ok(IpRange::V4(
                Ipv4Range::new(Ipv4Addr::from(network), Ipv4Addr::from(broadcast)).unwrap(),
            ))
        }
        IpAddr::V6(v6) => {
            if prefix > 128 {
                return Err(IpError::InvalidPrefix(prefix));
            }

            let ip_u128 = u128::from(v6);
            let mask = if prefix == 0 {
                0
            } else {
                !u128::MAX.checked_shr(prefix as u32).unwrap_or(0)
            };

            let network = ip_u128 & mask;
            let broadcast = ip_u128 | !mask;

            Ok(IpRange::V6(
                Ipv6Range::new(Ipv6Addr::from(network), Ipv6Addr::from(broadcast)).unwrap(),
            ))
        }
    }
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

#[cfg(test)]
mod tests {
    use super::*;

    /// Both bounds are inclusive, so the edges are the cases worth writing
    /// down: the property tests below establish that a range holds its own
    /// endpoints, and these establish that it holds nothing beyond them. An
    /// off-by-one here scans an address nobody asked about, or misses one they
    /// did.
    #[test]
    fn a_range_holds_both_its_bounds_and_nothing_outside_them() {
        let v4 =
            Ipv4Range::new(Ipv4Addr::new(172, 16, 0, 10), Ipv4Addr::new(172, 16, 0, 20)).unwrap();
        assert!(v4.contains(&Ipv4Addr::new(172, 16, 0, 10)));
        assert!(v4.contains(&Ipv4Addr::new(172, 16, 0, 20)));
        assert!(!v4.contains(&Ipv4Addr::new(172, 16, 0, 9)));
        assert!(!v4.contains(&Ipv4Addr::new(172, 16, 0, 21)));

        let v6 = Ipv6Range::new(Ipv6Addr::from(100), Ipv6Addr::from(200)).unwrap();
        assert_eq!(v6.len(), 101, "inclusive at both ends");
        assert!(v6.contains(&Ipv6Addr::from(100)));
        assert!(v6.contains(&Ipv6Addr::from(200)));
        assert!(!v6.contains(&Ipv6Addr::from(201)));
    }

    /// The ends of each address space, where the arithmetic that counts a range
    /// is one step from overflowing.
    ///
    /// `::/0` is the case the type cannot represent exactly: 2^128 addresses is
    /// one more than a `u128` holds, so the count saturates. That undercount of
    /// one is deliberate — the alternative is a wrapping subtraction reporting
    /// the whole of IPv6 as *nothing*, and a budget check reading zero would
    /// wave through precisely the target it exists to stop.
    #[test]
    fn the_extremes_of_each_address_space_saturate_rather_than_wrap() {
        let top_of_v4 = Ipv4Range::new(
            Ipv4Addr::new(255, 255, 255, 254),
            Ipv4Addr::new(255, 255, 255, 255),
        )
        .unwrap();
        assert_eq!(top_of_v4.len(), 2);

        let sixty_four = cidr_range(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 64).unwrap();
        assert_eq!(sixty_four.len(), 1u128 << 64);

        let everything = cidr_range(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0).unwrap();
        assert_eq!(everything.len(), u128::MAX, "saturated, never zero");
    }

    /// Ascending, with no address skipped or repeated. The order is what a scan
    /// walks, so two runs over one target list probe in the same sequence — and
    /// the values, not merely the count, are what the property tests below do
    /// not pin.
    #[test]
    fn iteration_yields_every_address_in_ascending_order() {
        let v4 = Ipv4Range::new(Ipv4Addr::new(1, 1, 1, 1), Ipv4Addr::new(1, 1, 1, 3)).unwrap();
        assert_eq!(
            v4.iter().collect::<Vec<_>>(),
            [
                IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
                IpAddr::V4(Ipv4Addr::new(1, 1, 1, 2)),
                IpAddr::V4(Ipv4Addr::new(1, 1, 1, 3)),
            ]
        );

        let v6 = Ipv6Range::new(Ipv6Addr::from(1), Ipv6Addr::from(3)).unwrap();
        assert_eq!(
            v6.iter().collect::<Vec<_>>(),
            [
                IpAddr::V6(Ipv6Addr::from(1)),
                IpAddr::V6(Ipv6Addr::from(2)),
                IpAddr::V6(Ipv6Addr::from(3)),
            ]
        );
    }

    /// Every form the grammar accepts, and what each covers.
    ///
    /// This is the whole of what a written range can mean, and everything in
    /// the crate that reads one ends here — so a spelling that stops working
    /// stops working for target files, imported reports and command lines at
    /// once.
    #[test]
    fn every_written_form_names_the_range_it_says_it_does() {
        for (written, first, last) in [
            ("8.8.8.8", "8.8.8.8", "8.8.8.8"),
            ("10.0.0.0/24", "10.0.0.0", "10.0.0.255"),
            ("192.168.1.5/24", "192.168.1.0", "192.168.1.255"),
            ("1.1.1.1-1.1.1.5", "1.1.1.1", "1.1.1.5"),
            ("10.0.0.1-50", "10.0.0.1", "10.0.0.50"),
            ("192.168.1.1-2.254", "192.168.1.1", "192.168.2.254"),
            ("::1", "::1", "::1"),
            ("::1/120", "::", "::ff"),
            ("2001:db8::1-2001:db8::5", "2001:db8::1", "2001:db8::5"),
        ] {
            let range: IpRange = written.parse().unwrap_or_else(|e| panic!("{written}: {e}"));

            assert_eq!(range.start_addr().to_string(), first, "{written} starts");
            assert_eq!(range.end_addr().to_string(), last, "{written} ends");
        }
    }

    /// `new` is the only way to build a range, so the ordering it checks is a
    /// property of every range that exists. Without that, an inverted one is
    /// constructible and disagrees with itself: `len` cannot represent a
    /// negative count and `to_iter` yields nothing, so a budget check and a scan
    /// read the same value differently.
    #[test]
    fn a_range_can_only_be_built_in_order() {
        let low = Ipv4Addr::new(10, 0, 0, 1);
        let high = Ipv4Addr::new(10, 0, 0, 5);

        assert!(matches!(
            Ipv4Range::new(high, low),
            Err(IpError::InvalidRange(_, _))
        ));

        assert!(matches!(
            Ipv6Range::new(Ipv6Addr::from(2), Ipv6Addr::from(1)),
            Err(IpError::InvalidRange(_, _))
        ));

        let range = Ipv4Range::new(low, high).expect("in order");
        assert_eq!(range.len(), 5);
        assert_eq!(range.iter().count() as u64, range.len());
    }

    /// The one mutation a range allows. It only ever grows the end, which is
    /// what keeps it unable to invert the range it is called on.
    #[test]
    fn extending_a_range_never_inverts_it() {
        let mut range =
            Ipv4Range::new(Ipv4Addr::new(10, 0, 0, 1), Ipv4Addr::new(10, 0, 0, 5)).unwrap();

        range.extend_end_to(Ipv4Addr::new(10, 0, 0, 9));
        assert_eq!(range.end_addr(), Ipv4Addr::new(10, 0, 0, 9));

        // A shorter end is not an instruction to shrink.
        range.extend_end_to(Ipv4Addr::new(10, 0, 0, 2));
        assert_eq!(range.end_addr(), Ipv4Addr::new(10, 0, 0, 9));
        assert!(range.end_addr() >= range.start_addr());
        assert_eq!(range.iter().count() as u64, range.len());
    }

    /// These messages are printed at whoever mistyped a target, so they have to
    /// name the value that was wrong rather than only the rule it broke.
    #[test]
    fn an_error_names_the_input_that_produced_it() {
        let prefix_err = IpError::InvalidPrefix(40);
        assert_eq!(format!("{prefix_err}"), "Invalid CIDR prefix: 40");

        let range_err = IpError::InvalidRange(
            IpAddr::V4(Ipv4Addr::new(1, 1, 1, 2)),
            IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
        );
        assert!(format!("{range_err}").contains("is greater than"));
    }
}

#[cfg(test)]
mod property_tests {
    use super::*;
    use proptest::prelude::*;

    fn any_ipv4() -> impl Strategy<Value = Ipv4Addr> {
        proptest::prelude::any::<u32>().prop_map(Ipv4Addr::from)
    }

    fn any_ipv6() -> impl Strategy<Value = Ipv6Addr> {
        proptest::prelude::any::<u128>().prop_map(Ipv6Addr::from)
    }

    fn any_ipv4_range() -> impl Strategy<Value = Ipv4Range> {
        (any_ipv4(), 0..5000u32).prop_map(|(start, len)| {
            let start_u32 = u32::from(start);
            let end_u32 = start_u32.saturating_add(len);
            Ipv4Range::new(start, Ipv4Addr::from(end_u32)).unwrap()
        })
    }

    fn any_ipv6_range() -> impl Strategy<Value = Ipv6Range> {
        (any_ipv6(), 0..5000u128).prop_map(|(start, len)| {
            let start_u128 = u128::from(start);
            let end_u128 = start_u128.saturating_add(len);
            Ipv6Range::new(start, Ipv6Addr::from(end_u128)).unwrap()
        })
    }

    proptest::proptest! {
        #[test]
        fn ipv4_range_invariant(a in any_ipv4(), b in any_ipv4()) {
            let start = std::cmp::min(a, b);
            let end = std::cmp::max(a, b);
            let range = Ipv4Range::new(start, end).unwrap();
            prop_assert!(range.contains(&start));
            prop_assert!(range.contains(&end));
            prop_assert_eq!(range.len(), (u32::from(end) - u32::from(start)) as u64 + 1);
        }

        #[test]
        fn ipv6_range_invariant(a in any_ipv6(), b in any_ipv6()) {
            let start = std::cmp::min(a, b);
            let end = std::cmp::max(a, b);
            let range = Ipv6Range::new(start, end).unwrap();
            prop_assert!(range.contains(&start));
            prop_assert!(range.contains(&end));
            prop_assert_eq!(range.len(), (u128::from(end) - u128::from(start)) + 1);
        }

        #[test]
        fn ipv4_iterator_consistency(range in any_ipv4_range()) {
            prop_assert_eq!(range.iter().count() as u64, range.len());
        }

        #[test]
        fn ipv6_iterator_consistency(range in any_ipv6_range()) {
            prop_assert_eq!(range.iter().count() as u128, range.len());
        }

        #[test]
        fn cidr_v4_roundtrip(v4 in any_ipv4(), prefix in 1..=32u8) {
            let range = cidr_range(IpAddr::V4(v4), prefix).unwrap();
            prop_assert_eq!(range.len(), 1u128 << (32 - prefix));
        }

        #[test]
        fn cidr_v6_roundtrip(v6 in any_ipv6(), prefix in 1..=128u8) {
            let range = cidr_range(IpAddr::V6(v6), prefix).unwrap();
            prop_assert_eq!(range.len(), 1u128 << (128 - prefix));
        }
    }
}