use crate::{Buf, BufMut, BufResult, Codec, Cursor};
use core::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Address(pub [u8; 16]);
impl Address {
pub const UNSPECIFIED: Self = Self([0; 16]);
pub const LOOPBACK: Self = Self([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
pub const fn from_octets(octets: [u8; 16]) -> Self {
Self(octets)
}
pub const fn octets(self) -> [u8; 16] {
self.0
}
pub const fn is_multicast(self) -> bool {
self.0[0] == 0xFF
}
pub const fn is_link_local(self) -> bool {
self.0[0] == 0xFE && (self.0[1] & 0xC0) == 0x80
}
pub const fn is_unique_local(self) -> bool {
(self.0[0] & 0xFE) == 0xFC
}
pub const fn is_global_unicast(self) -> bool {
!self.is_multicast() && !self.is_link_local() && !self.is_unique_local()
}
}
#[cfg(feature = "std")]
impl From<std::net::Ipv6Addr> for Address {
fn from(addr: std::net::Ipv6Addr) -> Self {
Self(addr.octets())
}
}
#[cfg(feature = "std")]
impl From<Address> for std::net::Ipv6Addr {
fn from(addr: Address) -> Self {
std::net::Ipv6Addr::from(addr.0)
}
}
impl From<[u8; 16]> for Address {
fn from(octets: [u8; 16]) -> Self {
Self(octets)
}
}
impl From<Address> for [u8; 16] {
fn from(addr: Address) -> Self {
addr.0
}
}
impl Codec for Address {
fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
self.0.encode(writer, ())
}
fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
Ok(Self(reader.read_array::<16>()?))
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[cfg(feature = "std")]
{
write!(f, "{}", std::net::Ipv6Addr::from(*self))
}
#[cfg(not(feature = "std"))]
{
for (i, &byte) in self.0.iter().enumerate() {
if i % 2 == 0 && i != 0 {
write!(f, ":")?;
}
write!(f, "{:02x}", byte)?;
}
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn address_properties() {
assert!(Address::UNSPECIFIED.is_global_unicast() == false);
assert!(Address::LOOPBACK.is_global_unicast() == false);
let multicast =
Address::from_octets([0xFF, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
assert!(multicast.is_multicast());
let link_local =
Address::from_octets([0xFE, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
assert!(link_local.is_link_local());
let unique_local =
Address::from_octets([0xFC, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
assert!(unique_local.is_unique_local());
}
}