dope_core/io/socket/addr/
inet.rs1use std::{
2 cell, marker,
3 mem::MaybeUninit,
4 net,
5 os::{fd, fd::AsFd as _},
6};
7
8use dope_sys::{
9 Errno,
10 io::socket::{BACKLOG, Kind, Socket as _, addr},
11};
12
13use crate::{
14 Backend,
15 io::socket::{BindError, Prepared, StreamSpec, addr::prepared},
16};
17
18#[derive(Clone, Copy)]
19pub struct Inet {
20 native: addr::Internet,
21}
22
23#[must_use]
25pub struct Listener {
26 fd: fd::OwnedFd,
27 local_addr: net::SocketAddr,
28 thread: marker::PhantomData<cell::Cell<()>>,
29}
30
31impl Listener {
32 pub fn bind(addr: net::SocketAddr) -> Result<Self, BindError> {
34 let address = Inet::from(&addr);
35 let domain = address.stream_spec().domain().raw();
36 let fd = Backend::socket(domain, Kind::Stream.raw()).map_err(BindError::Socket)?;
37 let borrowed = fd.as_fd();
38 address
39 .view()
40 .native()
41 .try_bind::<Backend, Errno>(borrowed)
42 .map_err(BindError::Bind)?;
43 Backend::listen::<Errno>(borrowed, BACKLOG).map_err(BindError::Listen)?;
44 let local = prepared::View::local(borrowed, &mut addr::Storage::empty())
45 .map_err(BindError::LocalAddress)?
46 .into_std()
47 .map_err(BindError::Address)?;
48 Ok(Self {
49 fd,
50 local_addr: local,
51 thread: marker::PhantomData,
52 })
53 }
54
55 pub const fn local_addr(&self) -> net::SocketAddr {
56 self.local_addr
57 }
58
59 pub(in crate::io::socket) fn into_parts(self) -> (fd::OwnedFd, net::SocketAddr) {
60 (self.fd, self.local_addr)
61 }
62}
63
64impl Inet {
65 pub fn from_std<'out>(
66 address: &net::SocketAddr,
67 out: &'out mut MaybeUninit<Self>,
68 ) -> &'out mut Self {
69 out.write(Self {
70 native: addr::Internet::from_std::<Backend>(address),
71 })
72 }
73}
74
75impl From<&net::SocketAddr> for Inet {
76 fn from(address: &net::SocketAddr) -> Self {
77 *Self::from_std(address, &mut MaybeUninit::uninit())
78 }
79}
80
81impl prepared::Sealed for Inet {}
82
83impl Prepared for Inet {
84 fn view(&self) -> prepared::View<'_> {
85 prepared::View(self.native.as_addr())
86 }
87
88 fn stream_spec(&self) -> StreamSpec {
89 StreamSpec(self.native.domain())
90 }
91}
92
93const _: () = assert!(size_of::<Inet>() <= 32);
94
95impl Inet {
96 pub fn try_connect(&self, fd: fd::BorrowedFd<'_>) -> Result<(), crate::Errno> {
98 self.view().native().try_connect::<Backend, Errno>(fd)
99 }
100}