moduvex_runtime/net/mod.rs
1//! Async networking: TCP listener, TCP stream, UDP socket.
2//!
3//! # Traits
4//! - [`AsyncRead`] — poll-based non-blocking read
5//! - [`AsyncWrite`] — poll-based non-blocking write + flush + shutdown
6//!
7//! # Types
8//! - [`TcpListener`] — accepts incoming TCP connections
9//! - [`TcpStream`] — bidirectional async byte stream
10//! - [`UdpSocket`] — connectionless async datagram socket
11
12use std::io;
13use std::pin::Pin;
14use std::task::{Context, Poll};
15
16pub mod sockaddr;
17pub mod tcp_listener;
18pub mod tcp_stream;
19pub mod udp_socket;
20
21pub use tcp_listener::TcpListener;
22pub use tcp_stream::TcpStream;
23pub use udp_socket::UdpSocket;
24
25// ── AsyncRead ─────────────────────────────────────────────────────────────────
26
27/// Async version of `std::io::Read`.
28///
29/// The poll method must be called with a pinned `Self` and a `Context`.
30/// It returns `Poll::Ready(Ok(n))` when `n` bytes have been written into
31/// `buf`, or `Poll::Pending` when no bytes are available yet (the waker
32/// will be called when data arrives).
33pub trait AsyncRead {
34 /// Attempt to read bytes into `buf`.
35 ///
36 /// On success returns `Poll::Ready(Ok(n))` where `n` is the number of
37 /// bytes read. `n == 0` signals EOF. Returns `Poll::Pending` and
38 /// arranges for the waker to be called on the next read-readiness event.
39 fn poll_read(
40 self: Pin<&mut Self>,
41 cx: &mut Context<'_>,
42 buf: &mut [u8],
43 ) -> Poll<io::Result<usize>>;
44}
45
46// ── AsyncWrite ────────────────────────────────────────────────────────────────
47
48/// Async version of `std::io::Write`.
49///
50/// All three poll methods follow the same contract: `Poll::Ready(Ok(...))`
51/// on success, `Poll::Pending` when the underlying resource is not ready
52/// (with the waker arranged to fire when it becomes ready).
53pub trait AsyncWrite {
54 /// Attempt to write bytes from `buf` into the sink.
55 ///
56 /// Returns the number of bytes written. May be less than `buf.len()`.
57 fn poll_write(
58 self: Pin<&mut Self>,
59 cx: &mut Context<'_>,
60 buf: &[u8],
61 ) -> Poll<io::Result<usize>>;
62
63 /// Flush any internal buffers to the OS.
64 ///
65 /// For kernel-backed sockets this is a no-op that returns `Ready(Ok(()))`.
66 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
67
68 /// Initiate a half-close: shut down the write side of the connection.
69 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
70}