bare-types 0.3.0

A zero-cost foundation for type-safe domain modeling in Rust. Implements the 'Parse, don't validate' philosophy to eliminate primitive obsession and ensure data integrity at the system boundary.
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
//! IP address range types for network programming.
//!
//! This module provides type-safe abstractions for IP address ranges,
//! allowing representation of contiguous IP address ranges.

use core::fmt;
use core::net::Ipv4Addr;
use core::str::FromStr;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Error type for IPv4 range parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum Ipv4RangeError {
    /// Invalid range format
    ///
    /// The input string is not in the correct range format.
    /// Expected format: "start-end" (e.g., "192.168.1.0-192.168.1.255").
    InvalidFormat,
    /// Invalid IP address
    ///
    /// One of the IP addresses in the range is invalid.
    InvalidIpAddr,
    /// Invalid range
    ///
    /// The start address is greater than the end address.
    InvalidRange,
}

impl fmt::Display for Ipv4RangeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidFormat => write!(f, "invalid IPv4 range format"),
            Self::InvalidIpAddr => write!(f, "invalid IP address"),
            Self::InvalidRange => write!(f, "invalid range: start > end"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Ipv4RangeError {}

/// An IPv4 address range (start to end inclusive).
///
/// # Examples
///
/// ```rust
/// use bare_types::net::Ipv4Range;
/// use core::net::Ipv4Addr;
///
/// // Parse range notation
/// let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
///
/// // Check if IP is in range
/// assert!(range.contains(&Ipv4Addr::new(192, 168, 1, 100)));
///
/// // Get number of addresses
/// assert_eq!(range.num_addresses(), 256);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Ipv4Range {
    /// Start IP address (inclusive)
    start: Ipv4Addr,
    /// End IP address (inclusive)
    end: Ipv4Addr,
}

impl Ipv4Range {
    /// Creates a new IPv4 range from start and end addresses.
    ///
    /// # Errors
    ///
    /// Returns `Ipv4RangeError::InvalidRange` if start > end.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    /// use core::net::Ipv4Addr;
    ///
    /// let range = Ipv4Range::new(
    ///     Ipv4Addr::new(192, 168, 1, 0),
    ///     Ipv4Addr::new(192, 168, 1, 255)
    /// ).unwrap();
    /// ```
    #[inline]
    pub fn new(start: Ipv4Addr, end: Ipv4Addr) -> Result<Self, Ipv4RangeError> {
        let start_u32 = u32::from(start);
        let end_u32 = u32::from(end);

        if start_u32 > end_u32 {
            return Err(Ipv4RangeError::InvalidRange);
        }

        Ok(Self { start, end })
    }

    /// Returns the start address.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    /// use core::net::Ipv4Addr;
    ///
    /// let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
    /// assert_eq!(range.start(), Ipv4Addr::new(192, 168, 1, 0));
    /// ```
    #[inline]
    #[must_use]
    pub const fn start(&self) -> Ipv4Addr {
        self.start
    }

    /// Returns the end address.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    /// use core::net::Ipv4Addr;
    ///
    /// let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
    /// assert_eq!(range.end(), Ipv4Addr::new(192, 168, 1, 255));
    /// ```
    #[inline]
    #[must_use]
    pub const fn end(&self) -> Ipv4Addr {
        self.end
    }

    /// Returns `true` if this range contains the given IP address.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    /// use core::net::Ipv4Addr;
    ///
    /// let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
    /// assert!(range.contains(&Ipv4Addr::new(192, 168, 1, 100)));
    /// assert!(!range.contains(&Ipv4Addr::new(192, 168, 2, 1)));
    /// ```
    #[inline]
    #[must_use]
    pub fn contains(&self, ip: &Ipv4Addr) -> bool {
        let ip_u32 = u32::from(*ip);
        let start_u32 = u32::from(self.start);
        let end_u32 = u32::from(self.end);
        ip_u32 >= start_u32 && ip_u32 <= end_u32
    }

    /// Returns the number of addresses in this range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    ///
    /// let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
    /// assert_eq!(range.num_addresses(), 256);
    /// ```
    #[inline]
    #[must_use]
    pub fn num_addresses(&self) -> u32 {
        let start_u32 = u32::from(self.start);
        let end_u32 = u32::from(self.end);
        end_u32 - start_u32 + 1
    }

    /// Returns `true` if this range overlaps with another range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    ///
    /// let range1: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
    /// let range2: Ipv4Range = "192.168.1.100-192.168.2.50".parse().unwrap();
    /// assert!(range1.overlaps(&range2));
    /// ```
    #[inline]
    #[must_use]
    pub fn overlaps(&self, other: &Self) -> bool {
        let self_start = u32::from(self.start);
        let self_end = u32::from(self.end);
        let other_start = u32::from(other.start);
        let other_end = u32::from(other.end);

        self_start <= other_end && self_end >= other_start
    }

    /// Returns `true` if this range fully contains another range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    ///
    /// let range1: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
    /// let range2: Ipv4Range = "192.168.1.100-192.168.1.200".parse().unwrap();
    /// assert!(range1.contains_range(&range2));
    /// assert!(!range2.contains_range(&range1));
    /// ```
    #[inline]
    #[must_use]
    pub fn contains_range(&self, other: &Self) -> bool {
        let self_start = u32::from(self.start);
        let self_end = u32::from(self.end);
        let other_start = u32::from(other.start);
        let other_end = u32::from(other.end);

        self_start <= other_start && self_end >= other_end
    }

    /// Returns `true` if this range is adjacent to another range.
    ///
    /// Two ranges are adjacent if one ends exactly where the other starts,
    /// or they can be merged into a single continuous range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    ///
    /// let range1: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
    /// let range2: Ipv4Range = "192.168.2.0-192.168.2.255".parse().unwrap();
    /// assert!(range1.is_adjacent_to(&range2));
    /// ```
    #[inline]
    #[must_use]
    pub fn is_adjacent_to(&self, other: &Self) -> bool {
        let self_end = u32::from(self.end);
        let other_start = u32::from(other.start);
        let other_end = u32::from(other.end);
        let self_start = u32::from(self.start);

        // self ends at other.start - 1 OR other ends at self.start - 1
        self_end + 1 == other_start || other_end + 1 == self_start
    }

    /// Returns a merged range if this range overlaps or is adjacent to another range.
    ///
    /// # Errors
    ///
    /// Returns `None` if the ranges cannot be merged (not overlapping or adjacent).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    ///
    /// let range1: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
    /// let range2: Ipv4Range = "192.168.2.0-192.168.2.255".parse().unwrap();
    /// let merged = range1.merge(&range2).unwrap();
    /// assert_eq!(merged.to_string(), "192.168.1.0-192.168.2.255");
    /// ```
    #[inline]
    pub fn merge(&self, other: &Self) -> Option<Self> {
        if self.overlaps(other) || self.is_adjacent_to(other) {
            let self_start = u32::from(self.start);
            let self_end = u32::from(self.end);
            let other_start = u32::from(other.start);
            let other_end = u32::from(other.end);

            let new_start = self_start.min(other_start);
            let new_end = self_end.max(other_end);

            Some(Self {
                start: Ipv4Addr::from(new_start),
                end: Ipv4Addr::from(new_end),
            })
        } else {
            None
        }
    }

    /// Returns `true` if this range can be represented as a CIDR block.
    ///
    /// A range can be represented as a CIDR if:
    /// - It has a power of 2 number of addresses, AND
    /// - The start address is aligned to that power of 2
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    ///
    /// let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
    /// assert!(range.is_cidr_compatible());
    ///
    /// let non_cidr: Ipv4Range = "192.168.1.0-192.168.1.100".parse().unwrap();
    /// assert!(!non_cidr.is_cidr_compatible());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_cidr_compatible(&self) -> bool {
        let count = self.num_addresses();
        if count == 0 {
            return false;
        }

        // Must be power of 2
        if count & (count - 1) != 0 {
            return false;
        }

        // Start address must be aligned
        let start_u32 = u32::from(self.start);
        start_u32 & (count - 1) == 0
    }

    /// Returns the prefix length if this range can be represented as a CIDR block.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bare_types::net::Ipv4Range;
    ///
    /// let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
    /// assert_eq!(range.cidr_prefix_len(), Some(24));
    /// ```
    #[inline]
    #[must_use]
    pub fn cidr_prefix_len(&self) -> Option<u8> {
        if self.is_cidr_compatible() {
            let count = self.num_addresses();
            // For power of 2 count = 2^n, prefix = 32 - n
            // count has n+1 bits, so leading_zeros = 32 - (n+1) = 31 - n
            // prefix = 32 - n = 32 - (31 - leading_zeros) = leading_zeros + 1
            let prefix_len = (count.leading_zeros() + 1) as u8;
            Some(prefix_len)
        } else {
            None
        }
    }
}

impl FromStr for Ipv4Range {
    type Err = Ipv4RangeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let Some((start_str, end_str)) = s.split_once('-') else {
            return Err(Ipv4RangeError::InvalidFormat);
        };

        let start: Ipv4Addr = start_str
            .parse()
            .map_err(|_| Ipv4RangeError::InvalidIpAddr)?;

        let end: Ipv4Addr = end_str.parse().map_err(|_| Ipv4RangeError::InvalidIpAddr)?;

        Self::new(start, end)
    }
}

impl fmt::Display for Ipv4Range {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}-{}", self.start, self.end)
    }
}

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

    #[test]
    fn test_new_valid() {
        let range = Ipv4Range::new(
            Ipv4Addr::new(192, 168, 1, 0),
            Ipv4Addr::new(192, 168, 1, 255),
        )
        .unwrap();
        assert_eq!(range.start(), Ipv4Addr::new(192, 168, 1, 0));
        assert_eq!(range.end(), Ipv4Addr::new(192, 168, 1, 255));
    }

    #[test]
    fn test_new_invalid_range() {
        assert!(
            Ipv4Range::new(
                Ipv4Addr::new(192, 168, 2, 0),
                Ipv4Addr::new(192, 168, 1, 255)
            )
            .is_err()
        );
    }

    #[test]
    fn test_parse() {
        let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
        assert_eq!(range.start(), Ipv4Addr::new(192, 168, 1, 0));
        assert_eq!(range.end(), Ipv4Addr::new(192, 168, 1, 255));
    }

    #[test]
    fn test_parse_invalid_format() {
        assert!("192.168.1.0".parse::<Ipv4Range>().is_err());
        assert!("192.168.1.0/24".parse::<Ipv4Range>().is_err());
    }

    #[test]
    fn test_contains() {
        let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
        assert!(range.contains(&Ipv4Addr::new(192, 168, 1, 0)));
        assert!(range.contains(&Ipv4Addr::new(192, 168, 1, 255)));
        assert!(range.contains(&Ipv4Addr::new(192, 168, 1, 128)));
        assert!(!range.contains(&Ipv4Addr::new(192, 168, 2, 0)));
    }

    #[test]
    fn test_num_addresses() {
        let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
        assert_eq!(range.num_addresses(), 256);

        let single: Ipv4Range = "192.168.1.100-192.168.1.100".parse().unwrap();
        assert_eq!(single.num_addresses(), 1);
    }

    #[test]
    fn test_overlaps() {
        let range1: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
        let range2: Ipv4Range = "192.168.1.100-192.168.2.50".parse().unwrap();
        let range3: Ipv4Range = "192.168.2.0-192.168.2.255".parse().unwrap();

        assert!(range1.overlaps(&range2));
        assert!(range2.overlaps(&range1));
        assert!(!range1.overlaps(&range3));
    }

    #[test]
    fn test_display() {
        let range: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
        assert_eq!(format!("{}", range), "192.168.1.0-192.168.1.255");
    }

    #[test]
    fn test_contains_range() {
        let range1: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
        let range2: Ipv4Range = "192.168.1.100-192.168.1.200".parse().unwrap();
        let range3: Ipv4Range = "192.168.1.0-192.168.2.255".parse().unwrap();

        assert!(range1.contains_range(&range2));
        assert!(!range2.contains_range(&range1));
        assert!(!range1.contains_range(&range3));
    }

    #[test]
    fn test_is_adjacent_to() {
        let range1: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
        let range2: Ipv4Range = "192.168.2.0-192.168.2.255".parse().unwrap();
        let range3: Ipv4Range = "192.168.3.0-192.168.3.255".parse().unwrap();

        assert!(range1.is_adjacent_to(&range2));
        assert!(range2.is_adjacent_to(&range1));
        assert!(!range1.is_adjacent_to(&range3));
    }

    #[test]
    fn test_merge() {
        // Test merging adjacent ranges
        let range1: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
        let range2: Ipv4Range = "192.168.2.0-192.168.2.255".parse().unwrap();
        let merged = range1.merge(&range2).unwrap();
        assert_eq!(merged.start(), Ipv4Addr::new(192, 168, 1, 0));
        assert_eq!(merged.end(), Ipv4Addr::new(192, 168, 2, 255));

        // Test merging overlapping ranges
        let range3: Ipv4Range = "192.168.1.100-192.168.2.50".parse().unwrap();
        let merged2 = range1.merge(&range3).unwrap();
        assert_eq!(merged2.start(), Ipv4Addr::new(192, 168, 1, 0));
        assert_eq!(merged2.end(), Ipv4Addr::new(192, 168, 2, 50));

        // Test non-overlapping ranges
        let range4: Ipv4Range = "192.168.5.0-192.168.5.255".parse().unwrap();
        assert!(range1.merge(&range4).is_none());
    }

    #[test]
    fn test_is_cidr_compatible() {
        // /24 network - CIDR compatible
        let cidr: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
        assert!(cidr.is_cidr_compatible());

        // /16 network - CIDR compatible
        let cidr2: Ipv4Range = "192.168.0.0-192.168.255.255".parse().unwrap();
        assert!(cidr2.is_cidr_compatible());

        // Non-CIDR compatible
        let non_cidr: Ipv4Range = "192.168.1.0-192.168.1.100".parse().unwrap();
        assert!(!non_cidr.is_cidr_compatible());
    }

    #[test]
    fn test_cidr_prefix_len() {
        let cidr: Ipv4Range = "192.168.1.0-192.168.1.255".parse().unwrap();
        assert_eq!(cidr.cidr_prefix_len(), Some(24));

        let cidr2: Ipv4Range = "192.168.0.0-192.168.255.255".parse().unwrap();
        assert_eq!(cidr2.cidr_prefix_len(), Some(16));

        let cidr3: Ipv4Range = "192.168.1.100-192.168.1.100".parse().unwrap();
        assert_eq!(cidr3.cidr_prefix_len(), Some(32));

        let non_cidr: Ipv4Range = "192.168.1.0-192.168.1.100".parse().unwrap();
        assert_eq!(non_cidr.cidr_prefix_len(), None);
    }
}