oxnet 0.1.4

commonly used networking primitives with common traits implemented
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
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
// Copyright 2025 Oxide Computer Company

use std::{
    net::{AddrParseError, IpAddr, Ipv4Addr, Ipv6Addr},
    num::ParseIntError,
};

/// A prefix error during the creation of an [IpNet], [Ipv4Net], or [Ipv6Net]
#[derive(Debug, Clone)]
pub struct IpNetPrefixError(u8);

impl std::fmt::Display for IpNetPrefixError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid network prefix {}", self.0)
    }
}
impl std::error::Error for IpNetPrefixError {}

/// An error during the parsing of an [IpNet], [Ipv4Net], or [Ipv6Net]
#[derive(Debug, Clone)]
pub enum IpNetParseError {
    /// Failure to parse the address
    InvalidAddr(AddrParseError),
    /// Bad prefix value
    PrefixValue(IpNetPrefixError),
    /// No slash to indicate the prefix
    NoPrefix,
    /// Prefix parse error
    InvalidPrefix(ParseIntError),
}

impl std::fmt::Display for IpNetParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IpNetParseError::InvalidAddr(e) => e.fmt(f),
            IpNetParseError::PrefixValue(e) => {
                write!(f, "invalid prefix value: {e}")
            }
            IpNetParseError::NoPrefix => write!(f, "missing '/' character"),
            IpNetParseError::InvalidPrefix(e) => e.fmt(f),
        }
    }
}
impl std::error::Error for IpNetParseError {}

/// A subnet, either IPv4 or IPv6
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum IpNet {
    /// An IPv4 subnet
    V4(Ipv4Net),
    /// An IPv6 subnet
    V6(Ipv6Net),
}

impl IpNet {
    /// Create an IpNet with the given address and prefix width.
    pub fn new(addr: IpAddr, prefix: u8) -> Result<Self, IpNetPrefixError> {
        match addr {
            IpAddr::V4(addr) => Ok(Self::V4(Ipv4Net::new(addr, prefix)?)),
            IpAddr::V6(addr) => Ok(Self::V6(Ipv6Net::new(addr, prefix)?)),
        }
    }

    /// Create an IpNet with the given address and prefix width with no checks
    /// for the validity of the prefix length.
    pub const fn new_unchecked(addr: IpAddr, prefix: u8) -> Self {
        match addr {
            IpAddr::V4(addr) => Self::V4(Ipv4Net::new_unchecked(addr, prefix)),
            IpAddr::V6(addr) => Self::V6(Ipv6Net::new_unchecked(addr, prefix)),
        }
    }

    /// Create an IpNet that contains *exclusively* the given address.
    pub fn host_net(addr: IpAddr) -> Self {
        match addr {
            IpAddr::V4(addr) => Self::V4(Ipv4Net::host_net(addr)),
            IpAddr::V6(addr) => Self::V6(Ipv6Net::host_net(addr)),
        }
    }

    /// Return the base address.
    pub const fn addr(&self) -> IpAddr {
        match self {
            IpNet::V4(inner) => IpAddr::V4(inner.addr()),
            IpNet::V6(inner) => IpAddr::V6(inner.addr()),
        }
    }

    /// Return the prefix address (the base address with the mask applied).
    pub fn prefix(&self) -> IpAddr {
        match self {
            IpNet::V4(inner) => inner.prefix().into(),
            IpNet::V6(inner) => inner.prefix().into(),
        }
    }

    /// Return the prefix length.
    pub const fn width(&self) -> u8 {
        match self {
            IpNet::V4(inner) => inner.width(),
            IpNet::V6(inner) => inner.width(),
        }
    }

    /// Return the netmask address derived from prefix length.
    pub fn mask_addr(&self) -> IpAddr {
        match self {
            IpNet::V4(inner) => inner.mask_addr().into(),
            IpNet::V6(inner) => inner.mask_addr().into(),
        }
    }

    /// Return `true` iff the subnet contains only the base address i.e. the
    /// size is exactly one address.
    pub const fn is_host_net(&self) -> bool {
        match self {
            IpNet::V4(inner) => inner.is_host_net(),
            IpNet::V6(inner) => inner.is_host_net(),
        }
    }

    /// Return `true` iff the base address corresponds to the all-zeroes host
    /// ID in the subnet.
    pub fn is_network_address(&self) -> bool {
        match self {
            IpNet::V4(inner) => inner.is_network_address(),
            IpNet::V6(inner) => inner.is_network_address(),
        }
    }

    /// Return `true` iff this subnet is in a multicast address range.
    pub const fn is_multicast(&self) -> bool {
        match self {
            IpNet::V4(inner) => inner.is_multicast(),
            IpNet::V6(inner) => inner.is_multicast(),
        }
    }

    /// Return `true` iff this subnet is in an administratively scoped
    /// multicast address range with boundaries that are administratively
    /// configured.
    ///
    /// "Admin" is short for "administratively"; these scopes have boundaries
    /// configured by network administrators, unlike well-known scopes like
    /// link-local or global.
    ///
    /// For IPv4, this is 239.0.0.0/8 as defined in [RFC 2365] and [RFC 5771].
    /// For IPv6, this includes scopes 4, 5, and 8 (admin-local, site-local,
    /// organization-local) as defined in [RFC 7346] and [RFC 4291].
    ///
    /// [RFC 2365]: https://tools.ietf.org/html/rfc2365
    /// [RFC 5771]: https://tools.ietf.org/html/rfc5771
    /// [RFC 7346]: https://tools.ietf.org/html/rfc7346
    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
    pub const fn is_admin_scoped_multicast(&self) -> bool {
        match self {
            IpNet::V4(inner) => inner.is_admin_scoped_multicast(),
            IpNet::V6(inner) => inner.is_admin_scoped_multicast(),
        }
    }

    /// Return `true` iff this subnet is in an admin-local multicast address
    /// range (scope 4) as defined in [RFC 7346] and [RFC 4291].
    /// This is only defined for IPv6. IPv4 does not have an equivalent
    /// "admin-local" scope.
    ///
    /// [RFC 7346]: https://tools.ietf.org/html/rfc7346
    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
    pub const fn is_admin_local_multicast(&self) -> bool {
        match self {
            IpNet::V4(_inner) => false,
            IpNet::V6(inner) => inner.is_admin_local_multicast(),
        }
    }

    /// Return `true` iff this subnet is in a local multicast address range.
    /// For IPv4, this is 239.255.0.0/16 (IPv4 Local Scope) as defined in
    /// [RFC 2365]. IPv6 does not have an equivalent "local" scope.
    ///
    /// [RFC 2365]: https://tools.ietf.org/html/rfc2365
    pub const fn is_local_multicast(&self) -> bool {
        match self {
            IpNet::V4(inner) => inner.is_local_multicast(),
            IpNet::V6(_inner) => false,
        }
    }

    /// Return `true` iff this subnet is in a site-local multicast address
    /// range. This is only defined for IPv6 (scope 5) as defined in [RFC 7346]
    /// and [RFC 4291]. IPv4 does not have a site-local multicast scope.
    ///
    /// [RFC 7346]: https://tools.ietf.org/html/rfc7346
    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
    pub const fn is_site_local_multicast(&self) -> bool {
        match self {
            IpNet::V4(_inner) => false,
            IpNet::V6(inner) => inner.is_site_local_multicast(),
        }
    }

    /// Return `true` iff this subnet is in an organization-local multicast
    /// address range.
    ///
    /// For IPv4, this is 239.192.0.0/14 as defined in [RFC 2365].
    /// For IPv6, this is scope 8 as defined in [RFC 7346] and [RFC 4291].
    ///
    /// [RFC 2365]: https://tools.ietf.org/html/rfc2365
    /// [RFC 7346]: https://tools.ietf.org/html/rfc7346
    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
    pub const fn is_org_local_multicast(&self) -> bool {
        match self {
            IpNet::V4(inner) => inner.is_org_local_multicast(),
            IpNet::V6(inner) => inner.is_org_local_multicast(),
        }
    }

    /// Return `true` iff this subnet is in a Unique Local Address range.
    /// This is only valid for IPv6 addresses.
    pub const fn is_unique_local(&self) -> bool {
        match self {
            IpNet::V4(_inner) => false, // IPv4 does not support ULA
            IpNet::V6(inner) => inner.is_unique_local(),
        }
    }

    /// Return `true` iff this subnet is in a loopback address range.
    pub const fn is_loopback(&self) -> bool {
        match self {
            IpNet::V4(inner) => inner.is_loopback(),
            IpNet::V6(inner) => inner.is_loopback(),
        }
    }

    /// Return `true` if the provided address is contained in self.
    ///
    /// This returns `false` if the address and the network are of different IP
    /// families.
    pub fn contains(&self, addr: IpAddr) -> bool {
        match (self, addr) {
            (IpNet::V4(net), IpAddr::V4(ip)) => net.contains(ip),
            (IpNet::V6(net), IpAddr::V6(ip)) => net.contains(ip),
            (_, _) => false,
        }
    }

    /// Returns `true` iff this subnet is wholly contained within `other`.
    ///
    /// This returns `false` if the address and the network are of different IP
    /// families.
    pub fn is_subnet_of(&self, other: &Self) -> bool {
        match (self, other) {
            (IpNet::V4(net), IpNet::V4(other)) => net.is_subnet_of(other),
            (IpNet::V6(net), IpNet::V6(other)) => net.is_subnet_of(other),
            (_, _) => false,
        }
    }

    /// Returns `true` iff `other` is wholly contained within this subnet.
    ///
    /// This returns `false` if the address and the network are of different IP
    /// families.
    pub fn is_supernet_of(&self, other: &Self) -> bool {
        other.is_subnet_of(self)
    }

    /// Return `true` if the provided `IpNet` shares any IP addresses with
    /// `self` (e.g., `self.is_subnet_of(other)`, or vice-versa).
    ///
    /// This returns `false` if the networks are of different IP families.
    pub fn overlaps(&self, other: &Self) -> bool {
        match (self, other) {
            (IpNet::V4(net), IpNet::V4(other)) => net.overlaps(other),
            (IpNet::V6(net), IpNet::V6(other)) => net.overlaps(other),
            (_, _) => false,
        }
    }

    /// Return `true` if this is an IPv4 network.
    pub const fn is_ipv4(&self) -> bool {
        matches!(self, IpNet::V4(_))
    }

    /// Return `true` if this is an IPv6 network.
    pub const fn is_ipv6(&self) -> bool {
        matches!(self, IpNet::V6(_))
    }
}

impl From<Ipv4Net> for IpNet {
    fn from(n: Ipv4Net) -> IpNet {
        IpNet::V4(n)
    }
}

impl From<Ipv6Net> for IpNet {
    fn from(n: Ipv6Net) -> IpNet {
        IpNet::V6(n)
    }
}

impl std::fmt::Display for IpNet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IpNet::V4(inner) => write!(f, "{inner}"),
            IpNet::V6(inner) => write!(f, "{inner}"),
        }
    }
}

impl std::str::FromStr for IpNet {
    type Err = IpNetParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let Some((addr_str, prefix_str)) = s.split_once('/') else {
            return Err(IpNetParseError::NoPrefix);
        };

        let prefix = prefix_str.parse().map_err(IpNetParseError::InvalidPrefix)?;
        let addr = addr_str.parse().map_err(IpNetParseError::InvalidAddr)?;
        IpNet::new(addr, prefix).map_err(IpNetParseError::PrefixValue)
    }
}

#[cfg(feature = "schemars")]
impl schemars::JsonSchema for IpNet {
    fn schema_name() -> String {
        "IpNet".to_string()
    }

    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        use crate::schema_util::label_schema;
        schemars::schema::SchemaObject {
            subschemas: Some(Box::new(schemars::schema::SubschemaValidation {
                one_of: Some(vec![
                    label_schema("v4", gen.subschema_for::<Ipv4Net>()),
                    label_schema("v6", gen.subschema_for::<Ipv6Net>()),
                ]),
                ..Default::default()
            })),
            extensions: crate::schema_util::extension("IpNet", "0.1.0"),
            ..Default::default()
        }
        .into()
    }
}

/// The maximum width of an IPv4 subnet
pub const IPV4_NET_WIDTH_MAX: u8 = 32;

/// An IPv4 subnet
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Ipv4Net {
    addr: Ipv4Addr,
    width: u8,
}

impl Ipv4Net {
    /// Create an Ipv4Net with the given address and prefix width.
    pub fn new(addr: Ipv4Addr, width: u8) -> Result<Self, IpNetPrefixError> {
        if width > IPV4_NET_WIDTH_MAX {
            Err(IpNetPrefixError(width))
        } else {
            Ok(Self { addr, width })
        }
    }

    /// Create an Ipv4Net with the given address and prefix width with no
    /// checks for the validity of the prefix length.
    pub const fn new_unchecked(addr: Ipv4Addr, width: u8) -> Self {
        Self { addr, width }
    }

    /// Create an Ipv4Net that contains *exclusively* the given address.
    pub const fn host_net(addr: Ipv4Addr) -> Self {
        Self {
            addr,
            width: IPV4_NET_WIDTH_MAX,
        }
    }

    /// Return the base address used to create this subnet.
    pub const fn addr(&self) -> Ipv4Addr {
        self.addr
    }

    /// Return the prefix width.
    pub const fn width(&self) -> u8 {
        self.width
    }

    pub(crate) fn mask(&self) -> u32 {
        u32::MAX
            .checked_shl((IPV4_NET_WIDTH_MAX - self.width) as u32)
            .unwrap_or(0)
    }

    /// Return the netmask address derived from prefix length.
    pub fn mask_addr(&self) -> Ipv4Addr {
        Ipv4Addr::from(self.mask())
    }

    /// Return true iff the subnet contains only the base address i.e. the
    /// size is exactly one address.
    pub const fn is_host_net(&self) -> bool {
        self.width == IPV4_NET_WIDTH_MAX
    }

    /// Return `true` iff the base address corresponds to the all-zeroes host
    /// ID in the subnet.
    pub fn is_network_address(&self) -> bool {
        self.addr == self.prefix()
    }

    /// Return `true` iff this subnet is in a multicast address range.
    pub const fn is_multicast(&self) -> bool {
        self.addr.is_multicast()
    }

    /// Return `true` iff this subnet is in an administratively scoped multicast
    /// address range (239.0.0.0/8) as defined in [RFC 2365] and [RFC 5771].
    ///
    /// "Admin" is short for "administratively"; these scopes have boundaries
    /// configured by network administrators.
    ///
    /// [RFC 2365]: https://tools.ietf.org/html/rfc2365
    /// [RFC 5771]: https://tools.ietf.org/html/rfc5771
    pub const fn is_admin_scoped_multicast(&self) -> bool {
        // RFC 2365/RFC 5771, §10: The administratively scoped IPv4 multicast
        // space is 239/8
        // IPv4 multicast is 224.0.0.0/4, so 239/8 is a subset of that
        self.addr.octets()[0] == 239
    }

    /// Return `true` iff this subnet is in a local multicast address range
    /// (239.255.0.0/16) as defined in [RFC 2365]. This is the IPv4 Local
    /// Scope.
    ///
    /// [RFC 2365]: https://tools.ietf.org/html/rfc2365
    pub const fn is_local_multicast(&self) -> bool {
        // RFC 2365: 239.255.0.0/16 is defined to be the IPv4 Local Scope
        let octets = self.addr.octets();
        octets[0] == 239 && octets[1] == 255
    }

    /// Return `true` iff this subnet is in an organization-local multicast
    /// address range (239.192.0.0/14) as defined in [RFC 2365].
    ///
    /// [RFC 2365]: https://tools.ietf.org/html/rfc2365
    pub const fn is_org_local_multicast(&self) -> bool {
        // RFC 2365: The IPv4 Organization Local Scope is 239.192.0.0/14
        // This is 239.192.0.0 - 239.195.255.255
        let octets = self.addr.octets();
        octets[0] == 239 && (octets[1] >= 192 && octets[1] <= 195)
    }

    /// Return `true` iff this subnet is in a loopback address range.
    pub const fn is_loopback(&self) -> bool {
        self.addr.is_loopback()
    }

    /// Return the number of addresses contained within this subnet or None for
    /// a /0 subnet whose value would be one larger than can be represented in
    /// a `u32`.
    pub const fn size(&self) -> Option<u32> {
        1u32.checked_shl((IPV4_NET_WIDTH_MAX - self.width) as u32)
    }

    /// Return the prefix address (the base address with the mask applied).
    pub fn prefix(&self) -> Ipv4Addr {
        self.first_addr()
    }

    /// Return the network address for subnets as applicable; /31 and /32
    /// subnets return `None`.
    pub fn network(&self) -> Option<Ipv4Addr> {
        (self.width < 31).then(|| self.first_addr())
    }

    /// Return the broadcast address for subnets as applicable; /31 and /32
    /// subnets return `None`.
    pub fn broadcast(&self) -> Option<Ipv4Addr> {
        (self.width < 31).then(|| self.last_addr())
    }

    /// Return the first address within this subnet.
    pub fn first_addr(&self) -> Ipv4Addr {
        let addr: u32 = self.addr.into();
        Ipv4Addr::from(addr & self.mask())
    }

    /// Return the last address within this subnet.
    pub fn last_addr(&self) -> Ipv4Addr {
        let addr: u32 = self.addr.into();
        Ipv4Addr::from(addr | !self.mask())
    }

    /// Return the first host address within this subnet. For /31 and /32
    /// subnets that is the first address; for wider subnets this returns
    /// the address immediately after the network address.
    pub fn first_host(&self) -> Ipv4Addr {
        let mask = self.mask();
        let addr: u32 = self.addr.into();
        let first = addr & mask;
        if self.width == 31 || self.width == 32 {
            Ipv4Addr::from(first)
        } else {
            Ipv4Addr::from(first + 1)
        }
    }

    /// Return the last host address within this subnet. For /31 and /32
    /// subnets that is the last address (there is no broadcast address); for
    /// wider subnets this returns the address immediately before the broadcast
    /// address.
    pub fn last_host(&self) -> Ipv4Addr {
        let mask = self.mask();
        let addr: u32 = self.addr.into();
        let last = addr | !mask;
        if self.width == 31 || self.width == 32 {
            Ipv4Addr::from(last)
        } else {
            Ipv4Addr::from(last - 1)
        }
    }

    /// Return `true` iff the given IP address is within the subnet.
    pub fn contains(&self, other: Ipv4Addr) -> bool {
        let mask = self.mask();
        let addr: u32 = self.addr.into();
        let other: u32 = other.into();

        (addr & mask) == (other & mask)
    }

    /// Return the nth address within this subnet or none if `n` is larger than
    /// the size of the subnet.
    pub fn nth(&self, n: usize) -> Option<Ipv4Addr> {
        let addr: u32 = self.addr.into();
        let nth = addr.checked_add(n.try_into().ok()?)?;
        (nth <= self.last_addr().into()).then_some(nth.into())
    }

    /// Produce an iterator over all addresses within this subnet.
    pub fn addr_iter(&self) -> impl Iterator<Item = Ipv4Addr> {
        Ipv4NetIter {
            next: Some(self.first_addr().into()),
            last: self.last_addr().into(),
        }
    }

    /// Produce an iterator over all hosts within this subnet. For /31 and /32
    /// subnets, this is all addresses; for all larger subnets this excludes
    /// the first (network) and last (broadcast) addresses.
    pub fn host_iter(&self) -> impl Iterator<Item = Ipv4Addr> {
        Ipv4NetIter {
            next: Some(self.first_host().into()),
            last: self.last_host().into(),
        }
    }

    /// Returns `true` iff this subnet is wholly contained within `other`.
    pub fn is_subnet_of(&self, other: &Self) -> bool {
        other.first_addr() <= self.first_addr() && other.last_addr() >= self.last_addr()
    }

    /// Returns `true` iff `other` is wholly contained within this subnet.
    pub fn is_supernet_of(&self, other: &Self) -> bool {
        other.is_subnet_of(self)
    }

    /// Return `true` if the `other` shares any IP addresses with `self`
    /// (e.g., `self.is_subnet_of(other)`, or vice-versa).
    pub fn overlaps(&self, other: &Self) -> bool {
        let (parent, child) = if self.width <= other.width {
            (self, other)
        } else {
            (other, self)
        };

        child.is_subnet_of(parent)
    }
}

impl std::fmt::Display for Ipv4Net {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}/{}", &self.addr, self.width)
    }
}

impl std::str::FromStr for Ipv4Net {
    type Err = IpNetParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let Some((addr_str, prefix_str)) = s.split_once('/') else {
            return Err(IpNetParseError::NoPrefix);
        };

        let prefix = prefix_str.parse().map_err(IpNetParseError::InvalidPrefix)?;
        let addr = addr_str.parse().map_err(IpNetParseError::InvalidAddr)?;
        Ipv4Net::new(addr, prefix).map_err(IpNetParseError::PrefixValue)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Ipv4Net {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        String::deserialize(deserializer)?
            .parse()
            .map_err(<D::Error as serde::de::Error>::custom)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Ipv4Net {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&format!("{self}"))
    }
}

#[cfg(feature = "schemars")]
const IPV4_NET_REGEX: &str = concat!(
    r#"^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}"#,
    r#"([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"#,
    r#"/([0-9]|1[0-9]|2[0-9]|3[0-2])$"#,
);

#[cfg(feature = "schemars")]
impl schemars::JsonSchema for Ipv4Net {
    fn schema_name() -> String {
        "Ipv4Net".to_string()
    }

    fn json_schema(_: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        schemars::schema::SchemaObject {
            metadata: Some(Box::new(schemars::schema::Metadata {
                title: Some("An IPv4 subnet".to_string()),
                description: Some("An IPv4 subnet, including prefix and prefix length".to_string()),
                examples: vec!["192.168.1.0/24".into()],
                ..Default::default()
            })),
            instance_type: Some(schemars::schema::InstanceType::String.into()),
            string: Some(Box::new(schemars::schema::StringValidation {
                pattern: Some(IPV4_NET_REGEX.to_string()),
                ..Default::default()
            })),
            extensions: crate::schema_util::extension("Ipv4Net", "0.1.0"),
            ..Default::default()
        }
        .into()
    }
}

/// The highest value for an IPv6 subnet prefix
pub const IPV6_NET_WIDTH_MAX: u8 = 128;

/// IPv6 multicast scope values as defined in [RFC 4291] and [RFC 7346].
///
/// [RFC 4291]: https://tools.ietf.org/html/rfc4291
/// [RFC 7346]: https://tools.ietf.org/html/rfc7346
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum MulticastScopeV6 {
    /// Interface-local scope (0x1)
    InterfaceLocal = 0x1,
    /// Link-local scope (0x2)
    LinkLocal = 0x2,
    /// Admin-local scope (0x4) - administratively configured
    AdminLocal = 0x4,
    /// Site-local scope (0x5) - administratively configured
    SiteLocal = 0x5,
    /// Organization-local scope (0x8) - administratively configured
    OrganizationLocal = 0x8,
    /// Global scope (0xE)
    Global = 0xE,
}

impl MulticastScopeV6 {
    /// Returns `true` if this scope is administratively configured
    /// (scopes 4, 5, 8).
    pub const fn is_admin_scoped_multicast(&self) -> bool {
        matches!(
            self,
            MulticastScopeV6::AdminLocal
                | MulticastScopeV6::SiteLocal
                | MulticastScopeV6::OrganizationLocal
        )
    }

    /// Create a `MulticastScopeV6` from a raw scope value.
    /// Returns `None` if the scope value is not recognized.
    pub const fn from_u8(scope: u8) -> Option<Self> {
        match scope {
            0x1 => Some(MulticastScopeV6::InterfaceLocal),
            0x2 => Some(MulticastScopeV6::LinkLocal),
            0x4 => Some(MulticastScopeV6::AdminLocal),
            0x5 => Some(MulticastScopeV6::SiteLocal),
            0x8 => Some(MulticastScopeV6::OrganizationLocal),
            0xE => Some(MulticastScopeV6::Global),
            _ => None,
        }
    }
}

/// An IPv6 subnet
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Ipv6Net {
    addr: Ipv6Addr,
    width: u8,
}

impl Ipv6Net {
    /// Create an Ipv6Net with the given base address and prefix width.
    pub fn new(addr: Ipv6Addr, width: u8) -> Result<Self, IpNetPrefixError> {
        if width > IPV6_NET_WIDTH_MAX {
            Err(IpNetPrefixError(width))
        } else {
            Ok(Self { addr, width })
        }
    }

    /// Create an Ipv6Net with the given address and prefix width with no
    /// checks for the validity of the prefix length.
    pub const fn new_unchecked(addr: Ipv6Addr, width: u8) -> Self {
        Self { addr, width }
    }

    /// Create an Ipv6Net that contains *exclusively* the given address.
    pub const fn host_net(addr: Ipv6Addr) -> Self {
        Self {
            addr,
            width: IPV6_NET_WIDTH_MAX,
        }
    }

    /// Return the base address used to create this subnet.
    pub const fn addr(&self) -> Ipv6Addr {
        self.addr
    }

    /// Return the prefix width.
    pub const fn width(&self) -> u8 {
        self.width
    }

    pub(crate) fn mask(&self) -> u128 {
        u128::MAX
            .checked_shl((IPV6_NET_WIDTH_MAX - self.width) as u32)
            .unwrap_or(0)
    }

    /// Return the netmask address derived from prefix length.
    pub fn mask_addr(&self) -> Ipv6Addr {
        Ipv6Addr::from(self.mask())
    }

    /// Return true iff the subnet contains only the base address i.e. the
    /// size is exactly one address.
    pub const fn is_host_net(&self) -> bool {
        self.width == IPV6_NET_WIDTH_MAX
    }

    /// Return `true` iff the base address corresponds to the all-zeroes host
    /// ID in the subnet.
    pub fn is_network_address(&self) -> bool {
        self.addr == self.prefix()
    }

    /// Return `true` iff this subnet is in a multicast address range.
    pub const fn is_multicast(&self) -> bool {
        self.addr.is_multicast()
    }

    /// Return the IPv6 multicast scope if this subnet is a multicast address,
    /// or `None` otherwise. This extracts the scope field from the multicast
    /// address as defined in [RFC 4291] and [RFC 7346].
    ///
    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
    /// [RFC 7346]: https://tools.ietf.org/html/rfc7346
    pub const fn multicast_scope(&self) -> Option<MulticastScopeV6> {
        if !self.addr.is_multicast() {
            return None;
        }

        // Extract the scope field (bits 4-7 of the second byte)
        let segments = self.addr.segments();
        let scope = (segments[0] & 0x000F) as u8;

        MulticastScopeV6::from_u8(scope)
    }

    /// Return `true` iff this subnet is in an administratively scoped
    /// multicast address range with boundaries that are administratively
    /// configured.
    ///
    /// "Admin" is short for "administratively"; these scopes have boundaries
    /// configured by network administrators, unlike well-known scopes like
    /// link-local or global.
    ///
    /// For IPv6, this includes scopes 4, 5, and 8 (admin-local, site-local,
    /// organization-local) as defined in [RFC 7346] and [RFC 4291].
    ///
    /// [RFC 7346]: https://tools.ietf.org/html/rfc7346
    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
    pub const fn is_admin_scoped_multicast(&self) -> bool {
        match self.multicast_scope() {
            Some(scope) => scope.is_admin_scoped_multicast(),
            None => false,
        }
    }

    /// Return `true` iff this address is an admin-local multicast address
    /// (scope 4) as defined in [RFC 7346] and [RFC 4291].
    ///
    /// [RFC 7346]: https://tools.ietf.org/html/rfc7346
    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
    pub const fn is_admin_local_multicast(&self) -> bool {
        matches!(self.multicast_scope(), Some(MulticastScopeV6::AdminLocal))
    }

    /// Return `true` iff this address is a site-local multicast address
    /// (scope 5) as defined in [RFC 7346] and [RFC 4291].
    ///
    /// [RFC 7346]: https://tools.ietf.org/html/rfc7346
    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
    pub const fn is_site_local_multicast(&self) -> bool {
        matches!(self.multicast_scope(), Some(MulticastScopeV6::SiteLocal))
    }

    /// Return `true` iff this address is an organization-local multicast
    /// address (scope 8) as defined in [RFC 7346] and [RFC 4291].
    ///
    /// [RFC 7346]: https://tools.ietf.org/html/rfc7346
    /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
    pub const fn is_org_local_multicast(&self) -> bool {
        matches!(
            self.multicast_scope(),
            Some(MulticastScopeV6::OrganizationLocal)
        )
    }

    /// Return `true` iff this subnet is in a loopback address range.
    pub const fn is_loopback(&self) -> bool {
        self.addr.is_loopback()
    }

    /// Return the number of addresses contained within this subnet or None for
    /// a /0 subnet whose value would be one larger than can be represented in
    /// a `u128`.
    pub const fn size(&self) -> Option<u128> {
        1u128.checked_shl((IPV6_NET_WIDTH_MAX - self.width) as u32)
    }

    /// Return the prefix address (the base address with the mask applied).
    pub fn prefix(&self) -> Ipv6Addr {
        self.first_addr()
    }

    /// Return `true` if this subnetwork is in the IPv6 Unique Local Address
    /// range defined in [RFC 4193], e.g., `fd00:/8`.
    ///
    /// [RFC 4193]: https://tools.ietf.org/html/rfc4193
    pub const fn is_unique_local(&self) -> bool {
        self.addr.is_unique_local()
    }

    /// Return the first address within this subnet.
    pub fn first_addr(&self) -> Ipv6Addr {
        let addr: u128 = self.addr.into();
        Ipv6Addr::from(addr & self.mask())
    }

    /// The broadcast address for this subnet which is also the last address.
    pub fn last_addr(&self) -> Ipv6Addr {
        let addr: u128 = self.addr.into();
        Ipv6Addr::from(addr | !self.mask())
    }

    /// Return an interator over the addresses of this subnet.
    pub fn iter(&self) -> impl Iterator<Item = Ipv6Addr> {
        Ipv6NetIter {
            next: Some(self.first_addr().into()),
            last: self.last_addr().into(),
        }
    }

    /// Return `true` if the address is within the subnet.
    pub fn contains(&self, other: Ipv6Addr) -> bool {
        let mask = self.mask();
        let addr: u128 = self.addr.into();
        let other: u128 = other.into();

        (addr & mask) == (other & mask)
    }

    /// Return the nth address within this subnet or none if `n` is larger than
    /// the size of the subnet.
    pub fn nth(&self, n: u128) -> Option<Ipv6Addr> {
        let addr: u128 = self.addr.into();
        let nth = addr.checked_add(n)?;
        (nth <= self.last_addr().into()).then_some(nth.into())
    }

    /// Returns `true` iff this subnet is wholly contained within `other`.
    pub fn is_subnet_of(&self, other: &Self) -> bool {
        other.first_addr() <= self.first_addr() && other.last_addr() >= self.last_addr()
    }

    /// Returns `true` iff `other` is wholly contained within this subnet.
    pub fn is_supernet_of(&self, other: &Self) -> bool {
        other.is_subnet_of(self)
    }

    /// Return `true` if the `other` shares any IP addresses with `self`
    /// (e.g., `self.is_subnet_of(other)`, or vice-versa).
    pub fn overlaps(&self, other: &Self) -> bool {
        let (parent, child) = if self.width <= other.width {
            (self, other)
        } else {
            (other, self)
        };

        child.is_subnet_of(parent)
    }
}

impl std::fmt::Display for Ipv6Net {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}/{}", &self.addr, self.width)
    }
}

impl std::str::FromStr for Ipv6Net {
    type Err = IpNetParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let Some((addr_str, prefix_str)) = s.split_once('/') else {
            return Err(IpNetParseError::NoPrefix);
        };

        let prefix = prefix_str.parse().map_err(IpNetParseError::InvalidPrefix)?;
        let addr = addr_str.parse().map_err(IpNetParseError::InvalidAddr)?;
        Ipv6Net::new(addr, prefix).map_err(IpNetParseError::PrefixValue)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Ipv6Net {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        String::deserialize(deserializer)?
            .parse()
            .map_err(<D::Error as serde::de::Error>::custom)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Ipv6Net {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&format!("{self}"))
    }
}

#[cfg(feature = "schemars")]
const IPV6_NET_REGEX: &str = concat!(
    r#"^("#,
    r#"([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|"#,
    r#"([0-9a-fA-F]{1,4}:){1,7}:|"#,
    r#"([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|"#,
    r#"([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|"#,
    r#"([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|"#,
    r#"([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|"#,
    r#"([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|"#,
    r#"[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|"#,
    r#":((:[0-9a-fA-F]{1,4}){1,7}|:)|"#,
    r#"fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|"#,
    r#"::(ffff(:0{1,4}){0,1}:){0,1}"#,
    r#"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}"#,
    r#"(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|"#,
    r#"([0-9a-fA-F]{1,4}:){1,4}:"#,
    r#"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}"#,
    r#"(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"#,
    r#")\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8])$"#,
);

#[cfg(feature = "schemars")]
impl schemars::JsonSchema for Ipv6Net {
    fn schema_name() -> String {
        "Ipv6Net".to_string()
    }

    fn json_schema(_: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        schemars::schema::SchemaObject {
            metadata: Some(Box::new(schemars::schema::Metadata {
                title: Some("An IPv6 subnet".to_string()),
                description: Some("An IPv6 subnet, including prefix and subnet mask".to_string()),
                examples: vec!["fd12:3456::/64".into()],
                ..Default::default()
            })),
            instance_type: Some(schemars::schema::InstanceType::String.into()),
            string: Some(Box::new(schemars::schema::StringValidation {
                pattern: Some(IPV6_NET_REGEX.to_string()),
                ..Default::default()
            })),
            extensions: crate::schema_util::extension("Ipv6Net", "0.1.0"),
            ..Default::default()
        }
        .into()
    }
}

pub struct Ipv4NetIter {
    next: Option<u32>,
    last: u32,
}

impl Iterator for Ipv4NetIter {
    type Item = Ipv4Addr;

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.next?;
        if next == self.last {
            self.next = None;
        } else {
            self.next = Some(next + 1)
        }
        Some(next.into())
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        let next = self.next?;
        let nth = next.checked_add(n as u32)?;
        self.next = (nth <= self.last).then_some(nth);
        self.next()
    }
}

pub struct Ipv6NetIter {
    next: Option<u128>,
    last: u128,
}

impl Iterator for Ipv6NetIter {
    type Item = Ipv6Addr;

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.next?;
        if next == self.last {
            self.next = None;
        } else {
            self.next = Some(next + 1)
        }
        Some(next.into())
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        let next = self.next?;
        let nth = next.checked_add(n as u128)?;
        self.next = (nth <= self.last).then_some(nth);
        self.next()
    }
}

#[cfg(feature = "ipnetwork")]
mod ipnetwork_feature {
    use super::*;
    use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network};

    impl From<IpNetwork> for IpNet {
        fn from(value: IpNetwork) -> Self {
            match value {
                IpNetwork::V4(net) => Self::V4(net.into()),
                IpNetwork::V6(net) => Self::V6(net.into()),
            }
        }
    }

    impl From<IpNet> for IpNetwork {
        fn from(value: IpNet) -> Self {
            match value {
                IpNet::V4(net) => Self::V4(net.into()),
                IpNet::V6(net) => Self::V6(net.into()),
            }
        }
    }

    impl From<Ipv4Network> for Ipv4Net {
        fn from(value: Ipv4Network) -> Self {
            Self {
                addr: value.ip(),
                width: value.prefix(),
            }
        }
    }

    impl From<Ipv4Net> for Ipv4Network {
        fn from(value: Ipv4Net) -> Self {
            Self::new(value.addr, value.width).unwrap()
        }
    }

    impl From<Ipv6Network> for Ipv6Net {
        fn from(value: Ipv6Network) -> Self {
            Self {
                addr: value.ip(),
                width: value.prefix(),
            }
        }
    }

    impl From<Ipv6Net> for Ipv6Network {
        fn from(value: Ipv6Net) -> Self {
            Self::new(value.addr, value.width).unwrap()
        }
    }
}

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

    #[test]
    fn test_ipv6_regex() {
        let re = regress::Regex::new(IPV6_NET_REGEX).unwrap();
        for case in [
            "1:2:3:4:5:6:7:8",
            "1:a:2:b:3:c:4:d",
            "1::",
            "::1",
            "::",
            "1::3:4:5:6:7:8",
            "1:2::4:5:6:7:8",
            "1:2:3::5:6:7:8",
            "1:2:3:4::6:7:8",
            "1:2:3:4:5::7:8",
            "1:2:3:4:5:6::8",
            "1:2:3:4:5:6:7::",
            "2001::",
            "fd00::",
            "::100:1",
            "fd12:3456::",
        ] {
            for prefix in 0..=128 {
                let net = format!("{case}/{prefix}");
                assert!(
                    re.find(&net).is_some(),
                    "Expected to match IPv6 case: {}",
                    prefix,
                );
            }
        }
    }

    #[test]
    fn test_ipv4_net_operations() {
        let x: IpNet = "0.0.0.0/0".parse().unwrap();
        assert_eq!(x, IpNet::V4("0.0.0.0/0".parse().unwrap()));
    }

    #[test]
    fn test_ipnet_serde() {
        let net_str = "fd00:2::/32";
        let net: IpNet = net_str.parse().unwrap();
        let ser = serde_json::to_string(&net).unwrap();

        assert_eq!(format!(r#""{}""#, net_str), ser);
        let net_des = serde_json::from_str::<IpNet>(&ser).unwrap();
        assert_eq!(net, net_des);

        let net_str = "fd00:47::1/64";
        let net: IpNet = net_str.parse().unwrap();
        let ser = serde_json::to_string(&net).unwrap();

        assert_eq!(format!(r#""{}""#, net_str), ser);
        let net_des = serde_json::from_str::<IpNet>(&ser).unwrap();
        assert_eq!(net, net_des);

        let net_str = "192.168.1.1/16";
        let net: IpNet = net_str.parse().unwrap();
        let ser = serde_json::to_string(&net).unwrap();

        assert_eq!(format!(r#""{}""#, net_str), ser);
        let net_des = serde_json::from_str::<IpNet>(&ser).unwrap();
        assert_eq!(net, net_des);

        let net_str = "0.0.0.0/0";
        let net: IpNet = net_str.parse().unwrap();
        let ser = serde_json::to_string(&net).unwrap();

        assert_eq!(format!(r#""{}""#, net_str), ser);
        let net_des = serde_json::from_str::<IpNet>(&ser).unwrap();
        assert_eq!(net, net_des);
    }

    #[test]
    fn test_ipnet_size() {
        let net = Ipv4Net::host_net("1.2.3.4".parse().unwrap());
        assert_eq!(net.size(), Some(1));
        assert_eq!(net.width(), 32);
        assert_eq!(net.mask(), 0xffff_ffff);
        assert_eq!(net.mask_addr(), Ipv4Addr::new(0xff, 0xff, 0xff, 0xff));

        let net = Ipv4Net::new("1.2.3.4".parse().unwrap(), 24).unwrap();
        assert_eq!(net.size(), Some(256));
        assert_eq!(net.width(), 24);
        assert_eq!(net.mask(), 0xffff_ff00);
        assert_eq!(net.mask_addr(), Ipv4Addr::new(0xff, 0xff, 0xff, 0));

        let net = Ipv4Net::new("0.0.0.0".parse().unwrap(), 0).unwrap();
        assert_eq!(net.size(), None);
        assert_eq!(net.width(), 0);
        assert_eq!(net.mask(), 0);
        assert_eq!(net.mask_addr(), Ipv4Addr::new(0, 0, 0, 0));

        let net = Ipv6Net::host_net("fd00:47::1".parse().unwrap());
        assert_eq!(net.size(), Some(1));
        assert_eq!(net.width(), 128);
        assert_eq!(net.mask(), 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff);
        assert_eq!(
            net.mask_addr(),
            Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)
        );

        let net = Ipv6Net::new("fd00:47::1".parse().unwrap(), 56).unwrap();
        assert_eq!(net.size(), Some(0x0000_0000_0000_0100_0000_0000_0000_0000));
        assert_eq!(net.width(), 56);
        assert_eq!(net.mask(), 0xffff_ffff_ffff_ff00_0000_0000_0000_0000);
        assert_eq!(
            net.mask_addr(),
            Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0xff00, 0, 0, 0, 0)
        );
    }

    #[test]
    fn test_iter() {
        let ipnet = Ipv4Net::new(Ipv4Addr::new(0, 0, 0, 0), 0).unwrap();

        let actual = ipnet.addr_iter().take(5).collect::<Vec<_>>();
        let expected = (0..5).map(Ipv4Addr::from).collect::<Vec<_>>();
        assert_eq!(actual, expected);

        let actual = ipnet.addr_iter().skip(5).take(10).collect::<Vec<_>>();
        let expected = (5..15).map(Ipv4Addr::from).collect::<Vec<_>>();
        assert_eq!(actual, expected);

        let ipnet = Ipv6Net::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0), 0).unwrap();

        let actual = ipnet.iter().take(5).collect::<Vec<_>>();
        let expected = (0..5).map(Ipv6Addr::from).collect::<Vec<_>>();
        assert_eq!(actual, expected);

        let actual = ipnet.iter().skip(5).take(10).collect::<Vec<_>>();
        let expected = (5..15).map(Ipv6Addr::from).collect::<Vec<_>>();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_contains() {
        let default_v4: IpNet = "0.0.0.0/0".parse().unwrap();
        let private_v4: IpNet = "10.0.0.0/8".parse().unwrap();
        let privater_v4_c0: IpNet = "10.0.0.0/9".parse().unwrap();
        let privater_v4_c1: IpNet = "10.128.0.0/9".parse().unwrap();

        assert!(private_v4.is_subnet_of(&default_v4));
        assert!(privater_v4_c0.is_subnet_of(&default_v4));
        assert!(privater_v4_c0.is_subnet_of(&private_v4));
        assert!(privater_v4_c1.is_subnet_of(&default_v4));
        assert!(privater_v4_c1.is_subnet_of(&private_v4));

        assert!(private_v4.is_supernet_of(&privater_v4_c0));
        assert!(private_v4.is_supernet_of(&privater_v4_c1));

        assert!(!privater_v4_c0.overlaps(&privater_v4_c1));
        assert!(!privater_v4_c1.overlaps(&privater_v4_c0));
        assert!(privater_v4_c0.overlaps(&privater_v4_c0));
        assert!(privater_v4_c0.overlaps(&private_v4));
        assert!(private_v4.overlaps(&privater_v4_c0));

        let child_ip: IpNet = "10.128.20.20/16".parse().unwrap();
        assert!(child_ip.is_subnet_of(&privater_v4_c1));
        assert!(!child_ip.is_subnet_of(&privater_v4_c0));
    }

    #[test]
    fn test_is_network_addr() {
        let v4_net: IpNet = "127.0.0.0/8".parse().unwrap();
        let v4_host: IpNet = "127.0.0.1/8".parse().unwrap();
        let v6_net: IpNet = "fd00:1234:5678::/48".parse().unwrap();
        let v6_host: IpNet = "fd00:1234:5678::7777/48".parse().unwrap();

        assert!(v4_net.is_network_address());
        assert!(!v4_host.is_network_address());
        assert!(v6_net.is_network_address());
        assert!(!v6_host.is_network_address());

        // We don't return a `.network()` for a /31 or /32, but the host bits
        // are zero in these addresses (i.e., they're in a canonical form).
        let two_addr: IpNet = "10.7.7.64/31".parse().unwrap();
        let one_addr: IpNet = "10.7.7.64/32".parse().unwrap();
        assert!(two_addr.is_network_address());
        assert!(one_addr.is_network_address());

        // The IpNet as used in a default route should be considered valid in
        // this form.
        let unspec: IpNet = "0.0.0.0/0".parse().unwrap();
        assert!(unspec.is_network_address());
    }

    #[test]
    fn test_is_multicast_with_scopes() {
        // IPv4 multicast tests (224.0.0.0/4 is the IPv4 multicast range)
        let v4_mcast: IpNet = "224.0.0.1/32".parse().unwrap();
        let v4_not_mcast: IpNet = "192.168.1.1/24".parse().unwrap();

        assert!(v4_mcast.is_multicast());
        assert!(!v4_not_mcast.is_multicast());

        // IPv6 multicast tests (ff00::/8 is the IPv6 multicast range)
        let v6_mcast: IpNet = "ff02::1/128".parse().unwrap();
        let v6_not_mcast: IpNet = "2001:db8::1/64".parse().unwrap();

        assert!(v6_mcast.is_multicast());
        assert!(!v6_not_mcast.is_multicast());

        // Test for site-local multicast (scope 5)
        let v6_site_local_mcast: IpNet = "ff05::1/128".parse().unwrap();
        // Test for organization-local multicast (scope 8)
        let v6_org_local_mcast: IpNet = "ff08::1/128".parse().unwrap();
        // Test for admin-local multicast (scope 4)
        let v6_admin_local_mcast: IpNet = "ff04::1/128".parse().unwrap();
        // Test for a multicast address that is not admin scoped (link-local, scope 2)
        let v6_link_local_mcast: IpNet = "ff02::1/128".parse().unwrap();

        // Test admin scoped multicast (covers scopes 4, 5, 8 for IPv6, 239/8 for IPv4)
        assert!(v6_admin_local_mcast.is_admin_scoped_multicast());
        assert!(v6_site_local_mcast.is_admin_scoped_multicast());
        assert!(v6_org_local_mcast.is_admin_scoped_multicast());
        assert!(!v6_link_local_mcast.is_admin_scoped_multicast()); // scope 2 is not administratively configured
        assert!(!v6_not_mcast.is_admin_scoped_multicast());

        // Test IPv4 admin scoped (239.0.0.0/8)
        let v4_admin_scoped: IpNet = "239.0.0.1/32".parse().unwrap();
        let v4_admin_scoped_range: IpNet = "239.192.0.0/16".parse().unwrap();
        assert!(v4_admin_scoped.is_admin_scoped_multicast());
        assert!(v4_admin_scoped_range.is_admin_scoped_multicast());
        assert!(!v4_mcast.is_admin_scoped_multicast());

        // Test IPv6 admin-local multicast (scope 4) - IPv4 does not have this
        assert!(!v6_site_local_mcast.is_admin_local_multicast());
        assert!(!v6_org_local_mcast.is_admin_local_multicast());
        assert!(v6_admin_local_mcast.is_admin_local_multicast());
        assert!(!v6_link_local_mcast.is_admin_local_multicast());
        assert!(!v6_not_mcast.is_admin_local_multicast());
        assert!(!v4_mcast.is_admin_local_multicast()); // IPv4 does not have admin-local
        assert!(!v4_admin_scoped.is_admin_local_multicast()); // IPv4 does not have admin-local

        // Test IPv4 local multicast (239.255.0.0/16) - IPv6 does not have this
        let v4_local_mcast: IpNet = "239.255.0.1/32".parse().unwrap();
        let v4_local_mcast_range: IpNet = "239.255.128.0/24".parse().unwrap();
        let v4_not_local: IpNet = "239.254.255.255/32".parse().unwrap();
        assert!(v4_local_mcast.is_local_multicast());
        assert!(v4_local_mcast_range.is_local_multicast());
        assert!(!v4_not_local.is_local_multicast());
        assert!(!v4_mcast.is_local_multicast()); // 224.0.0.1 is not in 239.255/16
        assert!(!v6_admin_local_mcast.is_local_multicast()); // IPv6 does not have local scope

        // Test site-local multicast (scope 5)
        assert!(v6_site_local_mcast.is_site_local_multicast());
        assert!(!v6_org_local_mcast.is_site_local_multicast());
        assert!(!v6_admin_local_mcast.is_site_local_multicast());
        assert!(!v6_link_local_mcast.is_site_local_multicast());
        assert!(!v6_not_mcast.is_site_local_multicast());
        assert!(!v4_mcast.is_site_local_multicast());

        // Test organization-local multicast
        // IPv6 (scope 8)
        assert!(!v6_site_local_mcast.is_org_local_multicast());
        assert!(v6_org_local_mcast.is_org_local_multicast());
        assert!(!v6_admin_local_mcast.is_org_local_multicast());
        assert!(!v6_link_local_mcast.is_org_local_multicast());
        assert!(!v6_not_mcast.is_org_local_multicast());

        // IPv4 (239.192.0.0/14)
        let v4_org_local_mcast: IpNet = "239.192.0.1/32".parse().unwrap();
        let v4_org_local_mcast_end: IpNet = "239.195.255.255/32".parse().unwrap();
        let v4_not_org_local: IpNet = "239.196.0.0/32".parse().unwrap();
        assert!(v4_org_local_mcast.is_org_local_multicast());
        assert!(v4_org_local_mcast_end.is_org_local_multicast());
        assert!(!v4_not_org_local.is_org_local_multicast());
        assert!(!v4_mcast.is_org_local_multicast()); // 224.0.0.1 is not in 239.192/14
    }

    #[test]
    fn test_ipv6_multicast_scope() {
        use MulticastScopeV6::*;

        let link_local: Ipv6Net = "ff02::1/128".parse().unwrap();
        let admin_local: Ipv6Net = "ff04::1/128".parse().unwrap();
        let site_local: Ipv6Net = "ff05::1/128".parse().unwrap();
        let org_local: Ipv6Net = "ff08::1/128".parse().unwrap();
        let global: Ipv6Net = "ff0e::1/128".parse().unwrap();
        let not_mcast: Ipv6Net = "2001:db8::1/64".parse().unwrap();

        assert_eq!(link_local.multicast_scope(), Some(LinkLocal));
        assert_eq!(admin_local.multicast_scope(), Some(AdminLocal));
        assert_eq!(site_local.multicast_scope(), Some(SiteLocal));
        assert_eq!(org_local.multicast_scope(), Some(OrganizationLocal));
        assert_eq!(global.multicast_scope(), Some(Global));
        assert_eq!(not_mcast.multicast_scope(), None);

        // Test is_admin_scoped_multicast
        assert!(!LinkLocal.is_admin_scoped_multicast());
        assert!(AdminLocal.is_admin_scoped_multicast());
        assert!(SiteLocal.is_admin_scoped_multicast());
        assert!(OrganizationLocal.is_admin_scoped_multicast());
        assert!(!Global.is_admin_scoped_multicast());
    }
}