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
use crate::Range;
use cidr::{Cidr, Inet};
use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;

/// The prefix_length was invalid (eg: 33 for an ipv4 address)
pub struct InvalidPrefixLengthError {
    prefix_length: u8,
    max_length: u8,
}

impl Debug for InvalidPrefixLengthError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Invalid prefix length: {}. Prefix length must be {} or less",
            self.prefix_length, self.max_length
        )
    }
}

impl Display for InvalidPrefixLengthError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

/// The host_address was not the first address of the described range.
/// For example, attempting to parse `127.0.0.1/24` will result in this
/// error because the first address of the range is actually `127.0.0.0`.
pub struct InvalidHostAddressError {
    host_address: IpAddr,
    prefix_length: u8,
}

impl Debug for InvalidHostAddressError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let ipinet: cidr::IpInet = cidr::Inet::new(self.host_address, self.prefix_length).unwrap();
        write!(
            f,
            "Invalid host address: {} is not the first address in the range: {}",
            ipinet.address(),
            ipinet.network(),
        )
    }
}

impl Display for InvalidHostAddressError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

/// An error indicating why a range instance could not be constructed.
pub enum InvalidRangeError {
    InvalidPrefixLength(InvalidPrefixLengthError),
    InvalidHostAddress(InvalidHostAddressError),
}

impl Debug for InvalidRangeError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            InvalidRangeError::InvalidPrefixLength(err) => Debug::fmt(err, f),
            InvalidRangeError::InvalidHostAddress(err) => Debug::fmt(err, f),
        }
    }
}

impl Display for InvalidRangeError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl Error for InvalidRangeError {}

/// An error indicating why a range instance could not be parsed.
/// For example, the address part of the string could be invalid (eg: "127.0.0.0.0.0/8").
/// Or, the prefix_length may not be a u8 (eg: "999" or "abc"). Or, the
/// passed in string may be fully invalid (eg: "lasjdskdsl").
pub struct UnparseableRangeError {
    text: String,
}

impl Debug for UnparseableRangeError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Either the host or the prefix length portions of {} could not be parsed",
            self.text
        )
    }
}

impl Display for UnparseableRangeError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

/// `InvalidRangeError` contains information about why a range
/// instance could not be parsed.
pub enum RangeParseError {
    InvalidPrefixLength(InvalidPrefixLengthError),
    InvalidHostAddress(InvalidHostAddressError),
    UnparseableRange(UnparseableRangeError),
}

impl Debug for RangeParseError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            RangeParseError::InvalidPrefixLength(err) => Debug::fmt(err, f),
            RangeParseError::InvalidHostAddress(err) => Debug::fmt(err, f),
            RangeParseError::UnparseableRange(err) => Debug::fmt(err, f),
        }
    }
}

impl Display for RangeParseError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl Error for RangeParseError {}

/// An `IpRange` represents a network range that may be either
/// an ipv4 or an ipv6 range. If an application is only working with
/// ipv4 addresses, it may be better to use [`Ipv4Range`] instead
/// as that type is smaller and thus performance somewhat better.
///
/// An `IpRange` may either be constructed using its `new` method
/// or may be parsed from a string using its [`FromStr`] implementation.
///
/// # Example
///
/// ```
/// # use libnetrangemerge::IpRange;
/// let ip_range: IpRange = "127.0.0.0/8".parse().expect("Range was invalid");
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct IpRange {
    host_address: IpAddr,
    prefix_length: u8,
}

impl IpRange {
    /// Create a new `IpRange` value.
    pub fn new(host_address: IpAddr, prefix_length: u8) -> Result<IpRange, InvalidRangeError> {
        match host_address {
            IpAddr::V4(_) => {
                if prefix_length > 32 {
                    return Err(InvalidRangeError::InvalidPrefixLength(
                        InvalidPrefixLengthError {
                            prefix_length,
                            max_length: 32,
                        },
                    ));
                }
            }
            IpAddr::V6(_) => {
                if prefix_length > 128 {
                    return Err(InvalidRangeError::InvalidPrefixLength(
                        InvalidPrefixLengthError {
                            prefix_length,
                            max_length: 128,
                        },
                    ));
                }
            }
        }
        let ipinet: cidr::IpInet = cidr::Inet::new(host_address, prefix_length).unwrap();
        if ipinet.first_address() != host_address {
            return Err(InvalidRangeError::InvalidHostAddress(
                InvalidHostAddressError {
                    host_address,
                    prefix_length,
                },
            ));
        }
        Ok(IpRange {
            host_address,
            prefix_length,
        })
    }
}

impl Range for IpRange {
    type Address = IpAddr;

    fn embiggen(&self) -> Option<Self> {
        assert_ne!(self.prefix_length, 0);
        match IpRange::new(self.host_address, self.prefix_length - 1) {
            Ok(n) => Some(n),
            Err(InvalidRangeError::InvalidHostAddress(_)) => return None,
            Err(InvalidRangeError::InvalidPrefixLength(_)) => unreachable!(),
        }
    }

    fn host_address(&self) -> &Self::Address {
        &self.host_address
    }

    fn prefix_length(&self) -> u8 {
        self.prefix_length
    }

    fn is_ipv6(&self) -> bool {
        self.host_address.is_ipv6()
    }

    fn contains(&self, other: &Self) -> bool {
        let c = cidr::IpCidr::new(self.host_address, self.prefix_length).unwrap();
        c.contains(&other.host_address)
    }
}

impl Debug for IpRange {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.host_address, self.prefix_length)
    }
}

impl Display for IpRange {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.host_address, self.prefix_length)
    }
}

fn parse_error<T>(s: &str) -> Result<T, RangeParseError> {
    Err(RangeParseError::UnparseableRange(UnparseableRangeError {
        text: s.to_string(),
    }))
}

impl FromStr for IpRange {
    type Err = RangeParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let idx_of_slash = if let Some(pos) = s.find("/") {
            pos
        } else {
            return parse_error(s);
        };

        let host_part = &s[0..idx_of_slash];
        let prefix_length_part = &s[idx_of_slash..][1..];

        let host_address = if let Ok(host_address) = host_part.parse() {
            host_address
        } else {
            return parse_error(s);
        };

        let prefix_length = if let Ok(prefix_length) = prefix_length_part.parse() {
            prefix_length
        } else {
            return parse_error(s);
        };

        match IpRange::new(host_address, prefix_length) {
            Ok(range) => Ok(range),
            Err(InvalidRangeError::InvalidPrefixLength(err)) => {
                Err(RangeParseError::InvalidPrefixLength(err))
            }
            Err(InvalidRangeError::InvalidHostAddress(err)) => {
                Err(RangeParseError::InvalidHostAddress(err))
            }
        }
    }
}

/// An `Ipv4Range` represents an ipv4 network range.
///
/// An `Ipv4Range` may either be constructed using its `new` method
/// or may be parsed from a string using its [`FromStr`] implementation.
///
/// # Example
///
/// ```
/// # use libnetrangemerge::Ipv4Range;
/// let ip_range: Ipv4Range = "127.0.0.0/8".parse().expect("Range was invalid");
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Ipv4Range {
    host_address: Ipv4Addr,
    prefix_length: u8,
}

impl Ipv4Range {
    /// Create a new `Ipv4Range` value.
    pub fn new(host_address: Ipv4Addr, prefix_length: u8) -> Result<Ipv4Range, InvalidRangeError> {
        if prefix_length > 32 {
            return Err(InvalidRangeError::InvalidPrefixLength(
                InvalidPrefixLengthError {
                    prefix_length,
                    max_length: 32,
                },
            ));
        }
        let ipinet = cidr::Ipv4Inet::new(host_address, prefix_length).unwrap();
        if ipinet.first_address() != host_address {
            return Err(InvalidRangeError::InvalidHostAddress(
                InvalidHostAddressError {
                    host_address: host_address.into(),
                    prefix_length,
                },
            ));
        }
        Ok(Ipv4Range {
            host_address,
            prefix_length,
        })
    }
}

impl Range for Ipv4Range {
    type Address = Ipv4Addr;

    fn embiggen(&self) -> Option<Self> {
        assert_ne!(self.prefix_length, 0);
        match Ipv4Range::new(self.host_address, self.prefix_length - 1) {
            Ok(n) => Some(n),
            Err(InvalidRangeError::InvalidHostAddress(_)) => return None,
            Err(InvalidRangeError::InvalidPrefixLength(_)) => unreachable!(),
        }
    }

    fn host_address(&self) -> &Self::Address {
        &self.host_address
    }

    fn prefix_length(&self) -> u8 {
        self.prefix_length
    }

    fn is_ipv6(&self) -> bool {
        false
    }

    fn contains(&self, other: &Self) -> bool {
        let c = cidr::Ipv4Cidr::new(self.host_address, self.prefix_length).unwrap();
        c.contains(&other.host_address)
    }
}

impl Debug for Ipv4Range {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.host_address, self.prefix_length)
    }
}

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

impl FromStr for Ipv4Range {
    type Err = RangeParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let idx_of_slash = if let Some(pos) = s.find("/") {
            pos
        } else {
            return parse_error(s);
        };

        let host_part = &s[0..idx_of_slash];
        let prefix_length_part = &s[idx_of_slash..][1..];

        let host_address = if let Ok(host_address) = host_part.parse() {
            host_address
        } else {
            return parse_error(s);
        };

        let prefix_length = if let Ok(prefix_length) = prefix_length_part.parse() {
            prefix_length
        } else {
            return parse_error(s);
        };

        match Ipv4Range::new(host_address, prefix_length) {
            Ok(range) => Ok(range),
            Err(InvalidRangeError::InvalidPrefixLength(err)) => {
                Err(RangeParseError::InvalidPrefixLength(err))
            }
            Err(InvalidRangeError::InvalidHostAddress(err)) => {
                Err(RangeParseError::InvalidHostAddress(err))
            }
        }
    }
}

/// An `Ipv6Range` represents an ipv6 network range.
///
/// An `Ipv6Range` may either be constructed using its `new` method
/// or may be parsed from a string using its [`FromStr`] implementation.
///
/// # Example
///
/// ```
/// # use libnetrangemerge::Ipv6Range;
/// let ip_range: Ipv6Range = "2600::/32".parse().expect("Range was invalid");
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Ipv6Range {
    host_address: Ipv6Addr,
    prefix_length: u8,
}

impl Ipv6Range {
    /// Create a new `Ipv6Range` value.
    pub fn new(host_address: Ipv6Addr, prefix_length: u8) -> Result<Ipv6Range, InvalidRangeError> {
        if prefix_length > 128 {
            return Err(InvalidRangeError::InvalidPrefixLength(
                InvalidPrefixLengthError {
                    prefix_length,
                    max_length: 128,
                },
            ));
        }
        let ipinet = cidr::Ipv6Inet::new(host_address, prefix_length).unwrap();
        if ipinet.first_address() != host_address {
            return Err(InvalidRangeError::InvalidHostAddress(
                InvalidHostAddressError {
                    host_address: host_address.into(),
                    prefix_length,
                },
            ));
        }
        Ok(Ipv6Range {
            host_address,
            prefix_length,
        })
    }
}

impl Range for Ipv6Range {
    type Address = Ipv6Addr;

    fn embiggen(&self) -> Option<Self> {
        assert_ne!(self.prefix_length, 0);
        match Ipv6Range::new(self.host_address, self.prefix_length - 1) {
            Ok(n) => Some(n),
            Err(InvalidRangeError::InvalidHostAddress(_)) => return None,
            Err(InvalidRangeError::InvalidPrefixLength(_)) => unreachable!(),
        }
    }

    fn host_address(&self) -> &Self::Address {
        &self.host_address
    }

    fn prefix_length(&self) -> u8 {
        self.prefix_length
    }

    fn is_ipv6(&self) -> bool {
        true
    }

    fn contains(&self, other: &Self) -> bool {
        let c = cidr::Ipv6Cidr::new(self.host_address, self.prefix_length).unwrap();
        c.contains(&other.host_address)
    }
}

impl Debug for Ipv6Range {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.host_address, self.prefix_length)
    }
}

impl Display for Ipv6Range {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.host_address, self.prefix_length)
    }
}

impl FromStr for Ipv6Range {
    type Err = RangeParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let idx_of_slash = if let Some(pos) = s.find("/") {
            pos
        } else {
            return parse_error(s);
        };

        let host_part = &s[0..idx_of_slash];
        let prefix_length_part = &s[idx_of_slash..][1..];

        let host_address = if let Ok(host_address) = host_part.parse() {
            host_address
        } else {
            return parse_error(s);
        };

        let prefix_length = if let Ok(prefix_length) = prefix_length_part.parse() {
            prefix_length
        } else {
            return parse_error(s);
        };

        match Ipv6Range::new(host_address, prefix_length) {
            Ok(range) => Ok(range),
            Err(InvalidRangeError::InvalidPrefixLength(err)) => {
                Err(RangeParseError::InvalidPrefixLength(err))
            }
            Err(InvalidRangeError::InvalidHostAddress(err)) => {
                Err(RangeParseError::InvalidHostAddress(err))
            }
        }
    }
}

#[cfg(test)]
mod test {
    use crate::std_range::{InvalidRangeError, IpRange, RangeParseError};

    #[test]
    fn test_new_ipv4() {
        IpRange::new("0.0.0.0".parse().unwrap(), 0).unwrap();
        IpRange::new("127.0.0.0".parse().unwrap(), 12).unwrap();
        IpRange::new("127.0.8.0".parse().unwrap(), 21).unwrap();

        match IpRange::new("127.0.0.1".parse().unwrap(), 12) {
            Err(InvalidRangeError::InvalidHostAddress(_)) => {}
            _ => panic!("Expected InvalidHostAddress failure"),
        }

        match IpRange::new("127.0.0.0".parse().unwrap(), 99) {
            Err(InvalidRangeError::InvalidPrefixLength(_)) => {}
            _ => panic!("Expected InvalidPrefixLength failure"),
        }

        match IpRange::new("127.0.0.0".parse().unwrap(), 0) {
            Err(InvalidRangeError::InvalidHostAddress(_)) => {}
            _ => panic!("Expected InvalidHostAddress failure"),
        }
    }

    #[test]
    fn test_parsing_ipv4() {
        "0.0.0.0/0".parse::<IpRange>().unwrap();
        "127.0.0.0/12".parse::<IpRange>().unwrap();
        "127.0.8.0/21".parse::<IpRange>().unwrap();

        match "127.0.0.1/12".parse::<IpRange>() {
            Err(RangeParseError::InvalidHostAddress(_)) => {}
            _ => panic!("Expected InvalidHostAddress failure"),
        }

        match "127.0.0.0/99".parse::<IpRange>() {
            Err(RangeParseError::InvalidPrefixLength(_)) => {}
            _ => panic!("Expected InvalidPrefixLength failure"),
        }

        match "127.0.0.0/0".parse::<IpRange>() {
            Err(RangeParseError::InvalidHostAddress(_)) => {}
            _ => panic!("Expected InvalidHostAddress failure"),
        }

        match "127.0.0.0x12".parse::<IpRange>() {
            Err(RangeParseError::UnparseableRange(_)) => {}
            _ => panic!("Expected UnparseableRange failure"),
        }

        match "127.0.0x0/12".parse::<IpRange>() {
            Err(RangeParseError::UnparseableRange(_)) => {}
            _ => panic!("Expected UnparseableRange failure"),
        }

        match "127.0.0.0/x".parse::<IpRange>() {
            Err(RangeParseError::UnparseableRange(_)) => {}
            _ => panic!("Expected UnparseableRange failure"),
        }

        match "127.0.0.0/".parse::<IpRange>() {
            Err(RangeParseError::UnparseableRange(_)) => {}
            _ => panic!("Expected UnparseableRange failure"),
        }
    }

    #[test]
    fn test_new_ipv6() {
        IpRange::new("::".parse().unwrap(), 0).unwrap();
        IpRange::new("::".parse().unwrap(), 125).unwrap();
        IpRange::new("::8".parse().unwrap(), 125).unwrap();

        match IpRange::new("::1".parse().unwrap(), 12) {
            Err(InvalidRangeError::InvalidHostAddress(_)) => {}
            _ => panic!("Expected InvalidHostAddress failure"),
        }

        match IpRange::new("::".parse().unwrap(), 129) {
            Err(InvalidRangeError::InvalidPrefixLength(_)) => {}
            _ => panic!("Expected InvalidPrefixLength failure"),
        }

        match IpRange::new("::8".parse().unwrap(), 0) {
            Err(InvalidRangeError::InvalidHostAddress(_)) => {}
            _ => panic!("Expected InvalidHostAddress failure"),
        }
    }

    #[test]
    fn test_parsing_ipv6() {
        "::/0".parse::<IpRange>().unwrap();
        "::/125".parse::<IpRange>().unwrap();
        "::8/125".parse::<IpRange>().unwrap();

        match "::1/12".parse::<IpRange>() {
            Err(RangeParseError::InvalidHostAddress(_)) => {}
            _ => panic!("Expected InvalidHostAddress failure"),
        }

        match "::/129".parse::<IpRange>() {
            Err(RangeParseError::InvalidPrefixLength(_)) => {}
            _ => panic!("Expected InvalidPrefixLength failure"),
        }

        match "::8/1".parse::<IpRange>() {
            Err(RangeParseError::InvalidHostAddress(_)) => {}
            _ => panic!("Expected InvalidHostAddress failure"),
        }

        match "::8x125".parse::<IpRange>() {
            Err(RangeParseError::UnparseableRange(_)) => {}
            _ => panic!("Expected UnparseableRange failure"),
        }

        match "::x/125".parse::<IpRange>() {
            Err(RangeParseError::UnparseableRange(_)) => {}
            _ => panic!("Expected UnparseableRange failure"),
        }

        match "::8/x".parse::<IpRange>() {
            Err(RangeParseError::UnparseableRange(_)) => {}
            _ => panic!("Expected UnparseableRange failure"),
        }

        match "::8/".parse::<IpRange>() {
            Err(RangeParseError::UnparseableRange(_)) => {}
            _ => panic!("Expected UnparseableRange failure"),
        }
    }
}