1
0

adding Address::None

This commit is contained in:
EAimTY 2023-01-24 05:00:10 +09:00
parent 595ba01e2d
commit 3caa232f13
2 changed files with 41 additions and 16 deletions

View File

@ -6,30 +6,37 @@ use std::{
/// Address
///
/// ```plain
/// +------+----------+----------+
/// | TYPE | ADDR | PORT |
/// +------+----------+----------+
/// | 1 | Variable | 2 |
/// +------+----------+----------+
/// +------+----------+
/// | TYPE | ADDR |
/// +------+----------+
/// | 1 | Variable |
/// +------+----------+
/// ```
///
/// The address type can be one of the following:
/// 0x00: fully-qualified domain name (the first byte indicates the length of the domain name)
/// 0x01: IPv4 address
/// 0x02: IPv6 address
///
/// 0x00: None
/// 0x01: Fully-qualified domain name (the first byte indicates the length of the domain name)
/// 0x02: IPv4 address
/// 0x03: IPv6 address
///
/// The port number is encoded in 2 bytes after the Domain name / IP address.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Address {
None,
DomainAddress(String, u16),
SocketAddress(SocketAddr),
}
impl Address {
pub const TYPE_CODE_DOMAIN: u8 = 0x00;
pub const TYPE_CODE_IPV4: u8 = 0x01;
pub const TYPE_CODE_IPV6: u8 = 0x02;
pub const TYPE_CODE_NONE: u8 = 0x00;
pub const TYPE_CODE_DOMAIN: u8 = 0x01;
pub const TYPE_CODE_IPV4: u8 = 0x02;
pub const TYPE_CODE_IPV6: u8 = 0x03;
pub fn type_code(&self) -> u8 {
match self {
Self::None => Self::TYPE_CODE_NONE,
Self::DomainAddress(_, _) => Self::TYPE_CODE_DOMAIN,
Self::SocketAddress(addr) => match addr {
SocketAddr::V4(_) => Self::TYPE_CODE_IPV4,
@ -40,18 +47,36 @@ impl Address {
pub fn len(&self) -> usize {
1 + match self {
Address::None => 0,
Address::DomainAddress(addr, _) => 1 + addr.len() + 2,
Address::SocketAddress(addr) => match addr {
SocketAddr::V4(_) => 6,
SocketAddr::V6(_) => 18,
SocketAddr::V4(_) => 1 * 4 + 2,
SocketAddr::V6(_) => 2 * 8 + 2,
},
}
}
pub fn is_none(&self) -> bool {
matches!(self, Self::None)
}
pub fn is_domain(&self) -> bool {
matches!(self, Self::DomainAddress(_, _))
}
pub fn is_ipv4(&self) -> bool {
matches!(self, Self::SocketAddress(SocketAddr::V4(_)))
}
pub fn is_ipv6(&self) -> bool {
matches!(self, Self::SocketAddress(SocketAddr::V6(_)))
}
}
impl Display for Address {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
Self::None => write!(f, "none"),
Self::DomainAddress(addr, port) => write!(f, "{addr}:{port}"),
Self::SocketAddress(addr) => write!(f, "{addr}"),
}

View File

@ -12,7 +12,7 @@ pub struct Packet {
pub frag_total: u8,
pub frag_id: u8,
pub len: u16,
pub addr: Option<Address>,
pub addr: Address,
}
impl Packet {
@ -24,7 +24,7 @@ impl Packet {
frag_total: u8,
frag_id: u8,
len: u16,
addr: Option<Address>,
addr: Address,
) -> Self {
Self {
assoc_id,
@ -43,6 +43,6 @@ impl Command for Packet {
}
fn len(&self) -> usize {
2 + 2 + 1 + 1 + 2 + self.addr.as_ref().map_or(0, |addr| addr.len())
2 + 2 + 1 + 1 + 2 + self.addr.len()
}
}