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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
// 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

//! # IP address sets
//!
//! [`IpSet`] holds the addresses a scan is about, as sorted non-overlapping
//! ranges. In that form a `/8` costs one range rather than sixteen million
//! addresses.
//!
//! ## Merging is lazy
//!
//! Insertion is constant time, because it only appends. Sorting and merging is
//! `O(n log n)` and happens once, when you call [`IpSet::canonicalize`]. The
//! split exists because a target file can name tens of thousands of ranges, and
//! merging after each one would make loading it quadratic.
//!
//! You do not have to track which state a set is in. Every query is correct
//! either way: [`contains`](IpSet::contains) and [`len`](IpSet::len) take a fast
//! path over merged ranges when they can and a slower one when they cannot.
//! Canonicalizing is a performance decision, not a correctness one, and the
//! right moment for it is when a set stops being built and starts being read.
//!
//! Most callers never need to think about it at all, because
//! [`TargetSet::new`](crate::model::target::TargetSet::new) canonicalizes what
//! it is given and never mutates it again. Everything downstream of a
//! `TargetSet` reads merged ranges by construction.

use super::range::{IpError, IpRange, Ipv4Range, Ipv6Range};
use std::{
    borrow::Cow,
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
    str::FromStr,
};

/// Errors that can occur when processing an [`IpSet`].
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum IpSetError {
    /// Indicates that an invalid IP range or address was provided.
    #[error("Invalid target in set: {0}")]
    InvalidTarget(#[from] IpError),
}

// ══════════════════════════════════════════════════════════════════════════════
// IpSet core model
// ══════════════════════════════════════════════════════════════════════════════

/// A collection of unique IP addresses stored as sorted, non-overlapping ranges.
///
/// Handles automatic merging of overlapping and adjacent ranges lazily.
///
/// Equality is over the addresses held, not over how the set was built: see the
/// hand-written [`PartialEq`].
#[derive(Debug, Clone, Default, Eq)]
pub struct IpSet {
    v4: Vec<Ipv4Range>,
    v6: Vec<Ipv6Range>,
    v4_dirty: bool,
    v6_dirty: bool,
}

impl IpSet {
    /// Creates a new, empty `IpSet`.
    pub fn new() -> Self {
        Self::default()
    }

    // ─── Insertion API ───────────────────────────────────────────────────────

    /// Adds a single IP address to the set.
    ///
    /// Constant time: it appends and defers the merge. See the module
    /// documentation for why.
    pub fn insert(&mut self, ip: IpAddr) {
        match ip {
            IpAddr::V4(v4) => self.push_v4_range(Ipv4Range::single(v4)),
            IpAddr::V6(v6) => self.push_v6_range(Ipv6Range::single(v6)),
        }
    }

    /// Adds a unified IP range to the set.
    pub fn insert_range(&mut self, range: IpRange) {
        match range {
            IpRange::V4(r) => self.push_v4_range(r),
            IpRange::V6(r) => self.push_v6_range(r),
        }
    }

    /// Appends an IPv4 range without immediate merging.
    pub fn push_v4_range(&mut self, range: Ipv4Range) {
        self.v4.push(range);
        self.v4_dirty = true;
    }

    /// Appends an IPv6 range without immediate merging.
    pub fn push_v6_range(&mut self, range: Ipv6Range) {
        self.v6.push(range);
        self.v6_dirty = true;
    }

    /// Sorts and merges the ranges, so that every read afterwards takes its
    /// fast path.
    ///
    /// Call it once, at the point the set stops being built and starts being
    /// read. It is not required for correctness, since every query answers
    /// correctly either way, but an unmerged set answers by scanning, and a set
    /// read once per received packet should not be.
    pub fn canonicalize(&mut self) {
        if self.v4_dirty {
            if !self.v4.is_empty() {
                self.merge_v4();
            }
            self.v4_dirty = false;
        }
        if self.v6_dirty {
            if !self.v6.is_empty() {
                self.merge_v6();
            }
            self.v6_dirty = false;
        }
    }

    fn merge_v4(&mut self) {
        self.v4.sort_by_key(|r| r.start_addr());
        let mut merged: Vec<Ipv4Range> = Vec::with_capacity(self.v4.len());
        let mut current = self.v4[0];

        for next in self.v4.drain(1..) {
            let curr_end = u32::from(current.end_addr());
            let next_start = u32::from(next.start_addr());

            if next_start <= curr_end.saturating_add(1) {
                current.extend_end_to(next.end_addr());
            } else {
                merged.push(current);
                current = next;
            }
        }
        merged.push(current);
        self.v4 = merged;
    }

    /// Sorts and merges the IPv6 ranges, keeping ranges on different interfaces
    /// apart.
    ///
    /// Two link-local ranges spanning the same numbers on two interfaces are two
    /// different sets of machines, and merging them would produce a range that
    /// means one thing at one end and something else at the other. So adjacency
    /// alone is not enough to combine two ranges; they have to agree on scope.
    ///
    /// **The sort is keyed on the zone first.** That leaves the vector as one
    /// run per interface, each sorted by address and disjoint within itself,
    /// which is what [`v6_runs`](Self::v6_runs) hands the binary search. Sorted
    /// by address first the runs interleave, and two ranges that overlap
    /// numerically while disagreeing on zone both survive the merge — a vector
    /// a binary search steps straight past.
    ///
    /// Grouping also merges strictly more than address-first ordering did: two
    /// ranges sharing a zone are now always adjacent, where before a
    /// differently-zoned range between them left both in place.
    fn merge_v6(&mut self) {
        self.v6.sort_by_key(|r| (r.zone(), r.start_addr()));
        let mut merged: Vec<Ipv6Range> = Vec::with_capacity(self.v6.len());
        let mut current = self.v6[0];

        for next in self.v6.drain(1..) {
            let curr_end = u128::from(current.end_addr());
            let next_start = u128::from(next.start_addr());

            if next.zone() == current.zone() && next_start <= curr_end.saturating_add(1) {
                current.extend_end_to(next.end_addr());
            } else {
                merged.push(current);
                current = next;
            }
        }
        merged.push(current);
        self.v6 = merged;
    }

    /// The merged IPv6 ranges, one slice per interface.
    ///
    /// Each slice is sorted by address and holds no two ranges that overlap,
    /// which is the precondition [`holds`] needs and which the vector as a
    /// whole does not meet. There is one slice per distinct zone, so this
    /// yields once for the sets that name no interface at all and otherwise as
    /// many times as the host has interfaces in the set.
    fn v6_runs(&self) -> impl Iterator<Item = &[Ipv6Range]> {
        let mut rest = self.v6.as_slice();

        std::iter::from_fn(move || {
            let zone = rest.first()?.zone();
            // Sorted by zone first, so this run is a prefix of what is left.
            let (run, tail) = rest.split_at(rest.partition_point(|r| r.zone() == zone));
            rest = tail;
            Some(run)
        })
    }

    // ─── Query API (Lazy) ────────────────────────────────────────────────────

    /// Checks if the set contains the given IP address, on any interface.
    ///
    /// Deliberately blind to zones: the callers are filtering received replies
    /// against the targets they asked about, and a reply arrives as a bare
    /// address with no interface attached to compare. The strategy that receives
    /// it is bound to one segment already, so the scope is established by which
    /// scanner is asking rather than by this test.
    ///
    /// Correct whatever state the set is in: a binary search when it is merged,
    /// and a linear scan of the unmerged ranges when it is not. The slow path
    /// allocates nothing, because a membership test is not a reason to merge a
    /// set the caller has not finished building.
    pub fn contains(&self, ip: &IpAddr) -> bool {
        if !self.v4_dirty && !self.v6_dirty {
            return self.contains_canonical(ip);
        }
        match ip {
            IpAddr::V4(v4) => self.v4.iter().any(|range| range.contains(v4)),
            IpAddr::V6(v6) => self.v6.iter().any(|range| range.contains(v6)),
        }
    }

    /// The number of distinct addresses the set covers.
    ///
    /// Overlapping ranges are counted once, so an unmerged set is merged before
    /// answering. That happens on a clone, which keeps counting a read.
    /// [`len_gross`](Self::len_gross) is the cheap over-estimate for a caller
    /// that asks often.
    pub fn len(&self) -> u128 {
        if !self.v4_dirty && !self.v6_dirty {
            self.len_canonical()
        } else {
            let mut temp = self.clone();
            temp.canonicalize();
            temp.len_canonical()
        }
    }

    /// Returns `true` if the set is empty.
    pub fn is_empty(&self) -> bool {
        self.v4.is_empty() && self.v6.is_empty()
    }

    /// How many addresses the ranges cover, counting overlaps once per range
    /// they appear in.
    ///
    /// [`len`](Self::len) clones and merges the whole set when it is dirty,
    /// which is the right answer to give a person and the wrong one to ask on
    /// every insertion. This costs one pass and no allocation, and it is never
    /// lower than the true count - so a budget checked against it refuses early
    /// rather than late.
    pub fn len_gross(&self) -> u128 {
        self.v4_len().saturating_add(self.v6_len())
    }

    /// Every address the set covers, one at a time, IPv4 before IPv6.
    ///
    /// Each address is yielded once, however many ranges named it. That needs
    /// merged ranges, so an unmerged set is merged on a clone and iteration
    /// stays a read. If you own the set, call
    /// [`canonicalize`](Self::canonicalize) first and skip the copy.
    ///
    /// Yields lazily. A `/8` is sixteen million addresses and an IPv6 range can
    /// hold far more than that, so nothing here is materialized.
    pub fn iter(&self) -> Box<dyn Iterator<Item = IpAddr> + Send + '_> {
        if self.v4_dirty || self.v6_dirty {
            let mut temp = self.clone();
            temp.canonicalize();
            temp.into_iter()
        } else {
            let v4_iter = self.v4.iter().flat_map(|range| range.iter());
            let v6_iter = self.v6.iter().flat_map(|range| range.iter());
            Box::new(v4_iter.chain(v6_iter))
        }
    }

    // ─── Query API (Read-Only / Sync) ────────────────────────────────────────

    /// The fast path [`contains`](Self::contains) takes on a merged set.
    ///
    /// Private, because the assertion below is the only thing separating a
    /// binary search over sorted ranges from a binary search over unsorted
    /// ones, and a release build compiles it out. Whether an address is in
    /// scope decides whether a reply is credited or discarded, so that choice
    /// is not one to leave to a caller who cannot see the set's state.
    ///
    /// # Panics
    ///
    /// In debug builds, if the set has unmerged ranges pending.
    fn contains_canonical(&self, ip: &IpAddr) -> bool {
        debug_assert!(
            !self.v4_dirty && !self.v6_dirty,
            "IpSet must be canonicalized before calling contains_canonical"
        );
        match ip {
            IpAddr::V4(v4) => holds(&self.v4, u128::from(u32::from(*v4)), |range| {
                (
                    u128::from(u32::from(range.start_addr())),
                    u128::from(u32::from(range.end_addr())),
                )
            }),
            IpAddr::V6(v6) => {
                let target = u128::from(*v6);
                self.v6_runs().any(|run| {
                    holds(run, target, |range| {
                        (u128::from(range.start_addr()), u128::from(range.end_addr()))
                    })
                })
            }
        }
    }

    /// The fast path [`len`](Self::len) takes on a merged set. Private for the
    /// same reason [`contains_canonical`](Self::contains_canonical) is.
    ///
    /// # Panics
    ///
    /// In debug builds, if the set has unmerged ranges pending.
    fn len_canonical(&self) -> u128 {
        debug_assert!(
            !self.v4_dirty && !self.v6_dirty,
            "IpSet must be canonicalized before calling len_canonical"
        );
        self.v4_len().saturating_add(self.v6_len())
    }

    /// How many addresses the IPv4 ranges cover, and how many the IPv6 ones do.
    ///
    /// Counted per family rather than as one total because a caller that emits
    /// a different probe per family needs to know the ratio between them - a
    /// sweep interleaving ARP with neighbor solicitation has to space each
    /// against the other's volume. Overlapping ranges are counted twice, which
    /// merging is what would fix: these steer pacing, and a pacing decision does
    /// not warrant canonicalizing a clone of the set to make them exact.
    ///
    /// Saturates rather than wrapping, for the reason
    /// [`Ipv6Range::len`](crate::model::ip::range::Ipv6Range::len) gives:
    /// a count too large to represent is still enormous, and a wrapped one reads
    /// as small.
    pub fn v4_len(&self) -> u128 {
        self.v4
            .iter()
            .fold(0u128, |total, r| total.saturating_add(r.len() as u128))
    }

    /// The IPv6 half of [`v4_len`](Self::v4_len).
    pub fn v6_len(&self) -> u128 {
        self.v6
            .iter()
            .fold(0u128, |total, r| total.saturating_add(r.len()))
    }

    /// Returns the underlying IPv4 ranges. If dirty, these ranges may be overlapping and un-merged.
    pub fn v4(&self) -> &[Ipv4Range] {
        &self.v4
    }

    /// Returns the underlying IPv6 ranges. If dirty, these ranges may be overlapping and un-merged.
    pub fn v6(&self) -> &[Ipv6Range] {
        &self.v6
    }
}

impl PartialEq for IpSet {
    /// Whether the two sets hold the same addresses.
    ///
    /// Written by hand rather than derived because the derive compared the
    /// range vectors as written and the dirty flags beside them, so one address
    /// inserted twice and the same address inserted once were different sets.
    /// What a caller means by `==` here is the addresses.
    ///
    /// Merged ranges are the only comparable form, so a set that is not in one
    /// is merged on a clone — the same trade [`len`](Self::len) makes, and for
    /// the same reason: comparing is a read, and a read does not mutate its
    /// operand. Two sets that have both been canonicalized, which is every set
    /// that reached a `TargetSet`, compare without allocating.
    fn eq(&self, other: &Self) -> bool {
        fn merged(set: &IpSet) -> Cow<'_, IpSet> {
            if set.v4_dirty || set.v6_dirty {
                let mut owned = set.clone();
                owned.canonicalize();
                Cow::Owned(owned)
            } else {
                Cow::Borrowed(set)
            }
        }

        let (this, that) = (merged(self), merged(other));
        this.v4 == that.v4 && this.v6 == that.v6
    }
}

/// Whether any range in `ranges` holds `target`, by binary search.
///
/// `bounds` reads a range's inclusive ends, widened to `u128` so that one
/// search serves both families.
///
/// **`ranges` must be sorted by start address and free of overlap.** Against
/// overlapping ranges the search can land on one that ends before the target,
/// conclude the target lies further right, and never look at the range on its
/// left that holds it. Each family reaches that precondition its own way: the
/// IPv4 vector is disjoint once merged, and the IPv6 vector only within a
/// single zone's run — see [`IpSet::v6_runs`].
fn holds<R>(ranges: &[R], target: u128, bounds: impl Fn(&R) -> (u128, u128)) -> bool {
    ranges
        .binary_search_by(|range| {
            let (start, end) = bounds(range);
            if target < start {
                std::cmp::Ordering::Greater
            } else if target > end {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Equal
            }
        })
        .is_ok()
}

// ══════════════════════════════════════════════════════════════════════════════
// Conversion Traits
// ══════════════════════════════════════════════════════════════════════════════

impl IntoIterator for IpSet {
    type Item = IpAddr;
    type IntoIter = Box<dyn Iterator<Item = IpAddr> + Send>;

    /// Consumes the `IpSet` and returns an iterator over its individual IP addresses.
    fn into_iter(mut self) -> Self::IntoIter {
        self.canonicalize();
        let v4_iter = self.v4.into_iter().flat_map(|range| {
            let start: u32 = range.start_addr().into();
            let end: u32 = range.end_addr().into();
            (start..=end).map(|ip| IpAddr::V4(Ipv4Addr::from(ip)))
        });

        let v6_iter = self.v6.into_iter().flat_map(|range| {
            let start: u128 = range.start_addr().into();
            let end: u128 = range.end_addr().into();
            (start..=end).map(|ip| IpAddr::V6(Ipv6Addr::from(ip)))
        });

        Box::new(v4_iter.chain(v6_iter))
    }
}

impl Extend<IpAddr> for IpSet {
    /// Marks only the families that actually gained a range.
    ///
    /// A set is merged per family, so extending with IPv4 addresses alone must
    /// not put IPv6 membership back on its slow path, and extending with
    /// nothing must not undo a `canonicalize` that has already run.
    fn extend<T: IntoIterator<Item = IpAddr>>(&mut self, iter: T) {
        for ip in iter {
            match ip {
                IpAddr::V4(v4) => self.push_v4_range(Ipv4Range::single(v4)),
                IpAddr::V6(v6) => self.push_v6_range(Ipv6Range::single(v6)),
            }
        }
    }
}

impl FromIterator<IpAddr> for IpSet {
    fn from_iter<I: IntoIterator<Item = IpAddr>>(iter: I) -> Self {
        let mut set = IpSet::new();
        set.extend(iter);
        set.canonicalize();
        set
    }
}

impl FromIterator<IpRange> for IpSet {
    fn from_iter<I: IntoIterator<Item = IpRange>>(iter: I) -> Self {
        let mut set = IpSet::new();
        for range in iter {
            set.insert_range(range);
        }
        set.canonicalize();
        set
    }
}

impl FromIterator<IpSet> for IpSet {
    fn from_iter<I: IntoIterator<Item = IpSet>>(iter: I) -> Self {
        let mut master = IpSet::new();
        for set in iter {
            if !set.v4.is_empty() {
                master.v4.extend(set.v4);
                master.v4_dirty = true;
            }
            if !set.v6.is_empty() {
                master.v6.extend(set.v6);
                master.v6_dirty = true;
            }
        }
        master.canonicalize();
        master
    }
}

impl From<IpAddr> for IpSet {
    fn from(ip: IpAddr) -> Self {
        let mut set = Self::new();
        set.insert(ip);
        set
    }
}

impl From<IpRange> for IpSet {
    fn from(range: IpRange) -> Self {
        let mut set = Self::new();
        set.insert_range(range);
        set
    }
}

impl TryFrom<&str> for IpSet {
    type Error = IpSetError;
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let mut set = IpSet::new();
        for part in value
            .split([',', ' '])
            .filter(|part| !part.trim().is_empty())
        {
            let range = part.parse::<IpRange>()?;
            set.insert_range(range);
        }
        set.canonicalize();
        Ok(set)
    }
}

impl FromStr for IpSet {
    type Err = IpSetError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

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

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

    /// The lazy state, seen from outside: two adjacent addresses stay two
    /// ranges until canonicalized, then become one, and the count is right
    /// either way.
    #[test]
    fn adjacent_addresses_merge_when_the_set_is_canonicalized() {
        let mut set = IpSet::new();
        set.insert(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)));
        set.insert(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 2)));

        // Before canonicalization, they stay as individual pushes
        assert_eq!(set.v4.len(), 2);
        assert!(set.v4_dirty);

        // Explicitly canonicalize since queries are now immutable
        set.canonicalize();
        assert_eq!(set.len(), 2);
        assert!(!set.v4_dirty);
        assert_eq!(set.v4.len(), 1);
    }

    /// Every arrangement two ranges can be in — overlapping at the start, at
    /// the end, disjoint, and one subsuming the rest — collapsing to the single
    /// range that covers them. Counted once each, which is what makes `len` a
    /// number a budget can be checked against.
    #[test]
    fn every_kind_of_overlap_collapses_to_one_range() {
        let mut set = IpSet::new();
        // Insert: [10-20]
        set.insert_range("10.0.0.10-10.0.0.20".parse().unwrap());
        // Insert: [5-15] (overlap start)
        set.insert_range("10.0.0.5-10.0.0.15".parse().unwrap());
        // Insert: [15-25] (overlap end)
        set.insert_range("10.0.0.15-10.0.0.25".parse().unwrap());
        // Insert: [30-40] (disjoint)
        set.insert_range("10.0.0.30-10.0.0.40".parse().unwrap());
        // Insert: [0-50] (subsume all)
        set.insert_range("10.0.0.0-10.0.0.50".parse().unwrap());

        set.canonicalize();
        assert_eq!(set.len(), 51);
        assert_eq!(set.v4().len(), 1);
    }

    /// Adjacency is tested with a saturating add, so two addresses at the very
    /// top of the IPv6 space still merge rather than overflowing into a
    /// comparison that fails.
    #[test]
    fn the_top_of_the_ipv6_space_merges_without_overflowing() {
        let mut set = IpSet::new();
        // ::f...f (max)
        let max_v6 = Ipv6Addr::from(u128::MAX);
        let max_minus_1 = Ipv6Addr::from(u128::MAX - 1);

        set.insert(IpAddr::V6(max_minus_1));
        set.insert(IpAddr::V6(max_v6));

        set.canonicalize();
        assert_eq!(set.len(), 2);
        assert_eq!(set.v6().len(), 1);
    }

    /// Iterating is a read: it yields every address once and leaves the set in
    /// the state it found it, so a caller can iterate a set it is still
    /// building.
    #[test]
    fn iterating_yields_each_address_without_mutating_the_set() {
        let mut set = IpSet::new();
        set.insert(IpAddr::V4(Ipv4Addr::from(1)));
        set.insert(IpAddr::V4(Ipv4Addr::from(2)));

        set.canonicalize();
        let ips: Vec<IpAddr> = set.iter().collect();
        assert_eq!(ips.len(), 2);
        assert!(!set.v4_dirty);
    }

    /// Canonicalizing an empty set is a no-op rather than an error, so a caller
    /// that built nothing does not have to check before reading.
    #[test]
    fn an_empty_set_canonicalizes_and_counts_as_zero() {
        let mut set = IpSet::new();
        set.canonicalize();
        assert_eq!(set.len_canonical(), 0);
        assert!(set.v4().is_empty());
    }

    /// A set is merged per family, so work on one must not undo the other's
    /// canonical state. Marking both put IPv6 membership back on its linear
    /// path every time an IPv4 address arrived.
    #[test]
    fn extending_one_family_leaves_the_other_canonical() {
        let mut set = IpSet::from_iter(vec![IpAddr::V6(Ipv6Addr::LOCALHOST)]);
        assert!(!set.v4_dirty && !set.v6_dirty, "from_iter canonicalizes");

        set.extend([IpAddr::V4(Ipv4Addr::LOCALHOST)]);

        assert!(set.v4_dirty, "the family that gained a range");
        assert!(!set.v6_dirty, "and only that one");

        // And extending with nothing does not undo a merge that already ran.
        let mut untouched = IpSet::from_iter(vec![IpAddr::V4(Ipv4Addr::LOCALHOST)]);
        untouched.extend([]);
        assert!(!untouched.v4_dirty && !untouched.v6_dirty);
    }

    /// One string naming both families, with a duplicate across two spellings
    /// that has to be counted once.
    #[test]
    fn a_written_set_may_mix_both_families_and_still_counts_distinctly() {
        let set = IpSet::from_str("1.1.1.1/32, 1.1.1.1, ::1-::1, 10.0.0.1-10.0.0.2").unwrap();
        // 1.1.1.1 (v4) + ::1 (v6) + 10.0.0.1, 10.0.0.2 (v4)
        assert_eq!(set.len(), 4);
    }

    /// Insertion appends and defers the merge, so a hundred addresses are a
    /// hundred ranges until `canonicalize` runs. That is the whole point of the
    /// split — merging on each insertion makes loading a target file quadratic.
    #[test]
    fn insertion_defers_the_merge_until_it_is_asked_for() {
        let mut set = IpSet::new();
        let ips = (0..100).map(|i| IpAddr::V4(Ipv4Addr::from(i)));
        set.extend(ips);

        assert_eq!(set.v4.len(), 100);
        set.canonicalize();
        assert_eq!(set.v4.len(), 1);
        assert_eq!(set.len(), 100);
    }

    /// The guard is the only thing that makes the private fast paths safe to
    /// have at all: `contains_canonical` binary-searches a vector that is
    /// sorted only once `canonicalize` has run, and against an unmerged one it
    /// silently misses. A wrong answer about whether an address is in scope
    /// decides whether a reply is credited or discarded, so a test that never
    /// trips the assertion is testing nothing, and would pass with the
    /// `debug_assert!` deleted.
    ///
    /// Debug-only because that is where the assertion exists; a release build
    /// compiles it out and takes the silently-wrong path this pins.
    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "must be canonicalized")]
    fn a_membership_query_on_an_unmerged_set_trips_the_guard() {
        let mut set = IpSet::new();
        set.insert(IpAddr::V4(Ipv4Addr::LOCALHOST));
        // Deliberately not canonicalized.
        set.contains_canonical(&IpAddr::V4(Ipv4Addr::LOCALHOST));
    }

    /// And the same for the count, which has its own guard for its own reason.
    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "must be canonicalized")]
    fn a_count_on_an_unmerged_set_trips_the_guard() {
        let mut set = IpSet::new();
        set.insert(IpAddr::V4(Ipv4Addr::LOCALHOST));
        set.len_canonical();
    }

    /// The case the guards let through, and the one the public `contains`
    /// delegates to once the set is merged.
    #[test]
    fn a_membership_query_on_a_merged_set_answers() {
        let set = IpSet::from_iter(vec![IpAddr::V4(Ipv4Addr::LOCALHOST)]);
        assert!(!set.v4_dirty, "from_iter canonicalizes");
        assert!(set.contains_canonical(&IpAddr::V4(Ipv4Addr::LOCALHOST)));
        assert_eq!(set.len_canonical(), 1);
    }

    /// Two link-local ranges spanning the same numbers on two interfaces are
    /// two different sets of machines. Merged on adjacency alone they would
    /// produce one range that means one thing at one end and something else at
    /// the other. Every interface holds an `fe80::/64`, so the mistake is
    /// available on any host with two of them.
    #[test]
    fn ranges_on_different_interfaces_never_merge_however_adjacent() {
        let one: Ipv6Addr = "fe80::1".parse().unwrap();
        let five: Ipv6Addr = "fe80::5".parse().unwrap();
        let six: Ipv6Addr = "fe80::6".parse().unwrap();
        let ten: Ipv6Addr = "fe80::a".parse().unwrap();

        let mut split = IpSet::new();
        split.push_v6_range(Ipv6Range::scoped(one, five, Some(4)).unwrap());
        split.push_v6_range(Ipv6Range::scoped(six, ten, Some(9)).unwrap());
        split.canonicalize();

        assert_eq!(split.v6().len(), 2, "adjacent, but on two segments");

        // The same numbers on one interface are one segment's worth of
        // machines, and do merge — or the zone check would be refusing
        // everything rather than refusing the right thing.
        let mut joined = IpSet::new();
        joined.push_v6_range(Ipv6Range::scoped(one, five, Some(4)).unwrap());
        joined.push_v6_range(Ipv6Range::scoped(six, ten, Some(4)).unwrap());
        joined.canonicalize();

        assert_eq!(joined.v6().len(), 1);

        // Membership still answers across the split.
        assert!(split.contains(&IpAddr::V6(five)));
        assert!(split.contains(&IpAddr::V6(six)));
    }

    /// Equality is about the addresses a set holds, not about whether it has
    /// been merged yet. Derived, it compared the dirty flags and the range
    /// vectors as written, so the same one address inserted two ways compared
    /// unequal — and `assert_eq!` on two sets was answering a question about
    /// bookkeeping.
    #[test]
    fn two_sets_holding_the_same_addresses_are_equal_however_they_were_built() {
        let canonical = IpSet::try_from("10.0.0.1-10.0.0.2, ::1").expect("parses");

        let mut piecemeal = IpSet::new();
        piecemeal.insert(IpAddr::V6(Ipv6Addr::LOCALHOST));
        piecemeal.insert(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2)));
        piecemeal.insert(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)));

        assert_eq!(canonical, piecemeal, "same addresses, different order");
        assert_ne!(canonical, IpSet::try_from("10.0.0.1, ::1").expect("parses"));
    }

    /// Refusing to merge across zones leaves ranges that *overlap* as well as
    /// ranges that abut, and a binary search cannot navigate an overlapping
    /// vector: it lands on a range that ends before the target, concludes the
    /// target lies further right, and never examines the range on its left
    /// that holds it.
    ///
    /// Two interfaces each carrying a slice of `fe80::/64` is the ordinary
    /// shape of a dual-homed segment, and a missed membership test there
    /// discards a reply from a host that did answer.
    #[test]
    fn membership_answers_when_ranges_on_different_interfaces_overlap() {
        let one: Ipv6Addr = "fe80::1".parse().unwrap();
        let two: Ipv6Addr = "fe80::2".parse().unwrap();
        let three: Ipv6Addr = "fe80::3".parse().unwrap();
        let ten: Ipv6Addr = "fe80::a".parse().unwrap();

        let mut set = IpSet::new();
        set.push_v6_range(Ipv6Range::scoped(one, ten, Some(4)).unwrap());
        set.push_v6_range(Ipv6Range::scoped(two, three, Some(9)).unwrap());
        set.canonicalize();

        for address in [one, two, three, ten] {
            assert!(
                set.contains(&IpAddr::V6(address)),
                "{address} is covered by the range on interface 4"
            );
        }
        assert!(!set.contains(&IpAddr::V6("fe80::b".parse().unwrap())));
    }
}

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

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

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

    /// Zoned ranges drawn from one narrow band of `fe80::/64`, so that
    /// generated ranges overlap each other often rather than by luck. Four
    /// zones, which is the shape of a multi-homed host.
    fn any_zoned_v6_range() -> impl Strategy<Value = Ipv6Range> {
        (0..64u128, 0..64u128, prop::option::of(0..4u32)).prop_map(|(a, b, zone)| {
            let base = u128::from(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0));
            let (low, high) = if a <= b { (a, b) } else { (b, a) };
            Ipv6Range::scoped(
                Ipv6Addr::from(base + low),
                Ipv6Addr::from(base + high),
                zone,
            )
            .expect("low <= high")
        })
    }

    proptest::proptest! {
        /// Membership has to agree with a linear scan of the same ranges.
        ///
        /// The fast path is a binary search, which is only valid over ranges
        /// that do not overlap. Zones are what put overlapping ranges in one
        /// vector — `merge_v6` refuses to combine ranges from two interfaces —
        /// so this is where a search that steps past the range holding the
        /// target shows up. An example of that is pinned in
        /// `membership_answers_when_ranges_on_different_interfaces_overlap`;
        /// this covers the arrangements nobody thought to write down.
        #[test]
        fn zoned_membership_agrees_with_a_linear_scan(
            ranges in prop::collection::vec(any_zoned_v6_range(), 1..12),
            offsets in prop::collection::vec(0..80u128, 1..20),
        ) {
            let mut set = IpSet::new();
            for range in &ranges {
                set.push_v6_range(*range);
            }
            set.canonicalize();

            let base = u128::from(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0));
            for offset in offsets {
                let probe = Ipv6Addr::from(base + offset);
                let expected = ranges.iter().any(|range| range.contains(&probe));
                prop_assert_eq!(
                    set.contains(&IpAddr::V6(probe)),
                    expected,
                    "{} in {:?}", probe, ranges
                );
            }
        }

        #[test]
        fn v4_membership_invariant(ips in proptest::collection::vec(any_ipv4(), 1..50)) {
            let mut set = IpSet::new();
            for &ip in &ips {
                set.insert(IpAddr::V4(ip));
            }
            for ip in ips {
                prop_assert!(set.contains(&IpAddr::V4(ip)));
            }
        }

        #[test]
        fn v6_membership_invariant(ips in proptest::collection::vec(any_ipv6(), 1..50)) {
            let mut set = IpSet::new();
            for &ip in &ips {
                set.insert(IpAddr::V6(ip));
            }
            for ip in ips {
                prop_assert!(set.contains(&IpAddr::V6(ip)));
            }
        }

        #[test]
        fn order_independence_mixed(
            ips in proptest::collection::vec(
                prop_oneof![
                    any_ipv4().prop_map(IpAddr::V4),
                    any_ipv6().prop_map(IpAddr::V6),
                ],
                0..50
            )
        ) {
            let mut set1 = IpSet::new();
            let mut set2 = IpSet::new();

            for &ip in &ips { set1.insert(ip); }
            let mut ips_rev = ips.clone();
            ips_rev.reverse();
            for &ip in &ips_rev { set2.insert(ip); }

            set1.canonicalize();
            set2.canonicalize();
            prop_assert_eq!(set1, set2);
        }
    }
}