2016-12-10 19:16:51 +08:00
|
|
|
use core::fmt;
|
|
|
|
|
|
|
|
/// A four-octet IPv4 address.
|
2016-12-12 10:39:46 +08:00
|
|
|
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
|
2016-12-10 19:16:51 +08:00
|
|
|
pub struct Address(pub [u8; 4]);
|
|
|
|
|
|
|
|
impl Address {
|
|
|
|
/// Construct an IPv4 address from a sequence of octets, in big-endian.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
/// The function panics if `data` is not four octets long.
|
|
|
|
pub fn from_bytes(data: &[u8]) -> Address {
|
|
|
|
let mut bytes = [0; 4];
|
|
|
|
bytes.copy_from_slice(data);
|
|
|
|
Address(bytes)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return an IPv4 address as a sequence of octets, in big-endian.
|
|
|
|
pub fn as_bytes(&self) -> &[u8] {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for Address {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
let bytes = self.0;
|
2016-12-11 00:25:43 +08:00
|
|
|
write!(f, "{}.{}.{}.{}", bytes[0], bytes[1], bytes[2], bytes[3])
|
2016-12-10 19:16:51 +08:00
|
|
|
}
|
|
|
|
}
|