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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
use super::*;

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

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

    /// Creates a `/32` host CIDR block for the given IPv4 address.
    ///
    /// # Arguments
    ///
    /// - `Ipv4Addr` - The single host IPv4 address.
    #[inline(always)]
    pub fn from_host(addr: Ipv4Addr) -> Self {
        Self {
            network: u32::from(addr),
            mask: u32::MAX,
            prefix_len: IPV4_MAX_PREFIX_LEN,
        }
    }

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

    /// Parses an IPv4 CIDR string (`a.b.c.d/p`) with zero heap allocations and canonicalizes host bits.
    ///
    /// # Arguments
    ///
    /// - `&str` - The IPv4 CIDR string to parse.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed canonical `Ipv4Cidr` or a parse error.
    #[inline(always)]
    pub fn parse(input: &str) -> Result<Self, IpCidrError> {
        Self::parse_bytes(input.as_bytes(), true, false)
    }

    /// Parses an IPv4 CIDR string (`a.b.c.d/p`), rejecting any non-zero host bits.
    ///
    /// # Arguments
    ///
    /// - `&str` - The IPv4 CIDR string to parse strictly.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed canonical `Ipv4Cidr` or an error.
    #[inline(always)]
    pub fn parse_strict(input: &str) -> Result<Self, IpCidrError> {
        Self::parse_bytes(input.as_bytes(), true, true)
    }

    /// Parses either an IPv4 CIDR (`a.b.c.d/p`) or a bare IPv4 host address (`a.b.c.d` as `/32`).
    ///
    /// # Arguments
    ///
    /// - `&str` - The IPv4 CIDR or bare IPv4 address string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed canonical `Ipv4Cidr` or an error.
    #[inline(always)]
    pub fn parse_or_host(input: &str) -> Result<Self, IpCidrError> {
        Self::parse_bytes(input.as_bytes(), false, false)
    }

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

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

    /// Returns the CIDR prefix length (`0..=32`).
    ///
    /// # 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 IPv4 address.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `Ipv4Addr` - The network address.
    #[inline(always)]
    pub fn network(&self) -> Ipv4Addr {
        Ipv4Addr::from(self.get_network_u32())
    }

    /// Returns the broadcast (last) IPv4 address in this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `Ipv4Addr` - The broadcast address.
    #[inline(always)]
    pub fn broadcast(&self) -> Ipv4Addr {
        Ipv4Addr::from(self.get_last_u32())
    }

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

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

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

    /// Returns the last IPv4 address in this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `Ipv4Addr` - The last address (equal to `broadcast()`).
    #[inline(always)]
    pub fn last_address(&self) -> Ipv4Addr {
        self.broadcast()
    }

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

    /// Returns whether this block is the `/0` wildcard matching all IPv4 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 IPv4 address is contained in this CIDR block in constant time.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    /// - `Ipv4Addr` - The address to test.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if `addr` belongs to this CIDR block.
    #[inline(always)]
    pub fn contains(&self, addr: Ipv4Addr) -> bool {
        self.contains_u32(u32::from(addr))
    }

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

    /// Checks whether this CIDR block completely contains another IPv4 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_u32(other.get_network_u32())
    }

    /// Checks whether this CIDR block shares at least one address with another IPv4 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_u32(other.get_network_u32()) || other.contains_u32(self.get_network_u32())
    }

    /// Computes the host-order bitmask for a validated IPv4 prefix length.
    ///
    /// # Arguments
    ///
    /// - `u8` - The prefix length (`0..=32`).
    ///
    /// # Returns
    ///
    /// - `u32` - The corresponding bitmask.
    #[inline(always)]
    pub(crate) fn prefix_to_mask(prefix_len: u8) -> u32 {
        ((u32::MAX as u64) << (IPV4_MAX_PREFIX_LEN - prefix_len)) as u32
    }

    /// Parses one decimal IPv4 octet (`0..=255`) without leading zeros starting at `*idx`.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Input ASCII bytes.
    /// - `&mut usize` - Cursor advanced past the parsed octet.
    ///
    /// # Returns
    ///
    /// - `Result<u32, IpCidrError>` - Parsed octet value in `0..=255`.
    #[inline(always)]
    fn parse_octet(bytes: &[u8], idx: &mut usize) -> Result<u32, IpCidrError> {
        let len: usize = bytes.len();
        let mut i: usize = *idx;
        if i >= len {
            return Err(IpCidrError::InvalidIpAddress);
        }
        let d0: u8 = bytes[i].wrapping_sub(ASCII_ZERO);
        if d0 > MAX_DECIMAL_DIGIT {
            return Err(IpCidrError::InvalidIpAddress);
        }
        i += 1;
        let mut val: u32 = d0 as u32;
        if i < len {
            let d1: u8 = bytes[i].wrapping_sub(ASCII_ZERO);
            if d1 <= MAX_DECIMAL_DIGIT {
                if d0 == 0 {
                    return Err(IpCidrError::InvalidIpAddress);
                }
                val = val * DECIMAL_BASE + (d1 as u32);
                i += 1;
                if i < len {
                    let d2: u8 = bytes[i].wrapping_sub(ASCII_ZERO);
                    if d2 <= MAX_DECIMAL_DIGIT {
                        val = val * DECIMAL_BASE + (d2 as u32);
                        if val > IPV4_MAX_OCTET {
                            return Err(IpCidrError::InvalidIpAddress);
                        }
                        i += 1;
                    }
                }
            }
        }
        *idx = i;
        Ok(val)
    }

    /// Parses four dotted-decimal IPv4 octets starting at `*idx`, returning host-order `u32`.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Input ASCII bytes.
    /// - `&mut usize` - Cursor advanced past the fourth octet.
    ///
    /// # Returns
    ///
    /// - `Result<u32, IpCidrError>` - Parsed host-order IPv4 address.
    #[inline(always)]
    pub(crate) fn parse_addr_u32(bytes: &[u8], idx: &mut usize) -> Result<u32, IpCidrError> {
        let len: usize = bytes.len();
        let o0: u32 = Self::parse_octet(bytes, idx)?;
        if *idx >= len || bytes[*idx] != ASCII_DOT {
            return Err(IpCidrError::InvalidIpAddress);
        }
        *idx += 1;
        let o1: u32 = Self::parse_octet(bytes, idx)?;
        if *idx >= len || bytes[*idx] != ASCII_DOT {
            return Err(IpCidrError::InvalidIpAddress);
        }
        *idx += 1;
        let o2: u32 = Self::parse_octet(bytes, idx)?;
        if *idx >= len || bytes[*idx] != ASCII_DOT {
            return Err(IpCidrError::InvalidIpAddress);
        }
        *idx += 1;
        let o3: u32 = Self::parse_octet(bytes, idx)?;
        Ok((o0 << 24) | (o1 << 16) | (o2 << 8) | o3)
    }

    /// Single-pass zero-allocation byte parser for IPv4 CIDR strings.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Input ASCII bytes.
    /// - `bool` - Whether a `/prefix` suffix is required.
    /// - `bool` - Whether non-zero host bits should be rejected.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed `Ipv4Cidr` or a parse error.
    #[inline(always)]
    pub(crate) fn parse_bytes(
        bytes: &[u8],
        require_slash: bool,
        strict_canonical: bool,
    ) -> Result<Self, IpCidrError> {
        if bytes.is_empty() {
            return Err(IpCidrError::EmptyInput);
        }
        let len: usize = bytes.len();
        let mut idx: usize = 0;
        let ip: u32 = Self::parse_addr_u32(bytes, &mut idx)?;
        let prefix_len: u8 = if idx == len {
            if require_slash {
                return Err(IpCidrError::InvalidSyntax);
            }
            IPV4_MAX_PREFIX_LEN
        } else if bytes[idx] == ASCII_SLASH {
            idx += 1;
            Self::parse_prefix_bytes(&bytes[idx..])?
        } else {
            return Err(IpCidrError::InvalidIpAddress);
        };
        let mask: u32 = Self::prefix_to_mask(prefix_len);
        let network: u32 = ip & mask;
        if strict_canonical && ip != network {
            return Err(IpCidrError::NonCanonicalNetwork);
        }
        Ok(Self {
            network,
            mask,
            prefix_len,
        })
    }

    /// Parses an IPv4 prefix length (`0..=32`) 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 > 2 {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        let first: u8 = bytes[0].wrapping_sub(ASCII_ZERO);
        if first > MAX_DECIMAL_DIGIT {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        if len == 1 {
            return Ok(first);
        }
        if first == 0 {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        let second: u8 = bytes[1].wrapping_sub(ASCII_ZERO);
        if second > MAX_DECIMAL_DIGIT {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        let prefix: u8 = first * 10 + second;
        if prefix > IPV4_MAX_PREFIX_LEN {
            return Err(IpCidrError::InvalidPrefixLength);
        }
        Ok(prefix)
    }
    /// Appends a decimal `u8` (`0..=255`) into `buf` at `*pos`.
    ///
    /// # Arguments
    ///
    /// - `&mut [u8; 18]` - Stack output buffer.
    /// - `&mut usize` - Current write cursor.
    /// - `u8` - Value to format.
    #[inline(always)]
    fn write_u8_dec(buf: &mut [u8; 18], pos: &mut usize, val: u8) {
        if val >= 100 {
            buf[*pos] = ASCII_ZERO + (val / 100);
            let rem: u8 = val % 100;
            buf[*pos + 1] = ASCII_ZERO + (rem / 10);
            buf[*pos + 2] = ASCII_ZERO + (rem % 10);
            *pos += 3;
        } else if val >= 10 {
            buf[*pos] = ASCII_ZERO + (val / 10);
            buf[*pos + 1] = ASCII_ZERO + (val % 10);
            *pos += 2;
        } else {
            buf[*pos] = ASCII_ZERO + val;
            *pos += 1;
        }
    }
}

/// Parses an `Ipv4Cidr` from its standard string representation (`a.b.c.d/p`).
impl FromStr for Ipv4Cidr {
    type Err = IpCidrError;

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

/// Formats an `Ipv4Cidr` in canonical `a.b.c.d/p` notation.
impl fmt::Display for Ipv4Cidr {
    /// Writes the canonical IPv4 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 {
        let mut buf: [u8; 18] = [0u8; 18];
        let mut pos: usize = 0;
        let octets: [u8; 4] = self.network.to_be_bytes();
        Self::write_u8_dec(&mut buf, &mut pos, octets[0]);
        buf[pos] = ASCII_DOT;
        pos += 1;
        Self::write_u8_dec(&mut buf, &mut pos, octets[1]);
        buf[pos] = ASCII_DOT;
        pos += 1;
        Self::write_u8_dec(&mut buf, &mut pos, octets[2]);
        buf[pos] = ASCII_DOT;
        pos += 1;
        Self::write_u8_dec(&mut buf, &mut pos, octets[3]);
        buf[pos] = ASCII_SLASH;
        pos += 1;
        Self::write_u8_dec(&mut buf, &mut pos, self.prefix_len);
        let text: &str = unsafe { str::from_utf8_unchecked(&buf[..pos]) };
        f.write_str(text)
    }
}