iptrie/prefix/
shorten.rs

1use ipnet::{IpNet, Ipv4Net, Ipv6Net};
2use crate::{BitSlot, IpPrefix, Ipv4Prefix, Ipv6Prefix, Ipv6Prefix120, Ipv6Prefix56};
3
4/// Shortening an Ip prefix
5pub trait IpPrefixShortening {
6    
7    /// Shortens the prefix
8    ///
9    /// Remains unchanged if the specified length is greater
10    /// than the previous one
11    fn shorten(&mut self, maxlen: u8);
12}
13
14impl IpPrefixShortening for Ipv4Prefix 
15{
16    #[inline]
17    fn shorten(&mut self, maxlen: u8) {
18        if maxlen < self.len {
19            self.addr = u32::from(self.addr) & u32::bitmask(maxlen);
20            self.len = maxlen;
21        }
22    }
23}
24
25impl IpPrefixShortening for Ipv6Prefix
26{
27    #[inline]
28    fn shorten(&mut self, maxlen: u8) {
29        if maxlen < self.len {
30            self.addr = u128::from(self.addr) & u128::bitmask(maxlen);
31            self.len = maxlen;
32        }
33    }
34}
35
36
37impl IpPrefixShortening for Ipv6Prefix56
38{
39    #[inline]
40    fn shorten(&mut self, maxlen: u8) {
41        if maxlen < self.len() {
42            self.slot = (self.slot & u64::bitmask(maxlen)) | u64::from(maxlen);
43        }
44    }
45}
46
47impl IpPrefixShortening for Ipv6Prefix120
48{
49    #[inline]
50    fn shorten(&mut self, maxlen: u8) {
51        if maxlen < self.len() {
52            self.slot = (self.slot & u128::bitmask(maxlen)) | u128::from(maxlen);
53        }
54    }
55}
56
57
58impl IpPrefixShortening for IpNet {
59    fn shorten(&mut self, maxlen: u8) {
60        match self {
61            IpNet::V4(ip) => ip.shorten(maxlen),
62            IpNet::V6(ip) => ip.shorten(maxlen),
63        }
64    }
65}
66
67impl IpPrefixShortening for Ipv4Net 
68{
69    fn shorten(&mut self, maxlen: u8) 
70    {
71        if maxlen < self.prefix_len() {
72            *self = Ipv4Net::new(self.network(), maxlen).unwrap()
73        }
74    }
75}
76
77impl IpPrefixShortening for Ipv6Net
78{
79    fn shorten(&mut self, maxlen: u8)
80    {
81        if maxlen < self.prefix_len() {
82            *self = Ipv6Net::new(self.network(), maxlen).unwrap()
83        }
84    }
85}