zond-engine 0.18.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
// 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

//! # Which ports to ask about
//!
//! [`PortSet`] is the port half of a scan's target specification: what a person
//! wrote, such as `"80, 443, 1000-2000, u:53, s:2905"`, held as disjoint ranges
//! per protocol. A qualifier in front of a token names the transport for it and
//! for every token after it until the next one, as nmap reads its own, and the
//! spelling belongs to [`Protocol::spec_prefix`].
//!
//! It is built once and never mutated. Every construction path merges and
//! sorts before returning, and there is no method that can undo that, so a
//! `PortSet` is canonical from the moment it exists. Two consequences follow,
//! and both are relied on elsewhere:
//!
//! - Membership is a binary search over sorted disjoint ranges, and it takes
//!   `&self`. A set can be shared across every worker in a scan with no lock,
//!   because there is nothing for a lock to protect.
//! - `Hash` agrees with `Eq`. Two sets holding the same ports hold identical
//!   range vectors whatever order or spelling produced them, which is what lets
//!   [`TargetMapBuilder`](crate::model::parse::target::TargetMapBuilder) group
//!   targets by port specification in constant time per target rather than by
//!   scanning the groups it has so far.

use crate::model::port::Protocol;
use std::{
    fmt,
    num::{IntErrorKind, ParseIntError},
    ops::RangeInclusive,
    str::FromStr,
};
use thiserror::Error;

/// The ports [`PortSet::common_discovery`] names: a handful that answer often
/// enough to be worth asking every host about, across Linux, Windows and
/// networking gear.
///
/// SSH, HTTP, HTTPS, SMB and RDP. Numbers rather than a written specification,
/// so that everything reaching for this list reaches for the same one: the
/// unprivileged discovery sweep probes exactly these, and a second spelling
/// somewhere else is a second list to keep in step.
pub const COMMON_DISCOVERY_PORTS: &[u16] = &[22, 80, 443, 445, 3389];

/// Where a range with its start left off begins: `-1024` means `1-1024`.
///
/// One rather than zero. Port 0 is reserved and nothing listens on it, so
/// including it in an open-ended range would spend a probe per host to
/// re-establish that, and `-` is the specification people reach for when the port
/// count is already enormous. A caller who wants it can still name `0` outright.
const FIRST_PORT: u16 = 1;

// ══════════════════════════════════════════════════════════════════════════════
// Error Types
// ══════════════════════════════════════════════════════════════════════════════

/// Errors that can occur when parsing a port range string.
///
/// Each one is printed at whoever wrote the specification, so each says what
/// was wrong with which token and then, in parentheses, what to write instead.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum PortSetParseError {
    /// A port was not a number, or was too large to be one. Ports are 16-bit,
    /// so `70000` fails here rather than wrapping to `4464`.
    #[error("{}", invalid_port(input, source))]
    InvalidPort {
        /// The token as written, so a user can find it in what they typed.
        input: String,
        /// Why it did not parse.
        #[source]
        source: ParseIntError,
    },

    /// A range was written backwards, as in `80-20`.
    #[error("range {start}-{end} runs backwards (write {end}-{start})")]
    InvalidRange {
        /// The lower bound as written, which is the larger of the two.
        start: u16,
        /// The upper bound as written.
        end: u16,
    },

    /// The input segment did not match any known port or range format.
    #[error("'{0}' is not a port or a range (write 22 or 1-1024)")]
    MalformedSpec(String),

    /// A range was written with spaces around its dash, as in `80 - 90`.
    ///
    /// Refused rather than read, because spaces separate ports: the halves of
    /// `80 - 90` are an open-ended range each, and the dash between them
    /// alone is every port there is. Carries the range as written.
    #[error("'{0}' has spaces in a range (write {joined})", joined = .0.split_whitespace().collect::<String>())]
    SpacedRange(String),

    /// A name was written where a port number goes, as in `ssh`.
    ///
    /// Carries the token as written, qualifier included. Which port a name
    /// stands for is not this grammar's to say: nmap reads one through its
    /// services table, this engine has none to agree with it on, and a
    /// specification that meant different ports on two builds would be a scan
    /// nobody could repeat. A front end that wants to suggest the number can
    /// ask the signature corpus, which knows the services it identifies.
    #[error("'{0}' is a name, not a port number (write one, as 22)")]
    ServiceName(String),

    /// A specification that is to name the ports a scan covers named none, as
    /// `""` or `" , "` does.
    ///
    /// Never returned by [`PortSet::try_from`], for which the empty string is
    /// the empty set, the rendering of one and what reads back from it. What
    /// refuses it is every place a specification says what to scan: a target's
    /// port half, a scan request's ports and a settings file's default. There
    /// an empty set plans a scan of nothing, which finishes without a word.
    #[error("names no ports (write 22 or 1-1024)")]
    NoPorts,
}

/// The message for a token that is not a port number, by why it is not one.
fn invalid_port(input: &str, source: &ParseIntError) -> String {
    match source.kind() {
        IntErrorKind::PosOverflow => format!("'{input}' is not a port (the highest is 65535)"),
        // Only a qualifier with nothing behind it gets this far empty: an end
        // left off a range is an open end.
        IntErrorKind::Empty => format!("'{input}' names no port (write {input}53)"),
        _ => format!("'{input}' is not a port number (write 22, 1-1024 or u:53)"),
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// PortSet Core Model
// ══════════════════════════════════════════════════════════════════════════════

/// The ports a scan asks about on each transport, as sorted disjoint ranges.
///
/// Canonical from construction and immutable afterwards; the module
/// documentation has what that buys and who relies on it.
///
/// Ranges rather than a set of numbers because the specifications people write
/// are overwhelmingly contiguous, such as `1-1024` or `1-65535`, and holding
/// sixty-five thousand `u16`s to represent one of them costs memory per target
/// group, of which a large import has many.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PortSet {
    tcp: Vec<RangeInclusive<u16>>,
    udp: Vec<RangeInclusive<u16>>,
    sctp: Vec<RangeInclusive<u16>>,
}

impl PortSet {
    /// Creates a new, empty `PortSet`.
    pub fn new() -> Self {
        Self {
            tcp: Vec::new(),
            udp: Vec::new(),
            sctp: Vec::new(),
        }
    }

    /// The ports worth asking every host about when the caller named none:
    /// [`COMMON_DISCOVERY_PORTS`].
    ///
    /// A deliberate choice rather than a neutral value, which is why it is not
    /// [`Default`]. A caller that scans this set is scanning what this crate
    /// picked, and should have said so.
    ///
    /// Built from the numbers rather than by parsing a written specification.
    /// The round trip was a fallible call on a constant this module owns, so a
    /// typo in the constant was a panic at a consumer's first call rather than
    /// something the compiler could catch.
    pub fn common_discovery() -> Self {
        COMMON_DISCOVERY_PORTS
            .iter()
            .map(|&port| (port, Protocol::Tcp))
            .collect()
    }

    /// The `count` TCP ports this engine would ask about first.
    ///
    /// The default a scan uses when the caller named no ports, and the answer to
    /// `--top-ports`. See [`catalog`](crate::model::port::catalog) for where the
    /// ranking comes from and how precisely to read it; the short version is
    /// that the first hundred are ranked against each other and the rest are
    /// grouped into tiers of comparable likelihood.
    ///
    /// Clamped to what the catalogue holds, so a caller passing a number a
    /// person typed gets every port there is rather than a panic.
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::model::port::set::PortSet;
    ///
    /// let top = PortSet::top_tcp(100);
    /// assert!(top.has_tcp(443));
    /// // Outside the well-known range, and running a service on a great many
    /// // home servers. This is what `1-1024` was missing.
    /// assert!(PortSet::top_tcp(1000).has_tcp(5432));
    /// ```
    pub fn top_tcp(count: usize) -> Self {
        super::catalog::top_tcp(count)
            .iter()
            .map(|&port| (port, Protocol::Tcp))
            .collect()
    }

    /// The `count` UDP ports this engine would ask about first.
    ///
    /// The counterpart of [`top_tcp`](Self::top_tcp), drawn from a much shorter
    /// list: a UDP port costs far more to classify and far
    /// more of them come back
    /// [`OpenFiltered`](crate::model::port::PortState::OpenFiltered) whatever is
    /// done, so the catalogue stops where the extra probes stop buying
    /// certainty.
    pub fn top_udp(count: usize) -> Self {
        super::catalog::top_udp(count)
            .iter()
            .map(|&port| (port, Protocol::Udp))
            .collect()
    }

    /// The `count` SCTP ports this engine would ask about first.
    ///
    /// The one list of the three that is not a default. A scan reaches SCTP
    /// only where a port specification named it, so this is what a front end
    /// offering the scan asks for rather than what fills in a blank. It is also
    /// the shortest by an order of magnitude, and
    /// [`catalog::SCTP_BY_PREVALENCE`](super::catalog::SCTP_BY_PREVALENCE) has
    /// the argument for why a closed set needs no tail.
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::model::port::set::PortSet;
    ///
    /// // The mobile core comes first, so a short list is still a useful one.
    /// assert!(PortSet::top_sctp(3).has_sctp(3868));
    /// ```
    pub fn top_sctp(count: usize) -> Self {
        super::catalog::top_sctp(count)
            .iter()
            .map(|&port| (port, Protocol::Sctp))
            .collect()
    }

    /// Returns the total number of unique port/protocol combinations.
    ///
    /// Note: This counts every individual port within every range.
    pub fn len(&self) -> usize {
        Protocol::ALL
            .iter()
            .copied()
            .map(|protocol| self.len_on(protocol))
            .sum()
    }

    /// Returns `true` if no ports are defined on any protocol.
    pub fn is_empty(&self) -> bool {
        Protocol::ALL
            .iter()
            .copied()
            .all(|protocol| self.ranges(protocol).is_empty())
    }

    /// Returns an iterator over all individual ports in the set.
    ///
    /// Walks the protocols in [`Protocol::ALL`] order, so a set renders and
    /// enumerates the same way whatever order it was written in.
    pub fn iter(&self) -> impl Iterator<Item = (u16, Protocol)> + '_ {
        Protocol::ALL.iter().copied().flat_map(move |protocol| {
            self.ranges(protocol)
                .iter()
                .flat_map(move |range| range.clone().map(move |port| (port, protocol)))
        })
    }

    /// Flattens the set into a vector of individual ports.
    pub fn to_vec(&self) -> Vec<(u16, Protocol)> {
        self.iter().collect()
    }

    /// The ports on one transport, as the merged ranges they are stored as.
    ///
    /// Ascending and non-overlapping from construction. Exposed as ranges rather
    /// than as ports because that is what they are: a full sweep is one entry
    /// here and sixty-five thousand through [`iter`](Self::iter).
    pub fn ranges(&self, protocol: Protocol) -> &[RangeInclusive<u16>] {
        match protocol {
            Protocol::Tcp => &self.tcp,
            Protocol::Udp => &self.udp,
            Protocol::Sctp => &self.sctp,
        }
    }

    /// The lane a protocol's ranges are built into.
    ///
    /// The one exhaustive match over [`Protocol`] on the write side, so a
    /// transport added to the enum stops this compiling until somebody says
    /// where its ports go. A catch-all here, or a local vector nobody returns,
    /// would drop them and produce a set quietly missing what it was given.
    fn lane_mut(&mut self, protocol: Protocol) -> &mut Vec<RangeInclusive<u16>> {
        match protocol {
            Protocol::Tcp => &mut self.tcp,
            Protocol::Udp => &mut self.udp,
            Protocol::Sctp => &mut self.sctp,
        }
    }

    /// How many ports the set holds on one transport.
    pub fn len_on(&self, protocol: Protocol) -> usize {
        self.ranges(protocol)
            .iter()
            .map(|range| usize::from(*range.end() - *range.start()) + 1)
            .sum()
    }

    /// The ports in either set.
    ///
    /// Merged as ranges rather than expanded, so uniting two full sweeps costs
    /// two entries and not a hundred and thirty thousand.
    pub fn union(&self, other: &PortSet) -> PortSet {
        let mut merged = PortSet::new();
        for &protocol in Protocol::ALL {
            let lane = merged.lane_mut(protocol);
            lane.extend(self.ranges(protocol).iter().cloned());
            lane.extend(other.ranges(protocol).iter().cloned());
            Self::merge_ranges(lane);
        }
        merged
    }

    /// The ports in this set and not in `other`.
    ///
    /// Cut as ranges rather than expanded, for the reason [`union`](Self::union)
    /// merges them: taking one port out of a full sweep leaves two entries, not
    /// sixty-five thousand. The result is canonical, as every set is.
    ///
    /// ```
    /// use zond_engine::model::port::set::PortSet;
    ///
    /// let scan = PortSet::try_from("1-1024,9100,u:53").unwrap();
    /// let kept = scan.difference(&PortSet::try_from("22,9100-9107").unwrap());
    /// assert_eq!(kept.to_string(), "1-21,23-1024,u:53");
    /// ```
    pub fn difference(&self, other: &PortSet) -> PortSet {
        let mut kept = PortSet::new();
        for &protocol in Protocol::ALL {
            let cuts = other.ranges(protocol);
            let lane = kept.lane_mut(protocol);
            for range in self.ranges(protocol) {
                // What is left of `range` from here up; `None` once a cut
                // reached its end. Both lists are sorted and disjoint, so each
                // cut past the range's end is one no later range reaches first.
                let mut rest = Some(*range.start());
                for cut in cuts {
                    let Some(start) = rest else { break };
                    if *cut.end() < start {
                        continue;
                    }
                    if *cut.start() > *range.end() {
                        break;
                    }
                    if *cut.start() > start {
                        lane.push(start..=*cut.start() - 1);
                    }
                    rest = cut.end().checked_add(1).filter(|next| next <= range.end());
                }
                if let Some(start) = rest {
                    lane.push(start..=*range.end());
                }
            }
        }
        kept
    }

    /// Whether the set holds `port` on `protocol`. A binary search over the
    /// merged ranges, so the cost follows how many ranges were written rather
    /// than how many ports they cover.
    pub fn contains(&self, port: u16, protocol: Protocol) -> bool {
        self.ranges(protocol)
            .binary_search_by(|range| {
                if port < *range.start() {
                    std::cmp::Ordering::Greater
                } else if port > *range.end() {
                    std::cmp::Ordering::Less
                } else {
                    std::cmp::Ordering::Equal
                }
            })
            .is_ok()
    }

    /// Whether `port` is in the TCP half of the set.
    pub fn has_tcp(&self, port: u16) -> bool {
        self.contains(port, Protocol::Tcp)
    }

    /// Whether `port` is in the UDP half of the set.
    pub fn has_udp(&self, port: u16) -> bool {
        self.contains(port, Protocol::Udp)
    }

    /// Whether `port` is in the SCTP half of the set.
    pub fn has_sctp(&self, port: u16) -> bool {
        self.contains(port, Protocol::Sctp)
    }

    // ─── Internal Utility ────────────────────────────────────────────────────

    /// Sorts and merges overlapping/adjacent ranges.
    /// Called automatically during construction.
    fn merge_ranges(ranges: &mut Vec<RangeInclusive<u16>>) {
        if ranges.is_empty() {
            return;
        }

        ranges.sort_by_key(|r| *r.start());
        let mut merged = Vec::with_capacity(ranges.len());
        let mut it = ranges.drain(..);
        let mut current = it.next().unwrap();

        for next in it {
            // Check for overlap or adjacency
            if *next.start() <= (*current.end()).saturating_add(1) {
                if *next.end() > *current.end() {
                    current = *current.start()..=*next.end();
                }
            } else {
                merged.push(current);
                current = next;
            }
        }
        merged.push(current);
        *ranges = merged;
    }
}

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

impl Default for PortSet {
    /// The empty set, which is what every other `Default` in this crate means
    /// and what a struct deriving `Default` around one has to get.
    ///
    /// The opinionated set is [`common_discovery`](Self::common_discovery). It
    /// was `Default` once, which meant that
    /// [`TargetSet`](crate::model::target::TargetSet) and anything else
    /// deriving `Default` acquired a scan specification nobody wrote.
    fn default() -> Self {
        Self::new()
    }
}

/// The set as a specification [`TryFrom<&str>`](PortSet::try_from) reads back.
///
/// The canonical form: the protocols in [`Protocol::ALL`] order, each one's
/// ranges ascending behind its own prefix, a single port written as itself and a
/// run written `start-end`. TCP comes first and so needs no qualifier, and
/// every other range carries its own although the one before it would do, so
/// the rendering reads the same to a parser that takes a qualifier for one
/// token as to one that takes it until the next. Because the ranges are merged from construction, two
/// sets holding the same ports render identically, which is what lets a written
/// scope be compared with another and what lets a report record a port set as
/// one field.
///
/// An empty set renders as the empty string, and reads back as an empty set.
///
/// ```
/// use zond_engine::model::port::set::PortSet;
///
/// let set = PortSet::try_from("443, 80, 1000-1005, u:53, s:2905").unwrap();
/// assert_eq!(set.to_string(), "80,443,1000-1005,u:53,s:2905");
/// assert_eq!(PortSet::try_from(set.to_string().as_str()).unwrap(), set);
/// ```
impl fmt::Display for PortSet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut first = true;
        for &protocol in Protocol::ALL {
            for range in self.ranges(protocol) {
                if !first {
                    f.write_str(",")?;
                }
                first = false;
                f.write_str(protocol.spec_prefix())?;
                if range.start() == range.end() {
                    write!(f, "{}", range.start())?;
                } else {
                    write!(f, "{}-{}", range.start(), range.end())?;
                }
            }
        }
        Ok(())
    }
}

/// Splits a written token into the protocol a qualifier in front of it names,
/// if it carries one, and the port or range left behind.
///
/// Case-insensitive, as every other parser here reads the words a person types:
/// `U:53` is `u:53`. The qualifiers are [`Protocol::qualifier`]'s, so `t:`
/// names TCP outright, which a specification needs once it has switched to
/// another transport and wants to switch back.
fn split_qualifier(word: &str) -> (Option<Protocol>, &str) {
    for &protocol in Protocol::ALL {
        let qualifier = protocol.qualifier();
        if let Some(head) = word.get(..qualifier.len())
            && head.eq_ignore_ascii_case(qualifier)
        {
            return (Some(protocol), &word[qualifier.len()..]);
        }
    }
    (None, word)
}

/// Refuses a range written with spaces around its dash, as in `80 - 90`,
/// `80- 90` or `80 -90`.
///
/// Spaces separate ports, so each of those arrives as words, one of them with
/// an open end: a leading dash, a trailing one, or a dash on its own, which is
/// all three. An open end facing another word across nothing but spaces is
/// the one reading nobody means, since `80 - 90` would then be every port
/// there is. An open end facing a comma or the edge of the specification is
/// the ordinary open-ended range, so `80, -1024` and `-1024 8080` are what
/// they look like.
fn refuse_spaced_range(words: &[&str]) -> Result<(), PortSetParseError> {
    for (index, word) in words.iter().enumerate() {
        let opens_back = word.starts_with('-') && index > 0;
        let opens_on = word.ends_with('-') && index + 1 < words.len();
        if opens_back || opens_on {
            let first = if opens_back { index - 1 } else { index };
            let last = if opens_on { index + 1 } else { index };
            return Err(PortSetParseError::SpacedRange(
                words[first..=last].join(" "),
            ));
        }
    }
    Ok(())
}

/// Parses one port where a number goes, telling a name written there apart
/// from any other token that is not a number.
///
/// `whole` is the token the number came from, which is what the error carries,
/// so a UDP port reports `u:http` rather than `http`, which is not what
/// anybody typed.
fn port_number(text: &str, whole: &str) -> Result<u16, PortSetParseError> {
    text.parse::<u16>().map_err(|source| {
        let named = text.starts_with(|c: char| c.is_ascii_alphabetic())
            && text
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
        if named {
            PortSetParseError::ServiceName(whole.to_string())
        } else {
            PortSetParseError::InvalidPort {
                input: whole.to_string(),
                source,
            }
        }
    })
}

impl TryFrom<&str> for PortSet {
    type Error = PortSetParseError;

    /// Parses a string into a canonicalized `PortSet`.
    ///
    /// ### Format Support
    /// * **Individual**: `80`, `443`
    /// * **Ranges**: `1000-2000`
    /// * **Open-ended ranges**: `-1024` is everything up to 1024, `1024-` is
    ///   everything from it, and a bare `-` is every port there is. The
    ///   convention every scanner's users already have in their fingers, and
    ///   more use than a flag for the same thing would be, since it applies to
    ///   the UDP half (`u:-`) and to one side of a mixed specification just as
    ///   readily.
    /// * **Protocols**: TCP until a qualifier says otherwise. `u:` switches to
    ///   UDP, `s:` to SCTP and `t:` back to TCP, and a qualifier holds for
    ///   every port after it until the next one, as nmap reads them:
    ///   `u:53,161` is two UDP ports. Case-insensitive.
    /// * **Separators**: commas and spaces, in any number. A range is written
    ///   without spaces, and `80 - 90` is refused rather than read as the three
    ///   open-ended ranges it would otherwise spell.
    /// * **Mixed**: `80, 443, 161-162, u:53, s:2905`
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::model::port::set::PortSet;
    ///
    /// let set = PortSet::try_from("80, 1000-1005, u:53,161, s:2905").unwrap();
    /// assert!(set.has_tcp(80) && set.has_tcp(1000));
    /// assert!(set.has_udp(53) && set.has_udp(161));
    /// assert!(set.has_sctp(2905));
    /// assert_eq!(set.len(), 10); // 1 + 6 + 2 + 1
    ///
    /// // Back to TCP after another transport.
    /// assert!(PortSet::try_from("u:53, t:80").unwrap().has_tcp(80));
    ///
    /// // Every port there is, which is what `-p-` means on a command line.
    /// let everything = PortSet::try_from("-").unwrap();
    /// assert_eq!(everything.len(), 65_535);
    /// assert!(everything.has_tcp(1) && everything.has_tcp(65_535));
    /// ```
    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let mut set = PortSet::new();
        let mut protocol = Protocol::Tcp;

        for part in value.split(',') {
            let words: Vec<&str> = part.split_whitespace().collect();
            refuse_spaced_range(&words)?;

            for word in words {
                let (qualifier, raw_range) = split_qualifier(word);
                if let Some(named) = qualifier {
                    protocol = named;
                }

                let range = match raw_range.split('-').collect::<Vec<_>>().as_slice() {
                    [single] => {
                        let port = port_number(single, word)?;
                        port..=port
                    }
                    // An end left off means "as far as there is", at whichever
                    // end it was left off. `-` on its own is both, and so is
                    // every port.
                    [start, end] => {
                        let start = if start.is_empty() {
                            FIRST_PORT
                        } else {
                            port_number(start, start)?
                        };
                        let end = if end.is_empty() {
                            u16::MAX
                        } else {
                            port_number(end, end)?
                        };
                        if start > end {
                            return Err(PortSetParseError::InvalidRange { start, end });
                        }
                        start..=end
                    }
                    _ => return Err(PortSetParseError::MalformedSpec(word.to_string())),
                };

                set.lane_mut(protocol).push(range);
            }
        }

        for &protocol in Protocol::ALL {
            Self::merge_ranges(set.lane_mut(protocol));
        }

        Ok(set)
    }
}

impl PortSet {
    /// Parses a specification that says which ports a scan covers, refusing
    /// one that names none with [`PortSetParseError::NoPorts`].
    pub(crate) fn parse_scan(spec: &str) -> Result<Self, PortSetParseError> {
        let set = Self::try_from(spec)?;
        if set.is_empty() {
            return Err(PortSetParseError::NoPorts);
        }
        Ok(set)
    }
}

impl TryFrom<String> for PortSet {
    type Error = PortSetParseError;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::try_from(value.as_str())
    }
}

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

impl FromIterator<(u16, Protocol)> for PortSet {
    fn from_iter<T: IntoIterator<Item = (u16, Protocol)>>(iter: T) -> Self {
        let mut set = PortSet::new();
        for (port, protocol) in iter {
            set.lane_mut(protocol).push(port..=port);
        }
        for &protocol in Protocol::ALL {
            Self::merge_ranges(set.lane_mut(protocol));
        }
        set
    }
}

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

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

    /// Taking ports out of a set leaves exactly the rest, per transport.
    ///
    /// A port kept that should have gone is a probe sent to a port the caller
    /// excluded, and one lost beside it is a port nobody asked to skip. The
    /// cases are the edges a range cut can get wrong: a cut at either end of a
    /// range, one inside it, one spanning two ranges, one at 65535, and a cut
    /// on another transport leaving this one alone.
    #[test]
    fn a_difference_keeps_every_port_outside_the_cut_and_none_inside_it() {
        let set = |spec: &str| PortSet::try_from(spec).expect("a specification");

        let cases = [
            ("1-100", "1", "2-100"),
            ("1-100", "100", "1-99"),
            ("1-100", "50-60", "1-49,61-100"),
            ("1-10,20-30", "5-25", "1-4,26-30"),
            ("1-65535", "65535", "1-65534"),
            ("1-65535", "1-65535", ""),
            ("80,443", "u:80", "80,443"),
            ("80,u:53,s:2905", "u:53", "80,s:2905"),
            ("9100-9107", "9000-9007,9100-9107", ""),
        ];
        for (from, cut, left) in cases {
            let kept = set(from).difference(&set(cut));
            assert_eq!(kept.to_string(), left, "{from} less {cut}");
            for (port, protocol) in set(from).iter() {
                assert_eq!(
                    kept.contains(port, protocol),
                    !set(cut).contains(port, protocol),
                    "{from} less {cut}, at {port}/{protocol:?}"
                );
            }
        }
    }

    /// Three transports in one specification, each behind its own prefix, and
    /// the rendering reads back as what was written.
    #[test]
    fn a_specification_keeps_its_three_transports_apart() {
        let set = PortSet::try_from("80, u:53, S:2905-2906").expect("a mixed specification");

        assert!(set.has_tcp(80) && !set.has_sctp(80));
        assert!(set.has_udp(53) && !set.has_sctp(53));
        assert!(set.has_sctp(2905) && set.has_sctp(2906) && !set.has_udp(2905));
        assert_eq!(set.len_on(Protocol::Sctp), 2);

        assert_eq!(set.to_string(), "80,u:53,s:2905-2906");
        assert_eq!(PortSet::try_from(set.to_string().as_str()).unwrap(), set);
    }

    /// The UDP prefix is read the way every other word a person types is.
    ///
    /// `TcpScanTechnique::from_str` ignores case, `Keyword::from_token` ignores
    /// case, `MacAddr::from_str` takes either, and hex is hex. This was the one
    /// parser in the module that did not, and it refused `U:53` with "Failed to
    /// parse port from 'U:53'", which reads as a complaint about the number.
    ///
    /// The error also carries the token as its field promises: the whole of what
    /// was written, prefix included, rather than what is left after the prefix
    /// comes off.
    #[test]
    fn the_udp_prefix_is_read_the_way_every_other_token_is() {
        let lower = PortSet::try_from("u:53").expect("the spelling that always worked");
        let upper = PortSet::try_from("U:53").expect("and the one that did not");
        assert_eq!(lower, upper);
        assert!(upper.has_udp(53) && !upper.has_tcp(53));

        // Mixed into a specification, where it must not reach back to a TCP
        // port written before it.
        let mixed = PortSet::try_from("80, U:53, u:161-162").expect("parses");
        assert!(mixed.has_tcp(80));
        assert!(mixed.has_udp(53) && mixed.has_udp(161) && mixed.has_udp(162));
        assert!(!mixed.has_tcp(53));

        let error = PortSet::try_from("U:http")
            .expect_err("not a port")
            .to_string();
        assert!(error.contains("U:http"), "the token as written: {error}");
    }

    /// The forms a person actually writes, mixed in one specification the way
    /// they arrive on a command line.
    #[test]
    fn a_specification_may_mix_ports_ranges_and_protocols() {
        let port_set_single = PortSet::try_from("21");
        let port_set_multiple = PortSet::try_from("21, 22 80, 800-1000, u:53 t:8080");

        assert!(port_set_single.is_ok());
        assert!(port_set_multiple.is_ok());

        let port_set_single = port_set_single.unwrap();
        let port_set_multiple = port_set_multiple.unwrap();

        assert!(port_set_single.has_tcp(21));

        assert!(port_set_multiple.has_tcp(21));
        assert!(port_set_multiple.has_tcp(22));
        assert!(port_set_multiple.has_tcp(80));
        assert!(port_set_multiple.has_tcp(900));
        assert!(port_set_multiple.has_udp(53));
        assert!(port_set_multiple.has_tcp(8080));
    }

    /// `u:` is this crate's own spelling for the UDP half, and it has to apply
    /// to a range as well as to a single port.
    #[test]
    fn the_udp_prefix_applies_to_single_ports_and_to_ranges() {
        let port_set_udp = PortSet::try_from("u:22 u:53-100, u:1024");

        assert!(port_set_udp.is_ok());

        let port_set_udp = port_set_udp.unwrap();

        assert!(port_set_udp.has_udp(22));
        assert!(port_set_udp.has_udp(53));
        assert!(port_set_udp.has_udp(80));
        assert!(port_set_udp.has_udp(100));
        assert!(port_set_udp.has_udp(1024));
    }

    /// The spelling every scanner's users already know, in all three of its
    /// forms. `-p-` is the one people type; the open-ended halves fall out of
    /// the same rule and are worth having for their own sake.
    #[test]
    fn a_range_may_leave_off_either_end_or_both() {
        let everything = PortSet::try_from("-").unwrap();
        assert!(everything.has_tcp(1));
        assert!(everything.has_tcp(65_535));
        assert_eq!(everything.len(), 65_535);

        let up_to = PortSet::try_from("-1024").unwrap();
        assert!(up_to.has_tcp(1) && up_to.has_tcp(1024));
        assert!(!up_to.has_tcp(1025));

        let onward = PortSet::try_from("1024-").unwrap();
        assert!(onward.has_tcp(1024) && onward.has_tcp(65_535));
        assert!(!onward.has_tcp(1023));
    }

    /// Port 0 is reserved and nothing listens on it, so an open-ended range
    /// starts at 1. A probe per host to re-establish that is a probe wasted, and
    /// these are the specifications with the most hosts behind them. Naming it
    /// outright still works.
    #[test]
    fn an_open_ended_range_starts_at_one_and_zero_must_be_asked_for() {
        assert!(!PortSet::try_from("-").unwrap().has_tcp(0));
        assert!(PortSet::try_from("0-").unwrap().has_tcp(0));
        assert!(PortSet::try_from("0").unwrap().has_tcp(0));
    }

    /// The open ends compose with everything else the grammar has: the
    /// qualifiers, and the other members of a mixed specification.
    #[test]
    fn an_open_ended_range_composes_with_the_rest_of_the_grammar() {
        let mixed = PortSet::try_from("22, u:-, t:9000-").unwrap();

        assert!(mixed.has_tcp(22));
        assert!(mixed.has_tcp(9000) && mixed.has_tcp(65_535));
        assert!(!mixed.has_tcp(8999));
        assert!(mixed.has_udp(1) && mixed.has_udp(65_535));
    }

    /// A dash is an end left off, not a wildcard: two of them name no range and
    /// are refused rather than read as one.
    #[test]
    fn more_than_one_dash_is_still_malformed() {
        assert!(matches!(
            PortSet::try_from("--"),
            Err(PortSetParseError::MalformedSpec(_))
        ));
        assert!(matches!(
            PortSet::try_from("1-2-3"),
            Err(PortSetParseError::MalformedSpec(_))
        ));
    }

    /// Whitespace names no ports, which is a valid thing for a set to hold:
    /// the empty set is what `Default` means and what an empty set renders
    /// as, so it has to read back. Where a specification says what to scan,
    /// naming nothing is refused instead.
    #[test]
    fn a_specification_naming_nothing_is_an_empty_set_not_an_error() {
        let empty = PortSet::try_from("   ");
        assert!(empty.is_ok());
        let set = empty.unwrap();
        assert!(set.tcp.is_empty());
        assert!(set.udp.is_empty());

        for nothing in ["", "   ", " , ,"] {
            assert_eq!(
                PortSet::parse_scan(nothing),
                Err(PortSetParseError::NoPorts)
            );
        }
        assert!(PortSet::parse_scan("22").is_ok());
    }

    /// The ends of the 16-bit space, where the range arithmetic is one step
    /// from overflowing.
    #[test]
    fn the_ends_of_the_port_space_parse_and_are_held() {
        let limits = PortSet::try_from("0, 65535, u:0-65535").unwrap();
        assert!(limits.has_tcp(0));
        assert!(limits.has_tcp(65535));
        assert!(limits.has_udp(32768));
    }

    /// Target lists are hand-written and pasted together, so stray and repeated
    /// separators are ordinary rather than exceptional. Refusing them would
    /// reject a file over punctuation.
    #[test]
    fn stray_separators_are_tolerated_rather_than_refused() {
        let messy = PortSet::try_from(", 80, , 443 ,").unwrap();
        assert!(messy.has_tcp(80));
        assert!(messy.has_tcp(443));
    }

    /// Each mistake is reported as the kind of mistake it is, because the
    /// error is printed at whoever typed it. A port too large for 16 bits must
    /// not silently wrap to a port they did not ask for.
    #[test]
    fn each_malformed_specification_is_refused_with_its_own_reason() {
        let port_set_invalid_port = PortSet::try_from("80 70000 22");
        let port_set_invalid_range = PortSet::try_from("21 8000-80");
        let port_set_malformed_spec = PortSet::try_from("22 60-70-80 8080");
        let port_set_not_numeric = PortSet::try_from("u:53 12ab 80");
        let port_set_named = PortSet::try_from("u:53 abcdef 80");

        assert!(matches!(
            port_set_invalid_port,
            Err(PortSetParseError::InvalidPort { .. })
        ));

        assert!(matches!(
            port_set_invalid_range,
            Err(PortSetParseError::InvalidRange {
                start: 8000,
                end: 80
            })
        ));

        assert!(matches!(
            port_set_not_numeric,
            Err(PortSetParseError::InvalidPort { .. })
        ));

        assert!(matches!(
            port_set_named,
            Err(PortSetParseError::ServiceName(_))
        ));

        assert!(matches!(
            port_set_malformed_spec,
            Err(PortSetParseError::MalformedSpec(_))
        ));
    }

    /// A qualifier holds for every port after it until the next one, which is
    /// how nmap reads `-p U:53,161,T:21-25,80` and how anybody who learned the
    /// grammar there writes it. Read per token, `U:53,161` scans TCP 161, a
    /// port nobody asked for, and reports it as if it were the answer.
    #[test]
    fn a_qualifier_holds_until_the_next_one_as_nmap_reads_it() {
        let set = PortSet::try_from("U:53,161").expect("an nmap specification");
        assert!(set.has_udp(53) && set.has_udp(161));
        assert!(!set.has_tcp(161), "161 is UDP, as the qualifier said");

        let mixed = PortSet::try_from("8080, u:53,161, T:21-25,80, s:2905").expect("parses");
        assert!(mixed.has_tcp(8080) && mixed.has_tcp(23) && mixed.has_tcp(80));
        assert!(mixed.has_udp(53) && mixed.has_udp(161));
        assert!(!mixed.has_udp(80) && !mixed.has_tcp(161));
        assert!(mixed.has_sctp(2905));
        assert_eq!(mixed.len(), 1 + 2 + 5 + 1 + 1);

        let tcp = PortSet::try_from("t:22").expect("TCP named outright");
        assert!(tcp.has_tcp(22) && tcp.len() == 1);
    }

    /// A range written with spaces around its dash is refused, not read as the
    /// open-ended ranges its halves spell apart. `80 - 90` is three tokens,
    /// the middle one every port there is, and scanning 65,535 ports for a
    /// request for eleven is the worst reading available.
    ///
    /// Spaces still separate ports, and an open end facing a comma or the
    /// edge of the specification is still an open end.
    #[test]
    fn a_range_written_with_spaces_is_refused_rather_than_widened() {
        for (written, fix) in [
            ("80 - 90", "80-90"),
            ("80- 90", "80-90"),
            ("22, 80 -90", "80-90"),
            ("u:80 - 90", "u:80-90"),
        ] {
            let error = PortSet::try_from(written)
                .expect_err("a spaced range")
                .to_string();
            assert!(
                error.contains(&format!("write {fix}")),
                "{written}: {error}"
            );
        }

        let open = PortSet::try_from("80, -1024 9000-, 443").expect("open ends by commas");
        assert!(open.has_tcp(1) && open.has_tcp(65_535) && open.has_tcp(443));
        assert!(PortSet::try_from("-1024 8080").unwrap().has_tcp(8080));
    }

    /// Each refusal says what to write instead, since it is printed at whoever
    /// typed the specification and "invalid digit found in string" tells them
    /// only that something somewhere was not a number.
    #[test]
    fn each_refusal_says_what_to_write_instead() {
        let hint = |written: &str| PortSet::try_from(written).expect_err("refused").to_string();

        let ssh = hint("ssh");
        assert!(
            ssh.contains("'ssh' is a name") && ssh.contains("as 22"),
            "{ssh}"
        );
        let snmp = hint("U:snmp");
        assert!(snmp.contains("'U:snmp' is a name"), "{snmp}");
        let stray = hint("8o");
        assert!(
            stray.contains("'8o'") && stray.contains("write 22"),
            "{stray}"
        );
        let large = hint("70000");
        assert!(large.contains("65535"), "{large}");
        let backwards = hint("80-20");
        assert!(backwards.contains("write 20-80"), "{backwards}");
        let bare = hint("u:");
        assert!(bare.contains("write u:53"), "{bare}");
        let dashes = hint("1-2-3");
        assert!(
            dashes.contains("'1-2-3'") && dashes.contains("write"),
            "{dashes}"
        );
    }

    /// The owned-string conversion has to agree with the borrowed one, since
    /// callers reach this type from both an argument and a parsed config.
    #[test]
    fn an_owned_string_parses_the_same_as_a_borrowed_one() {
        let port_set = PortSet::try_from(String::from("21 80-100 u:5353"));

        assert!(port_set.is_ok());

        let port_set = port_set.unwrap();

        assert!(port_set.has_tcp(21));
        assert!(port_set.has_tcp(80));
        assert!(port_set.has_tcp(92));
        assert!(port_set.has_tcp(100));
        assert!(port_set.has_udp(5353));
    }

    /// Two claims, and the second is why the first is written here.
    ///
    /// Two claims, and the second is why the first is written here.
    ///
    /// `common_discovery` is the set every caller that wants this crate's
    /// opinion reaches for, including the unprivileged discovery sweep, so what
    /// it holds has to be exactly what [`COMMON_DISCOVERY_PORTS`] names. A
    /// second list somewhere else was how the sweep and this set could come to
    /// disagree with nothing reporting it.
    ///
    /// And `Default` is empty. It named those same five ports once, which meant
    /// every struct deriving `Default` around a `PortSet`, `TargetSet` among
    /// them, silently carried a scan specification nobody wrote.
    #[test]
    fn the_discovery_set_is_what_the_constant_names_and_default_stays_empty() {
        let set = PortSet::common_discovery();
        for &port in COMMON_DISCOVERY_PORTS {
            assert!(set.has_tcp(port), "{port} is named in the discovery set");
        }
        assert_eq!(
            set.len(),
            COMMON_DISCOVERY_PORTS.len(),
            "and nothing else is"
        );

        assert!(PortSet::default().is_empty());
        assert_eq!(PortSet::default(), PortSet::new());
    }

    /// Canonical from construction: overlapping, adjacent and subsumed ranges
    /// all collapse. That is what makes membership a binary search and what
    /// makes `Hash` agree with `Eq`, so two spellings of one set group together
    /// in `TargetMapBuilder`.
    #[test]
    fn overlapping_and_adjacent_ranges_collapse_on_construction() {
        // Overlap: 1-10 and 5-15 should be 1-15
        let set = PortSet::try_from("1-10, 5-15").unwrap();
        assert_eq!(set.len(), 15);
        assert_eq!(set.tcp.len(), 1);

        // Adjacency: 20 and 21 should be 20-21
        let set = PortSet::try_from("20, 21").unwrap();
        assert_eq!(set.len(), 2);
        assert_eq!(set.tcp.len(), 1);

        // Subsumption: 100-200 and 150
        let set = PortSet::try_from("100-200, 150").unwrap();
        assert_eq!(set.len(), 101);
        assert_eq!(set.tcp.len(), 1);

        // Mixed messy overlaps
        let set = PortSet::try_from("u:53, u:53-53, u:50-60, u:55-65").unwrap();
        assert_eq!(set.len(), 16); // 50 to 65
        assert_eq!(set.udp.len(), 1);
    }
}

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

    proptest::proptest! {
        /// Verify that any single port inserted is correctly contained in the set.
        #[test]
        fn single_port_roundtrip(p in 0..=65535u16) {
            let s = format!("{}", p);
            let set = PortSet::from_str(&s).unwrap();
            prop_assert!(set.has_tcp(p));
            prop_assert_eq!(set.len(), 1);
        }

        /// Verify that any port range [a, b] contains all values within it.
        #[test]
        fn port_range_invariant(a in 0..=65535u16, b in 0..=65535u16) {
            let (start, end) = if a < b { (a, b) } else { (b, a) };
            let s = format!("{}-{}", start, end);
            let set = PortSet::from_str(&s).unwrap();

            prop_assert!(set.has_tcp(start));
            prop_assert!(set.has_tcp(end));
            prop_assert_eq!(set.len(), (end - start + 1) as usize);
        }

        /// Verify that UDP prefix 'u:' correctly assigns ports to the UDP set.
        #[test]
        fn udp_prefix_honored(p in 0..=65535u16) {
            let s = format!("u:{}", p);
            let set = PortSet::from_str(&s).unwrap();
            prop_assert!(set.has_udp(p));
            prop_assert!(!set.has_tcp(p));
        }

        /// Verify that comma-separated lists correctly aggregate multiple ports.
        #[test]
        fn multiple_ports_aggregation(p1 in 0..=1000u16, p2 in 2000..=3000u16) {
            let s = format!("{}, {}", p1, p2);
            let set = PortSet::from_str(&s).unwrap();
            prop_assert!(set.has_tcp(p1));
            prop_assert!(set.has_tcp(p2));
            prop_assert_eq!(set.len(), 2);
        }

        /// Invariant: Normalization produces the same port count as a HashSet.
        #[test]
        fn normalization_invariant(ports in prop::collection::vec(0..=500u16, 1..=50)) {
            let s = ports.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(",");
            let set = PortSet::from_str(&s).unwrap();

            let unique_count = ports.into_iter().collect::<std::collections::HashSet<_>>().len();
            prop_assert_eq!(set.len(), unique_count);
            prop_assert!(set.tcp.len() <= unique_count);
        }
    }
}