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
use super::*;

/// Core operations for `IpCidr`.
impl IpCidr {
    /// Constructs a canonical `IpCidr` from an `IpAddr` and prefix length.
    ///
    /// # Arguments
    ///
    /// - `IpAddr` - The IPv4 or IPv6 address.
    /// - `u8` - The prefix length (`0..=32` for IPv4, `0..=128` for IPv6).
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The canonical `IpCidr` or an error.
    #[inline(always)]
    pub fn new(addr: IpAddr, prefix_len: u8) -> Result<Self, IpCidrError> {
        match addr {
            IpAddr::V4(v4) => Ok(Self::V4(Ipv4Cidr::new(v4, prefix_len)?)),
            IpAddr::V6(v6) => Ok(Self::V6(Ipv6Cidr::new(v6, prefix_len)?)),
        }
    }

    /// Constructs a canonical `IpCidr`, rejecting addresses with non-zero host bits.
    ///
    /// # Arguments
    ///
    /// - `IpAddr` - The IPv4 or IPv6 network address.
    /// - `u8` - The prefix length (`0..=32` for IPv4, `0..=128` for IPv6).
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The canonical `IpCidr` or an error.
    #[inline(always)]
    pub fn new_strict(addr: IpAddr, prefix_len: u8) -> Result<Self, IpCidrError> {
        match addr {
            IpAddr::V4(v4) => Ok(Self::V4(Ipv4Cidr::new_strict(v4, prefix_len)?)),
            IpAddr::V6(v6) => Ok(Self::V6(Ipv6Cidr::new_strict(v6, prefix_len)?)),
        }
    }

    /// Creates a single-host CIDR block (`/32` for IPv4, `/128` for IPv6).
    ///
    /// # Arguments
    ///
    /// - `IpAddr` - The single host IP address.
    #[inline(always)]
    pub fn from_host(addr: IpAddr) -> Self {
        match addr {
            IpAddr::V4(v4) => Self::V4(Ipv4Cidr::from_host(v4)),
            IpAddr::V6(v6) => Self::V6(Ipv6Cidr::from_host(v6)),
        }
    }

    /// Classifies whether a non-empty CIDR input targets IPv6 by inspecting at most the first 5 bytes.
    ///
    /// Every valid IPv6 literal contains `:` within its first 5 bytes (`xxxx:` or `::`), whereas
    /// every valid IPv4 literal contains `.` within its first 4 bytes and never `:`.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Non-empty ASCII input bytes.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the input should be parsed as IPv6.
    #[inline(always)]
    fn is_ipv6_input(bytes: &[u8]) -> bool {
        let probe_len: usize = bytes.len().min(FAMILY_PROBE_BYTES);
        let mut idx: usize = 0;
        while idx < probe_len {
            let b: u8 = bytes[idx];
            if b == ASCII_COLON {
                return true;
            }
            if b == CIDR_ASCII_DOT {
                return false;
            }
            idx += 1;
        }
        bytes[probe_len..].contains(&ASCII_COLON)
    }

    /// Parses an IPv4 or IPv6 CIDR string (`addr/prefix`) with zero heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&str` - The CIDR string to parse.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed canonical `IpCidr` or a parse error.
    #[inline(always)]
    pub fn parse(input: &str) -> Result<Self, IpCidrError> {
        if input.is_empty() {
            return Err(IpCidrError::EmptyInput);
        }
        if Self::is_ipv6_input(input.as_bytes()) {
            Ok(Self::V6(Ipv6Cidr::parse(input)?))
        } else {
            Ok(Self::V4(Ipv4Cidr::parse(input)?))
        }
    }

    /// Parses an IPv4 or IPv6 CIDR string (`addr/prefix`), rejecting non-zero host bits.
    ///
    /// # Arguments
    ///
    /// - `&str` - The CIDR string to parse strictly.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed canonical `IpCidr` or an error.
    #[inline(always)]
    pub fn parse_strict(input: &str) -> Result<Self, IpCidrError> {
        if input.is_empty() {
            return Err(IpCidrError::EmptyInput);
        }
        if Self::is_ipv6_input(input.as_bytes()) {
            Ok(Self::V6(Ipv6Cidr::parse_strict(input)?))
        } else {
            Ok(Self::V4(Ipv4Cidr::parse_strict(input)?))
        }
    }

    /// Parses either a CIDR string (`addr/prefix`) or a bare IP host address.
    ///
    /// # Arguments
    ///
    /// - `&str` - The CIDR or bare IP address string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, IpCidrError>` - The parsed canonical `IpCidr` or an error.
    #[inline(always)]
    pub fn parse_or_host(input: &str) -> Result<Self, IpCidrError> {
        if input.is_empty() {
            return Err(IpCidrError::EmptyInput);
        }
        if Self::is_ipv6_input(input.as_bytes()) {
            Ok(Self::V6(Ipv6Cidr::parse_or_host(input)?))
        } else {
            Ok(Self::V4(Ipv4Cidr::parse_or_host(input)?))
        }
    }

    /// Returns `true` if this is an IPv4 CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` for `IpCidr::V4`, `false` for `IpCidr::V6`.
    #[inline(always)]
    pub fn is_ipv4(&self) -> bool {
        matches!(self, Self::V4(_))
    }

    /// Returns `true` if this is an IPv6 CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` for `IpCidr::V6`, `false` for `IpCidr::V4`.
    #[inline(always)]
    pub fn is_ipv6(&self) -> bool {
        matches!(self, Self::V6(_))
    }

    /// Returns the prefix length of this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `u8` - The prefix length in bits.
    #[inline(always)]
    pub fn prefix_len(&self) -> u8 {
        match self {
            Self::V4(cidr) => cidr.get_prefix_len(),
            Self::V6(cidr) => cidr.get_prefix_len(),
        }
    }

    /// Returns the canonical network address of this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `IpAddr` - The canonical network address.
    #[inline(always)]
    pub fn network(&self) -> IpAddr {
        match self {
            Self::V4(cidr) => IpAddr::V4(cidr.network()),
            Self::V6(cidr) => IpAddr::V6(cidr.network()),
        }
    }

    /// Returns the inclusive last address covered by this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `IpAddr` - The last address in the block.
    #[inline(always)]
    pub fn last_address(&self) -> IpAddr {
        match self {
            Self::V4(cidr) => IpAddr::V4(cidr.last_address()),
            Self::V6(cidr) => IpAddr::V6(cidr.last_address()),
        }
    }

    /// Returns whether this block matches only a single host address.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` for `/32` IPv4 or `/128` IPv6.
    #[inline(always)]
    pub fn is_host(&self) -> bool {
        match self {
            Self::V4(cidr) => cidr.is_host(),
            Self::V6(cidr) => cidr.is_host(),
        }
    }

    /// Returns whether this block is a `/0` wildcard for its address family.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `prefix_len == 0`.
    #[inline(always)]
    pub fn is_any(&self) -> bool {
        match self {
            Self::V4(cidr) => cidr.is_any(),
            Self::V6(cidr) => cidr.is_any(),
        }
    }

    /// Checks whether the given `IpAddr` belongs to this CIDR block.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    /// - `IpAddr` - The IP address to test.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if `addr` matches this block's family and bitmask.
    #[inline(always)]
    pub fn contains(&self, addr: IpAddr) -> bool {
        match (self, addr) {
            (Self::V4(cidr), IpAddr::V4(ip)) => cidr.contains(ip),
            (Self::V6(cidr), IpAddr::V6(ip)) => cidr.contains(ip),
            _ => false,
        }
    }

    /// Checks whether `addr` belongs to this CIDR block, also unwrapping IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) against IPv4 blocks.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The CIDR block.
    /// - `IpAddr` - The IP address to test.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if `addr` (or its mapped IPv4 address) is contained in this block.
    #[inline(always)]
    pub fn contains_mapped(&self, addr: IpAddr) -> bool {
        match (self, addr) {
            (Self::V4(cidr), IpAddr::V4(ip)) => cidr.contains(ip),
            (Self::V4(cidr), IpAddr::V6(ip)) => match ip.to_ipv4_mapped() {
                Some(mapped) => cidr.contains(mapped),
                None => false,
            },
            (Self::V6(cidr), IpAddr::V6(ip)) => cidr.contains(ip),
            _ => false,
        }
    }

    /// Checks whether this CIDR block completely contains another `IpCidr`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The outer CIDR block.
    /// - `Self` - The candidate subnet block.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if both blocks share an address family and `self` contains `other`.
    #[inline(always)]
    pub fn contains_cidr(&self, other: Self) -> bool {
        match (self, other) {
            (Self::V4(a), Self::V4(b)) => a.contains_cidr(b),
            (Self::V6(a), Self::V6(b)) => a.contains_cidr(b),
            _ => false,
        }
    }

    /// Checks whether this CIDR block overlaps another `IpCidr`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The first CIDR block.
    /// - `Self` - The second CIDR block.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if both blocks share at least one IP address.
    #[inline(always)]
    pub fn overlaps(&self, other: Self) -> bool {
        match (self, other) {
            (Self::V4(a), Self::V4(b)) => a.overlaps(b),
            (Self::V6(a), Self::V6(b)) => a.overlaps(b),
            _ => false,
        }
    }
}

/// Converts an `Ipv4Cidr` into `IpCidr::V4`.
impl From<Ipv4Cidr> for IpCidr {
    /// Wraps an `Ipv4Cidr` in `IpCidr::V4`.
    ///
    /// # Arguments
    ///
    /// - `Ipv4Cidr` - The IPv4 CIDR block.
    #[inline(always)]
    fn from(cidr: Ipv4Cidr) -> Self {
        Self::V4(cidr)
    }
}

/// Converts an `Ipv6Cidr` into `IpCidr::V6`.
impl From<Ipv6Cidr> for IpCidr {
    /// Wraps an `Ipv6Cidr` in `IpCidr::V6`.
    ///
    /// # Arguments
    ///
    /// - `Ipv6Cidr` - The IPv6 CIDR block.
    #[inline(always)]
    fn from(cidr: Ipv6Cidr) -> Self {
        Self::V6(cidr)
    }
}

/// Parses an `IpCidr` from its standard string representation.
impl FromStr for IpCidr {
    type Err = IpCidrError;

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

/// Formats an `IpCidr` in canonical notation.
impl fmt::Display for IpCidr {
    /// Writes the canonical IPv4 or 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 {
        match self {
            Self::V4(cidr) => fmt::Display::fmt(cidr, f),
            Self::V6(cidr) => fmt::Display::fmt(cidr, f),
        }
    }
}