Skip to main content

dope_core/io/socket/addr/
mod.rs

1pub(in crate::io::socket) mod inet;
2pub(in crate::io::socket) mod prepared;
3pub(in crate::io::socket) mod unix;
4
5use std::{net, os::fd};
6
7use dope_sys::{Errno, io::socket::addr};
8
9use crate::{Backend, io::socket};
10
11#[derive(Clone, Copy)]
12#[repr(transparent)]
13pub struct Addr(addr::Storage<addr::Socklen>);
14
15impl Addr {
16    pub fn from_std(address: net::SocketAddr) -> Self {
17        let native = addr::Internet::from_std::<Backend>(address);
18        Self(addr::Storage::from_addr(native.as_addr()))
19    }
20
21    /// Copies an already-prepared socket address.
22    pub fn copy_from<A: socket::Prepared>(addr: &A) -> Self {
23        Self(addr::Storage::from_addr(addr.view().native()))
24    }
25
26    pub fn into_std(self) -> Result<net::SocketAddr, socket::Error> {
27        self.0.to_std().map_err(socket::Error::from)
28    }
29
30    /// Reads the local address bound to a descriptor.
31    pub fn local(fd: fd::BorrowedFd<'_>) -> Result<Self, addr::Local<Errno>> {
32        let mut buffer = addr::Storage::<addr::Length>::empty();
33        let view = addr::Addr::local::<Backend, Errno>(fd, &mut buffer)?;
34        Ok(Self(addr::Storage::from_addr(view)))
35    }
36
37    pub(crate) const STORAGE_CAPACITY: usize = addr::CAPACITY;
38
39    pub(crate) fn try_parse(name: &[u8]) -> Result<net::SocketAddr, socket::Error> {
40        addr::Internet::try_parse(name).map_err(socket::Error::from)
41    }
42}