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
use std::convert::TryFrom;
use std::fmt;

use {
    IPV6_INTERFACE_LOCAL_MULTICAST_MASK, IPV6_LINK_LOCAL_MULTICAST_MASK,
    IPV6_LINK_LOCAL_UNICAST_MASK, IPV6_LOOPBACK, IPV6_MULTICAST_MASK, IPV6_UNSPECIFIED,
    Ipv6Formatter, MalformedAddress,
};

// An Ipv6 address
#[derive(Copy, Eq, PartialEq, Hash, Clone)]
pub struct Ipv6Address(pub(crate) u128);

impl Ipv6Address {
    /// Return `true` if this address is `::`
    pub fn is_unspecified(&self) -> bool {
        *self == IPV6_UNSPECIFIED
    }

    /// Return `true` if this address is `::1`
    pub fn is_loopback(&self) -> bool {
        *self == IPV6_LOOPBACK
    }

    /// Return `true` if this address is a multicast address
    pub fn is_multicast(&self) -> bool {
        *self & IPV6_MULTICAST_MASK == IPV6_MULTICAST_MASK
    }

    /// Return `true` if this address is an interface-local multicast address
    pub fn is_interface_local_multicast(&self) -> bool {
        *self & IPV6_INTERFACE_LOCAL_MULTICAST_MASK == IPV6_INTERFACE_LOCAL_MULTICAST_MASK
    }

    /// Return `true` if this address is a link-local multicast address
    pub fn is_link_local_multicast(&self) -> bool {
        *self & IPV6_LINK_LOCAL_MULTICAST_MASK == IPV6_LINK_LOCAL_MULTICAST_MASK
    }

    /// Return `true` if this address is a link-local unicast address
    pub fn is_link_local_unicast(&self) -> bool {
        *self & IPV6_LINK_LOCAL_UNICAST_MASK == IPV6_LINK_LOCAL_UNICAST_MASK
    }

    /// Return `true` if this address is a global unicast address
    pub fn is_global_unicast(&self) -> bool {
        !self.is_link_local_unicast()
            && !self.is_unspecified()
            && !self.is_loopback()
            && !self.is_multicast()
    }

    /// Return the address as an `u128`
    pub fn value(&self) -> u128 {
        self.0
    }

    /// Return the address as an array of bytes
    pub fn octets(&self) -> [u8; 16] {
        let mut bytes: [u8; 16] = [0; 16];
        for (i, b) in bytes.iter_mut().enumerate() {
            *b = self.octet(i);
        }
        bytes
    }

    /// Return the address as an array of bytes
    pub fn hextets(&self) -> [u16; 8] {
        let mut hextets: [u16; 8] = [0; 8];
        for (i, h) in hextets.iter_mut().enumerate() {
            *h = self.hextet(i);
        }
        hextets
    }

    fn octet(&self, i: usize) -> u8 {
        ((self.0 >> ((15 - i) * 8)) & 0xff) as u8
    }

    fn hextet(&self, i: usize) -> u16 {
        ((self.0 >> ((7 - i) * 16)) & 0xffff) as u16
    }

    pub fn from_slice_unchecked(bytes: &[u8]) -> Ipv6Address {
        let mut shift = 120;
        let mut address = Ipv6Address(0);
        for b in bytes {
            address += u128::from(*b) << shift;
            shift -= 8;
        }
        address
    }
    pub fn from_slice(bytes: &[u8]) -> Result<Ipv6Address, MalformedAddress> {
        if bytes.len() != 16 {
            return Err(MalformedAddress);
        }
        Ok(Self::from_slice_unchecked(bytes))
    }

    /// Create a formatter to stringify this IPv6 address.
    pub fn formatter<'a, W: fmt::Write>(&self, writer: &'a mut W) -> Ipv6Formatter<'a, W> {
        Ipv6Formatter::new(writer, self.hextets())
    }

    /// Return a string representation of this IPv6 address. There are several ways to represent an
    /// IPv6 address. This method uses the convention documented in
    /// [RFC5952](https://tools.ietf.org/html/rfc5952):
    ///
    /// - lower case
    /// - the longest sequence of zeros is replaced by `::`
    /// - no leading zero (`fe80::123` instead of `fe80::0123`)
    ///
    /// For other formatting options, use [`formatter()`](#method.formatter`).
    ///
    /// ```rust
    /// # use ipaddr::{Ipv6Address};
    /// # fn main() {
    /// let ip = Ipv6Address::from(0xfe80_0000_0000_0000_8657_e6fe_08d5_5325);
    /// assert_eq!(ip.to_string(), "fe80::8657:e6fe:8d5:5325");
    ///
    /// // the same representation is used in the Display implementation
    /// assert_eq!(format!("{}", ip), "fe80::8657:e6fe:8d5:5325");
    /// # }
    pub fn to_string(&self) -> String {
        let mut s = String::with_capacity(40);
        // https://doc.rust-lang.org/std/fmt/index.html#formatting-traits
        // Formatting strings is infaillible. The write! macro we use in our formatter can only
        // fail when writing in the underlying string, but here is a String so it should not fail.
        self.formatter(&mut s)
            .rfc_5952()
            .write()
            .expect("string formatting failed?!");
        s
    }
}

impl fmt::Display for Ipv6Address {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.formatter(f).write()
    }
}

impl fmt::Debug for Ipv6Address {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Ipv6Address(")?;
        self.formatter(f).write()?;
        f.write_str(")")
    }
}

impl<'a> TryFrom<&'a [u8]> for Ipv6Address {
    type Error = MalformedAddress;
    fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
        Ipv6Address::from_slice(bytes)
    }
}

impl From<[u8; 16]> for Ipv6Address {
    fn from(bytes: [u8; 16]) -> Self {
        Ipv6Address::from_slice_unchecked(&bytes[..])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_packed() {
        let expected: [u8; 16] = [
            0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x57, 0xe6, 0xfe, 0x08, 0xd5,
            0x53, 0x25,
        ];

        let ip = Ipv6Address(0xfe800000000000008657e6fe08d55325);
        assert_eq!(ip.octets(), expected);
    }
    #[test]
    fn test_from_bytes() {
        let bytes: [u8; 16] = [
            0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86, 0x57, 0xe6, 0xfe, 0x08, 0xd5,
            0x53, 0x25,
        ];

        let expected = Ipv6Address(0xfe800000000000008657e6fe08d55325);
        assert_eq!(Ipv6Address::from(bytes), expected);
    }
}