cidr-radix 11.2.0

Zero-dependency, zero-allocation IPv4/IPv6 CIDR parsing, bitmask matching, canonicalization, and radix-indexed IpCidrSet lookup.
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
use super::*;

/// Core operations for `Ipv6Cidr`.
impl Ipv6Cidr {
    /// Constructs a canonical `Ipv6Cidr` by masking host bits according to `prefix_len`.
    ///
    /// # Arguments
    ///
    /// - `Ipv6Addr` - The IPv6 address.
    /// - `u8` - The CIDR prefix length (`0..=128`).
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The canonical CIDR block or an error if `prefix_len > 128`.
    #[inline(always)]
    pub fn new(addr: Ipv6Addr, prefix_len: u8) -> Result<Self, IpCidrError> {
        if prefix_len > IPV6_MAX_PREFIX_LEN {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        let mask: u128 = Self::prefix_to_mask(prefix_len);
        let network: u128 = u128::from(addr) & mask;
        Ok(Self {
            network,
            mask,
            prefix_len,
        })
    }

    /// Constructs an `Ipv6Cidr`, rejecting addresses with non-zero host bits.
    ///
    /// # Arguments
    ///
    /// - `Ipv6Addr` - The IPv6 network address.
    /// - `u8` - The CIDR prefix length (`0..=128`).
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The CIDR block or an error on invalid prefix or host bits.
    #[inline(always)]
    pub fn new_strict(addr: Ipv6Addr, prefix_len: u8) -> Result<Self, IpCidrError> {
        if prefix_len > IPV6_MAX_PREFIX_LEN {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        let mask: u128 = Self::prefix_to_mask(prefix_len);
        let raw: u128 = u128::from(addr);
        let network: u128 = raw & mask;
        if raw != network {
            return Err(IpCidrError::NonCanonicalNetwork);
        }
        Ok(Self {
            network,
            mask,
            prefix_len,
        })
    }

    /// Creates a `/128` host CIDR block for the given IPv6 address.
    ///
    /// # Arguments
    ///
    /// - `Ipv6Addr` - The single host IPv6 address.
    #[inline(always)]
    pub fn from_host(addr: Ipv6Addr) -> Self {
        Self {
            network: u128::from(addr),
            mask: u128::MAX,
            prefix_len: IPV6_MAX_PREFIX_LEN,
        }
    }

    /// Creates the `::/0` wildcard IPv6 CIDR block matching all IPv6 addresses.
    #[inline(always)]
    pub fn any() -> Self {
        Self {
            network: 0,
            mask: 0,
            prefix_len: 0,
        }
    }

    /// Parses an IPv6 CIDR string (`addr/prefix`) with zero heap allocations and canonicalizes host bits.
    ///
    /// # Arguments
    ///
    /// - `&str` - The IPv6 CIDR string to parse.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed canonical `Ipv6Cidr` or a parse error.
    #[inline(always)]
    pub fn parse(input: &str) -> Result<Self, IpCidrError> {
        Self::parse_inner(input, true, false)
    }

    /// Parses an IPv6 CIDR string (`addr/prefix`), rejecting non-zero host bits.
    ///
    /// # Arguments
    ///
    /// - `&str` - The IPv6 CIDR string to parse strictly.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed canonical `Ipv6Cidr` or an error.
    #[inline(always)]
    pub fn parse_strict(input: &str) -> Result<Self, IpCidrError> {
        Self::parse_inner(input, true, true)
    }

    /// Parses either an IPv6 CIDR (`addr/prefix`) or a bare IPv6 host address (`addr` as `/128`).
    ///
    /// # Arguments
    ///
    /// - `&str` - The IPv6 CIDR or bare IPv6 address string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed canonical `Ipv6Cidr` or an error.
    #[inline(always)]
    pub fn parse_or_host(input: &str) -> Result<Self, IpCidrError> {
        Self::parse_inner(input, false, false)
    }

    /// Returns the raw host-order `u128` network address.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `u128` - The canonical masked network address as `u128`.
    #[inline(always)]
    pub fn get_network_u128(&self) -> u128 {
        self.network
    }

    /// Returns the precomputed host-order `u128` bitmask.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `u128` - The network bitmask as `u128`.
    #[inline(always)]
    pub fn get_mask_u128(&self) -> u128 {
        self.mask
    }

    /// Returns the CIDR prefix length (`0..=128`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `u8` - The prefix length in bits.
    #[inline(always)]
    pub fn get_prefix_len(&self) -> u8 {
        self.prefix_len
    }

    /// Returns the canonical network IPv6 address.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `Ipv6Addr` - The network address.
    #[inline(always)]
    pub fn network(&self) -> Ipv6Addr {
        Ipv6Addr::from(self.get_network_u128())
    }

    /// Returns the last host-order `u128` address covered by this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `u128` - The inclusive upper bound address as `u128`.
    #[inline(always)]
    pub fn get_last_u128(&self) -> u128 {
        self.get_network_u128() | !self.get_mask_u128()
    }

    /// Returns the first IPv6 address in this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `Ipv6Addr` - The first address (equal to `network()`).
    #[inline(always)]
    pub fn first_address(&self) -> Ipv6Addr {
        self.network()
    }

    /// Returns the last IPv6 address in this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `Ipv6Addr` - The inclusive last IPv6 address.
    #[inline(always)]
    pub fn last_address(&self) -> Ipv6Addr {
        Ipv6Addr::from(self.get_last_u128())
    }

    /// Returns the subnet mask as an `Ipv6Addr`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `Ipv6Addr` - The subnet mask address.
    #[inline(always)]
    pub fn netmask(&self) -> Ipv6Addr {
        Ipv6Addr::from(self.get_mask_u128())
    }

    /// Returns whether this block represents a single `/128` host.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `prefix_len == 128`.
    #[inline(always)]
    pub fn is_host(&self) -> bool {
        self.get_prefix_len() == IPV6_MAX_PREFIX_LEN
    }

    /// Returns whether this block is the `/0` wildcard matching all IPv6 addresses.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `prefix_len == 0`.
    #[inline(always)]
    pub fn is_any(&self) -> bool {
        self.get_prefix_len() == 0
    }

    /// Checks whether the given IPv6 address is contained in this CIDR block in constant time.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    /// - `Ipv6Addr` - The address to test.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if `addr` belongs to this CIDR block.
    #[inline(always)]
    pub fn contains(&self, addr: Ipv6Addr) -> bool {
        self.contains_u128(u128::from(addr))
    }

    /// Checks whether a host-order `u128` IPv6 address is contained in this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    /// - `u128` - The host-order IPv6 address to test.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if `addr` belongs to this CIDR block.
    #[inline(always)]
    pub fn contains_u128(&self, addr: u128) -> bool {
        (addr & self.get_mask_u128()) == self.get_network_u128()
    }

    /// Checks whether this CIDR block completely contains another IPv6 CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The outer CIDR block.
    /// - `Self` - The candidate subnet block.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if every address in `other` is in `self`.
    #[inline(always)]
    pub fn contains_cidr(&self, other: Self) -> bool {
        self.get_prefix_len() <= other.get_prefix_len()
            && self.contains_u128(other.get_network_u128())
    }

    /// Checks whether this CIDR block shares at least one address with another IPv6 CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The first CIDR block.
    /// - `Self` - The second CIDR block.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the two CIDR blocks overlap.
    #[inline(always)]
    pub fn overlaps(&self, other: Self) -> bool {
        self.contains_u128(other.get_network_u128()) || other.contains_u128(self.get_network_u128())
    }

    /// Computes the host-order 128-bit mask for a validated IPv6 prefix length.
    ///
    /// # Arguments
    ///
    /// - `u8` - The prefix length (`0..=128`).
    ///
    /// # Returns
    ///
    /// - `u128` - The corresponding 128-bit mask.
    #[inline(always)]
    pub(crate) fn prefix_to_mask(prefix_len: u8) -> u128 {
        if prefix_len == 0 {
            0
        } else {
            u128::MAX << (IPV6_MAX_PREFIX_LEN - prefix_len)
        }
    }

    /// Internal single-pass zero-allocation IPv6 CIDR parser.
    ///
    /// # Arguments
    ///
    /// - `&str` - Input string to parse.
    /// - `bool` - Whether a `/prefix` suffix is required.
    /// - `bool` - Whether non-zero host bits should be rejected.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed `Ipv6Cidr` or an error.
    #[inline(always)]
    pub(crate) fn parse_inner(
        input: &str,
        require_slash: bool,
        strict_canonical: bool,
    ) -> Result<Self, IpCidrError> {
        let bytes: &[u8] = input.as_bytes();
        let len: usize = bytes.len();
        if len == 0 {
            return Err(IpCidrError::EmptyInput);
        }
        let mut groups: [u16; IPV6_GROUP_COUNT] = [0u16; IPV6_GROUP_COUNT];
        let mut count: usize = 0;
        let mut compress_pos: usize = IPV6_NO_COMPRESS;
        let mut idx: usize = 0;
        if bytes[0] == IPV6_ASCII_COLON {
            if len < 2 || bytes[1] != IPV6_ASCII_COLON {
                return Err(IpCidrError::InvalidIpAddress);
            }
            compress_pos = 0;
            idx = 2;
            if idx < len && bytes[idx] == IPV6_ASCII_COLON {
                return Err(IpCidrError::InvalidIpAddress);
            }
        }
        while idx < len && bytes[idx] != IPV6_ASCII_SLASH {
            if count >= IPV6_GROUP_COUNT {
                return Err(IpCidrError::InvalidIpAddress);
            }
            let group_start: usize = idx;
            let first_nib: u8 = IPV6_HEX_LUT[bytes[idx] as usize];
            if first_nib > IPV6_MAX_HEX_VALUE {
                return Err(IpCidrError::InvalidIpAddress);
            }
            let mut val: u16 = first_nib as u16;
            idx += 1;
            let mut digits: usize = 1;
            while idx < len {
                let nib: u8 = IPV6_HEX_LUT[bytes[idx] as usize];
                if nib > IPV6_MAX_HEX_VALUE {
                    break;
                }
                digits += 1;
                if digits > IPV6_MAX_GROUP_DIGITS {
                    return Err(IpCidrError::InvalidIpAddress);
                }
                val = (val << 4) | (nib as u16);
                idx += 1;
            }
            if idx == len || bytes[idx] == IPV6_ASCII_SLASH {
                groups[count] = val;
                count += 1;
                break;
            }
            let delim: u8 = bytes[idx];
            if delim == IPV6_ASCII_COLON {
                groups[count] = val;
                count += 1;
                idx += 1;
                if idx == len || bytes[idx] == IPV6_ASCII_SLASH {
                    return Err(IpCidrError::InvalidIpAddress);
                }
                if bytes[idx] == IPV6_ASCII_COLON {
                    if compress_pos <= IPV6_GROUP_COUNT {
                        return Err(IpCidrError::InvalidIpAddress);
                    }
                    compress_pos = count;
                    idx += 1;
                    if idx == len || bytes[idx] == IPV6_ASCII_SLASH {
                        break;
                    }
                    if bytes[idx] == IPV6_ASCII_COLON {
                        return Err(IpCidrError::InvalidIpAddress);
                    }
                }
            } else if delim == IPV6_ASCII_DOT {
                if count > IPV6_MAX_EMBEDDED_V4_GROUPS {
                    return Err(IpCidrError::InvalidIpAddress);
                }
                let mut v4_idx: usize = group_start;
                let v4: u32 = Ipv4Cidr::parse_addr_u32(bytes, &mut v4_idx)?;
                idx = v4_idx;
                if idx < len && bytes[idx] != IPV6_ASCII_SLASH {
                    return Err(IpCidrError::InvalidIpAddress);
                }
                groups[count] = (v4 >> 16) as u16;
                groups[count + 1] = (v4 & 0xFFFF) as u16;
                count += 2;
                break;
            } else {
                return Err(IpCidrError::InvalidIpAddress);
            }
        }
        if compress_pos <= IPV6_GROUP_COUNT {
            if count >= IPV6_GROUP_COUNT {
                return Err(IpCidrError::InvalidIpAddress);
            }
            let zero_groups: usize = IPV6_GROUP_COUNT - count;
            let mut i: usize = count;
            while i > compress_pos {
                i -= 1;
                groups[i + zero_groups] = groups[i];
                groups[i] = 0;
            }
        } else if count != IPV6_GROUP_COUNT {
            return Err(IpCidrError::InvalidIpAddress);
        }
        let hi: u64 = ((groups[0] as u64) << 48)
            | ((groups[1] as u64) << 32)
            | ((groups[2] as u64) << 16)
            | (groups[3] as u64);
        let lo: u64 = ((groups[4] as u64) << 48)
            | ((groups[5] as u64) << 32)
            | ((groups[6] as u64) << 16)
            | (groups[7] as u64);
        let raw: u128 = ((hi as u128) << 64) | (lo as u128);
        let prefix_len: u8 = if idx == len {
            if require_slash {
                return Err(IpCidrError::InvalidSyntax);
            }
            IPV6_MAX_PREFIX_LEN
        } else {
            Self::parse_prefix_bytes(&bytes[idx + 1..])?
        };
        let mask: u128 = Self::prefix_to_mask(prefix_len);
        let network: u128 = raw & mask;
        if strict_canonical && raw != network {
            return Err(IpCidrError::NonCanonicalNetwork);
        }
        Ok(Self {
            network,
            mask,
            prefix_len,
        })
    }

    /// Parses an IPv6 prefix length (`0..=128`) from ASCII bytes without leading zeros.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - ASCII prefix bytes following `/`.
    ///
    /// # Returns
    ///
    /// - `Result<u8, IpCidrError>` - The validated prefix length or `InvalidPrefixLength`.
    #[inline(always)]
    pub(crate) fn parse_prefix_bytes(bytes: &[u8]) -> Result<u8, IpCidrError> {
        let len: usize = bytes.len();
        if len == 0 || len > 3 {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        let first: u8 = bytes[0].wrapping_sub(IPV6_ASCII_ZERO);
        if first > IPV6_MAX_DECIMAL_DIGIT {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        if len == 1 {
            return Ok(first);
        }
        if first == 0 {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        let mut value: u16 = first as u16;
        let mut idx: usize = 1;
        while idx < len {
            let d: u8 = bytes[idx].wrapping_sub(IPV6_ASCII_ZERO);
            if d > IPV6_MAX_DECIMAL_DIGIT {
                return Err(IpCidrError::InvalidPrefixLength);
            }
            value = value * 10 + (d as u16);
            idx += 1;
        }
        if value > IPV6_MAX_PREFIX_LEN as u16 {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        Ok(value as u8)
    }
}

/// Parses an `Ipv6Cidr` from its standard string representation (`addr/prefix`).
impl FromStr for Ipv6Cidr {
    type Err = IpCidrError;

    /// Parses a canonical `Ipv6Cidr` from `s`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Input CIDR string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, Self::Err>` - Parsed `Ipv6Cidr` or parse error.
    #[inline(always)]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

/// Formats an `Ipv6Cidr` in canonical RFC 5952 `addr/prefix` notation.
impl fmt::Display for Ipv6Cidr {
    /// Writes the canonical IPv6 CIDR notation to the formatter.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block to format.
    /// - `&mut fmt::Formatter<'_>` - The target formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Result of the formatting operation.
    #[inline(always)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", Ipv6Addr::from(self.network), self.prefix_len)
    }
}