#[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use core::cmp::Ordering;
use core::fmt::{self, Write};
use core::hash;
use core::iter;
use core::option;
use core::slice;
use super::helper::WriteHelper;
use super::{IpAddr, Ipv4Addr, Ipv6Addr};
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SocketAddr {
V4(SocketAddrV4),
V6(SocketAddrV6),
}
#[derive(Copy)]
pub struct SocketAddrV4 {
addr: Ipv4Addr,
port: u16,
}
#[derive(Copy)]
pub struct SocketAddrV6 {
addr: Ipv6Addr,
port: u16,
flow_info: u32,
scope_id: u32,
}
impl SocketAddr {
pub const fn new(ip: IpAddr, port: u16) -> SocketAddr {
match ip {
IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
}
}
pub const fn ip(&self) -> IpAddr {
match *self {
SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
}
}
pub fn set_ip(&mut self, new_ip: IpAddr) {
match (self, new_ip) {
(&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
(&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
(self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
}
}
pub const fn port(&self) -> u16 {
match *self {
SocketAddr::V4(ref a) => a.port(),
SocketAddr::V6(ref a) => a.port(),
}
}
pub fn set_port(&mut self, new_port: u16) {
match *self {
SocketAddr::V4(ref mut a) => a.set_port(new_port),
SocketAddr::V6(ref mut a) => a.set_port(new_port),
}
}
pub const fn is_ipv4(&self) -> bool {
matches!(*self, SocketAddr::V4(_))
}
pub const fn is_ipv6(&self) -> bool {
matches!(*self, SocketAddr::V6(_))
}
}
impl SocketAddrV4 {
pub const fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
SocketAddrV4 {
addr: ip,
port: port,
}
}
pub const fn ip(&self) -> &Ipv4Addr {
&self.addr
}
pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
self.addr = new_ip
}
pub const fn port(&self) -> u16 {
self.port
}
pub fn set_port(&mut self, new_port: u16) {
self.port = new_port;
}
}
impl SocketAddrV6 {
pub const fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
SocketAddrV6 {
addr: ip,
port: port,
flow_info: flowinfo,
scope_id: scope_id,
}
}
pub const fn ip(&self) -> &Ipv6Addr {
&self.addr
}
pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
self.addr = new_ip
}
pub const fn port(&self) -> u16 {
self.port
}
pub fn set_port(&mut self, new_port: u16) {
self.port = new_port
}
pub const fn flowinfo(&self) -> u32 {
self.flow_info
}
pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
self.flow_info = new_flowinfo;
}
pub const fn scope_id(&self) -> u32 {
self.scope_id
}
pub fn set_scope_id(&mut self, new_scope_id: u32) {
self.scope_id = new_scope_id;
}
}
impl From<SocketAddrV4> for SocketAddr {
fn from(sock4: SocketAddrV4) -> SocketAddr {
SocketAddr::V4(sock4)
}
}
impl From<SocketAddrV6> for SocketAddr {
fn from(sock6: SocketAddrV6) -> SocketAddr {
SocketAddr::V6(sock6)
}
}
impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
fn from(pieces: (I, u16)) -> SocketAddr {
SocketAddr::new(pieces.0.into(), pieces.1)
}
}
impl fmt::Display for SocketAddr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
SocketAddr::V4(ref a) => a.fmt(f),
SocketAddr::V6(ref a) => a.fmt(f),
}
}
}
impl fmt::Debug for SocketAddr {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, fmt)
}
}
impl fmt::Display for SocketAddrV4 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.precision().is_none() && f.width().is_none() {
write!(f, "{}:{}", self.ip(), self.port())
} else {
const IPV4_SOCKET_BUF_LEN: usize = (3 * 4) + 3 + 1 + 5; let mut buf = [0; IPV4_SOCKET_BUF_LEN];
let mut buf_slice = WriteHelper::new(&mut buf[..]);
write!(buf_slice, "{}:{}", self.ip(), self.port()).unwrap();
let len = IPV4_SOCKET_BUF_LEN - buf_slice.into_raw().len();
let buf = unsafe { core::str::from_utf8_unchecked(&buf[..len]) };
f.pad(buf)
}
}
}
impl fmt::Debug for SocketAddrV4 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, fmt)
}
}
impl fmt::Display for SocketAddrV6 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.precision().is_none() && f.width().is_none() {
match self.scope_id() {
0 => write!(f, "[{}]:{}", self.ip(), self.port()),
scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
}
} else {
const IPV6_SOCKET_BUF_LEN: usize = (4 * 8) + 7 + 2 + 1 + 10 + 1 + 5;
let mut buf = [0; IPV6_SOCKET_BUF_LEN];
let mut buf_slice = WriteHelper::new(&mut buf[..]);
match self.scope_id() {
0 => write!(buf_slice, "[{}]:{}", self.ip(), self.port()),
scope_id => write!(buf_slice, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
}
.unwrap();
let len = IPV6_SOCKET_BUF_LEN - buf_slice.into_raw().len();
let buf = unsafe { core::str::from_utf8_unchecked(&buf[..len]) };
f.pad(buf)
}
}
}
impl fmt::Debug for SocketAddrV6 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, fmt)
}
}
impl Clone for SocketAddrV4 {
fn clone(&self) -> SocketAddrV4 {
*self
}
}
impl Clone for SocketAddrV6 {
fn clone(&self) -> SocketAddrV6 {
*self
}
}
impl PartialEq for SocketAddrV4 {
fn eq(&self, other: &SocketAddrV4) -> bool {
self.port == other.port && self.addr == other.addr
}
}
impl PartialEq for SocketAddrV6 {
fn eq(&self, other: &SocketAddrV6) -> bool {
self.port == other.port
&& self.addr == other.addr
&& self.flow_info == other.flow_info
&& self.scope_id == other.scope_id
}
}
impl Eq for SocketAddrV4 {}
impl Eq for SocketAddrV6 {}
impl PartialOrd for SocketAddrV4 {
fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialOrd for SocketAddrV6 {
fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SocketAddrV4 {
fn cmp(&self, other: &SocketAddrV4) -> Ordering {
self.ip()
.cmp(other.ip())
.then(self.port().cmp(&other.port()))
}
}
impl Ord for SocketAddrV6 {
fn cmp(&self, other: &SocketAddrV6) -> Ordering {
self.ip()
.cmp(other.ip())
.then(self.port().cmp(&other.port()))
}
}
impl hash::Hash for SocketAddrV4 {
fn hash<H: hash::Hasher>(&self, s: &mut H) {
(self.port, self.addr).hash(s)
}
}
impl hash::Hash for SocketAddrV6 {
fn hash<H: hash::Hasher>(&self, s: &mut H) {
(self.port, self.addr, self.flow_info, self.scope_id).hash(s)
}
}
#[cfg_attr(feature = "std", doc = "[`TcpStream`]: std::net::TcpStream")]
#[cfg_attr(
not(feature = "std"),
doc = "[`TcpStream`]: https://doc.rust-lang.org/std/net/struct.TcpStream.html"
)]
#[cfg_attr(feature = "std", doc = "[`UdpSocket`]: std::net::UdpSocket")]
#[cfg_attr(
not(feature = "std"),
doc = "[`UdpSocket`]: https://doc.rust-lang.org/std/net/struct.UdpSocket.html"
)]
pub trait ToSocketAddrs {
type Iter: Iterator<Item = SocketAddr>;
fn to_socket_addrs(&self) -> Result<Self::Iter, ToSocketAddrError>;
}
#[derive(Debug)]
pub enum ToSocketAddrError {}
impl ToSocketAddrs for SocketAddr {
type Iter = option::IntoIter<SocketAddr>;
fn to_socket_addrs(&self) -> Result<option::IntoIter<SocketAddr>, ToSocketAddrError> {
Ok(Some(*self).into_iter())
}
}
impl ToSocketAddrs for SocketAddrV4 {
type Iter = option::IntoIter<SocketAddr>;
fn to_socket_addrs(&self) -> Result<option::IntoIter<SocketAddr>, ToSocketAddrError> {
SocketAddr::V4(*self).to_socket_addrs()
}
}
impl ToSocketAddrs for SocketAddrV6 {
type Iter = option::IntoIter<SocketAddr>;
fn to_socket_addrs(&self) -> Result<option::IntoIter<SocketAddr>, ToSocketAddrError> {
SocketAddr::V6(*self).to_socket_addrs()
}
}
impl ToSocketAddrs for (IpAddr, u16) {
type Iter = option::IntoIter<SocketAddr>;
fn to_socket_addrs(&self) -> Result<option::IntoIter<SocketAddr>, ToSocketAddrError> {
let (ip, port) = *self;
match ip {
IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
}
}
}
impl ToSocketAddrs for (Ipv4Addr, u16) {
type Iter = option::IntoIter<SocketAddr>;
fn to_socket_addrs(&self) -> Result<option::IntoIter<SocketAddr>, ToSocketAddrError> {
let (ip, port) = *self;
SocketAddrV4::new(ip, port).to_socket_addrs()
}
}
impl ToSocketAddrs for (Ipv6Addr, u16) {
type Iter = option::IntoIter<SocketAddr>;
fn to_socket_addrs(&self) -> Result<option::IntoIter<SocketAddr>, ToSocketAddrError> {
let (ip, port) = *self;
SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
}
}
impl<'a> ToSocketAddrs for &'a [SocketAddr] {
type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
fn to_socket_addrs(&self) -> Result<Self::Iter, ToSocketAddrError> {
Ok(self.iter().cloned())
}
}
impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
type Iter = T::Iter;
fn to_socket_addrs(&self) -> Result<T::Iter, ToSocketAddrError> {
(**self).to_socket_addrs()
}
}