embassy/embassy-net/src/tcp.rs

597 lines
20 KiB
Rust
Raw Normal View History

2023-05-15 00:39:57 +02:00
//! TCP sockets.
//!
//! # Listening
//!
//! `embassy-net` does not have a `TcpListener`. Instead, individual `TcpSocket`s can be put into
//! listening mode by calling [`TcpSocket::accept`].
//!
//! Incoming connections when no socket is listening are rejected. To accept many incoming
//! connections, create many sockets and put them all into listening mode.
use core::cell::RefCell;
use core::future::poll_fn;
2021-02-03 05:09:37 +01:00
use core::mem;
2022-05-04 20:48:37 +02:00
use core::task::Poll;
2022-06-12 22:15:44 +02:00
use embassy_net_driver::Driver;
use embassy_time::Duration;
2022-05-23 03:50:43 +02:00
use smoltcp::iface::{Interface, SocketHandle};
use smoltcp::socket::tcp;
pub use smoltcp::socket::tcp::State;
2022-06-12 22:15:44 +02:00
use smoltcp::wire::{IpEndpoint, IpListenEndpoint};
2022-05-23 03:50:43 +02:00
use crate::time::duration_to_smoltcp;
2022-12-07 16:02:28 +01:00
use crate::{SocketStack, Stack};
2021-02-03 05:09:37 +01:00
2023-05-15 00:39:57 +02:00
/// Error returned by TcpSocket read/write functions.
2022-05-04 20:48:37 +02:00
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
2023-05-15 00:39:57 +02:00
/// The connection was reset.
///
/// This can happen on receiving a RST packet, or on timeout.
2022-05-04 20:48:37 +02:00
ConnectionReset,
}
2023-05-15 00:39:57 +02:00
/// Error returned by [`TcpSocket::connect`].
2022-05-04 20:48:37 +02:00
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ConnectError {
/// The socket is already connected or listening.
InvalidState,
/// The remote host rejected the connection with a RST packet.
ConnectionReset,
/// Connect timed out.
TimedOut,
/// No route to host.
NoRoute,
}
2023-05-15 00:39:57 +02:00
/// Error returned by [`TcpSocket::accept`].
2022-05-04 20:48:37 +02:00
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum AcceptError {
/// The socket is already connected or listening.
InvalidState,
/// Invalid listen port
InvalidPort,
/// The remote host rejected the connection with a RST packet.
ConnectionReset,
}
2021-02-03 05:09:37 +01:00
2023-05-15 00:39:57 +02:00
/// A TCP socket.
2021-02-03 05:09:37 +01:00
pub struct TcpSocket<'a> {
2022-05-23 03:50:43 +02:00
io: TcpIo<'a>,
2021-02-03 05:09:37 +01:00
}
2023-05-15 00:39:57 +02:00
/// The reader half of a TCP socket.
2022-05-13 22:15:27 +02:00
pub struct TcpReader<'a> {
2022-05-23 03:50:43 +02:00
io: TcpIo<'a>,
2022-05-13 22:15:27 +02:00
}
2023-05-15 00:39:57 +02:00
/// The writer half of a TCP socket.
2022-05-13 22:15:27 +02:00
pub struct TcpWriter<'a> {
2022-05-23 03:50:43 +02:00
io: TcpIo<'a>,
2022-05-13 22:15:27 +02:00
}
impl<'a> TcpReader<'a> {
2023-05-15 00:39:57 +02:00
/// Read data from the socket.
///
/// Returns how many bytes were read, or an error. If no data is available, it waits
/// until there is at least one byte available.
pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
self.io.read(buf).await
}
}
impl<'a> TcpWriter<'a> {
2023-05-15 00:39:57 +02:00
/// Write data to the socket.
///
/// Returns how many bytes were written, or an error. If the socket is not ready to
/// accept data, it waits until it is.
pub async fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
self.io.write(buf).await
}
2023-05-15 00:39:57 +02:00
/// Flushes the written data to the socket.
///
/// This waits until all data has been sent, and ACKed by the remote host. For a connection
/// closed with [`abort()`](TcpSocket::abort) it will wait for the TCP RST packet to be sent.
pub async fn flush(&mut self) -> Result<(), Error> {
self.io.flush().await
}
}
2021-02-03 05:09:37 +01:00
impl<'a> TcpSocket<'a> {
2023-05-15 00:39:57 +02:00
/// Create a new TCP socket on the given stack, with the given buffers.
pub fn new<D: Driver>(stack: &'a Stack<D>, rx_buffer: &'a mut [u8], tx_buffer: &'a mut [u8]) -> Self {
let s = &mut *stack.socket.borrow_mut();
2022-05-23 03:50:43 +02:00
let rx_buffer: &'static mut [u8] = unsafe { mem::transmute(rx_buffer) };
let tx_buffer: &'static mut [u8] = unsafe { mem::transmute(tx_buffer) };
let handle = s.sockets.add(tcp::Socket::new(
tcp::SocketBuffer::new(rx_buffer),
tcp::SocketBuffer::new(tx_buffer),
));
2021-02-03 05:09:37 +01:00
Self {
2022-05-23 03:50:43 +02:00
io: TcpIo {
stack: &stack.socket,
handle,
},
2021-02-03 05:09:37 +01:00
}
}
2023-05-15 00:39:57 +02:00
/// Split the socket into reader and a writer halves.
2022-05-13 22:15:27 +02:00
pub fn split(&mut self) -> (TcpReader<'_>, TcpWriter<'_>) {
2022-05-23 03:50:43 +02:00
(TcpReader { io: self.io }, TcpWriter { io: self.io })
2022-05-13 22:15:27 +02:00
}
2023-05-15 00:39:57 +02:00
/// Connect to a remote host.
2022-05-04 20:48:37 +02:00
pub async fn connect<T>(&mut self, remote_endpoint: T) -> Result<(), ConnectError>
2021-02-03 05:09:37 +01:00
where
T: Into<IpEndpoint>,
{
let local_port = self.io.stack.borrow_mut().get_local_port();
2022-05-23 03:50:43 +02:00
2022-12-07 00:28:38 +01:00
match {
self.io
.with_mut(|s, i| s.connect(i.context(), remote_endpoint, local_port))
} {
2022-05-04 20:48:37 +02:00
Ok(()) => {}
2022-05-23 03:50:43 +02:00
Err(tcp::ConnectError::InvalidState) => return Err(ConnectError::InvalidState),
Err(tcp::ConnectError::Unaddressable) => return Err(ConnectError::NoRoute),
2022-05-04 20:48:37 +02:00
}
2021-02-03 05:09:37 +01:00
poll_fn(|cx| {
2022-05-23 03:50:43 +02:00
self.io.with_mut(|s, _| match s.state() {
2022-06-12 22:15:44 +02:00
tcp::State::Closed | tcp::State::TimeWait => Poll::Ready(Err(ConnectError::ConnectionReset)),
2022-05-23 03:50:43 +02:00
tcp::State::Listen => unreachable!(),
tcp::State::SynSent | tcp::State::SynReceived => {
2021-02-03 05:09:37 +01:00
s.register_send_waker(cx.waker());
Poll::Pending
}
_ => Poll::Ready(Ok(())),
})
})
.await
}
2023-05-15 00:39:57 +02:00
/// Accept a connection from a remote host.
///
/// This function puts the socket in listening mode, and waits until a connection is received.
2022-05-04 20:48:37 +02:00
pub async fn accept<T>(&mut self, local_endpoint: T) -> Result<(), AcceptError>
2021-11-04 13:34:13 +01:00
where
2022-05-23 03:50:43 +02:00
T: Into<IpListenEndpoint>,
2021-11-04 13:34:13 +01:00
{
match self.io.with_mut(|s, _| s.listen(local_endpoint)) {
2022-05-04 20:48:37 +02:00
Ok(()) => {}
2022-05-23 03:50:43 +02:00
Err(tcp::ListenError::InvalidState) => return Err(AcceptError::InvalidState),
Err(tcp::ListenError::Unaddressable) => return Err(AcceptError::InvalidPort),
2022-05-04 20:48:37 +02:00
}
2021-11-04 13:34:13 +01:00
poll_fn(|cx| {
2022-05-23 03:50:43 +02:00
self.io.with_mut(|s, _| match s.state() {
tcp::State::Listen | tcp::State::SynSent | tcp::State::SynReceived => {
2021-11-04 13:34:13 +01:00
s.register_send_waker(cx.waker());
Poll::Pending
}
_ => Poll::Ready(Ok(())),
})
})
.await
}
2023-05-15 00:39:57 +02:00
/// Read data from the socket.
///
/// Returns how many bytes were read, or an error. If no data is available, it waits
/// until there is at least one byte available.
pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
self.io.read(buf).await
}
2023-05-15 00:39:57 +02:00
/// Write data to the socket.
///
/// Returns how many bytes were written, or an error. If the socket is not ready to
/// accept data, it waits until it is.
pub async fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
self.io.write(buf).await
}
2023-05-15 00:39:57 +02:00
/// Flushes the written data to the socket.
///
/// This waits until all data has been sent, and ACKed by the remote host. For a connection
/// closed with [`abort()`](TcpSocket::abort) it will wait for the TCP RST packet to be sent.
pub async fn flush(&mut self) -> Result<(), Error> {
self.io.flush().await
}
2023-05-15 00:39:57 +02:00
/// Set the timeout for the socket.
///
/// If the timeout is set, the socket will be closed if no data is received for the
/// specified duration.
2021-02-03 05:09:37 +01:00
pub fn set_timeout(&mut self, duration: Option<Duration>) {
self.io
.with_mut(|s, _| s.set_timeout(duration.map(duration_to_smoltcp)))
2021-02-03 05:09:37 +01:00
}
2023-05-15 00:39:57 +02:00
/// Set the keep-alive interval for the socket.
///
/// If the keep-alive interval is set, the socket will send keep-alive packets after
/// the specified duration of inactivity.
///
/// If not set, the socket will not send keep-alive packets.
2021-02-03 05:09:37 +01:00
pub fn set_keep_alive(&mut self, interval: Option<Duration>) {
self.io
.with_mut(|s, _| s.set_keep_alive(interval.map(duration_to_smoltcp)))
2021-02-03 05:09:37 +01:00
}
2023-05-15 00:39:57 +02:00
/// Set the hop limit field in the IP header of sent packets.
2021-02-03 05:09:37 +01:00
pub fn set_hop_limit(&mut self, hop_limit: Option<u8>) {
self.io.with_mut(|s, _| s.set_hop_limit(hop_limit))
2021-02-03 05:09:37 +01:00
}
2023-05-15 00:39:57 +02:00
/// Get the local endpoint of the socket.
///
/// Returns `None` if the socket is not bound (listening) or not connected.
2022-05-23 03:50:43 +02:00
pub fn local_endpoint(&self) -> Option<IpEndpoint> {
self.io.with(|s, _| s.local_endpoint())
2021-02-03 05:09:37 +01:00
}
2023-05-15 00:39:57 +02:00
/// Get the remote endpoint of the socket.
///
/// Returns `None` if the socket is not connected.
2022-05-23 03:50:43 +02:00
pub fn remote_endpoint(&self) -> Option<IpEndpoint> {
self.io.with(|s, _| s.remote_endpoint())
2021-02-03 05:09:37 +01:00
}
2023-05-15 00:39:57 +02:00
/// Get the state of the socket.
pub fn state(&self) -> State {
self.io.with(|s, _| s.state())
2021-02-03 05:09:37 +01:00
}
2023-05-15 00:39:57 +02:00
/// Close the write half of the socket.
///
/// This closes only the write half of the socket. The read half side remains open, the
/// socket can still receive data.
///
/// Data that has been written to the socket and not yet sent (or not yet ACKed) will still
/// still sent. The last segment of the pending to send data is sent with the FIN flag set.
2021-02-03 05:09:37 +01:00
pub fn close(&mut self) {
self.io.with_mut(|s, _| s.close())
2021-02-03 05:09:37 +01:00
}
2023-05-15 00:39:57 +02:00
/// Forcibly close the socket.
///
/// This instantly closes both the read and write halves of the socket. Any pending data
/// that has not been sent will be lost.
///
/// Note that the TCP RST packet is not sent immediately - if the `TcpSocket` is dropped too soon
/// the remote host may not know the connection has been closed.
/// `abort()` callers should wait for a [`flush()`](TcpSocket::flush) call to complete before
/// dropping or reusing the socket.
2021-02-03 05:09:37 +01:00
pub fn abort(&mut self) {
self.io.with_mut(|s, _| s.abort())
2021-02-03 05:09:37 +01:00
}
2023-05-15 00:39:57 +02:00
/// Get whether the socket is ready to send data, i.e. whether there is space in the send buffer.
2021-02-03 05:09:37 +01:00
pub fn may_send(&self) -> bool {
self.io.with(|s, _| s.may_send())
2021-02-03 05:09:37 +01:00
}
2023-05-15 00:39:57 +02:00
/// Get whether the socket is ready to receive data, i.e. whether there is some pending data in the receive buffer.
2021-02-03 05:09:37 +01:00
pub fn may_recv(&self) -> bool {
self.io.with(|s, _| s.may_recv())
2021-02-03 05:09:37 +01:00
}
2022-05-13 22:15:27 +02:00
}
2021-02-03 05:09:37 +01:00
impl<'a> Drop for TcpSocket<'a> {
fn drop(&mut self) {
self.io.stack.borrow_mut().sockets.remove(self.io.handle);
2021-02-03 05:09:37 +01:00
}
}
2022-05-23 03:50:43 +02:00
// =======================
2021-02-03 05:09:37 +01:00
2022-05-23 03:50:43 +02:00
#[derive(Copy, Clone)]
struct TcpIo<'a> {
stack: &'a RefCell<SocketStack>,
2022-05-23 03:50:43 +02:00
handle: SocketHandle,
2021-02-03 05:09:37 +01:00
}
2022-05-13 22:15:27 +02:00
2022-05-23 03:50:43 +02:00
impl<'d> TcpIo<'d> {
fn with<R>(&self, f: impl FnOnce(&tcp::Socket, &Interface) -> R) -> R {
let s = &*self.stack.borrow();
2022-05-23 03:50:43 +02:00
let socket = s.sockets.get::<tcp::Socket>(self.handle);
f(socket, &s.iface)
}
fn with_mut<R>(&mut self, f: impl FnOnce(&mut tcp::Socket, &mut Interface) -> R) -> R {
let s = &mut *self.stack.borrow_mut();
2022-05-23 03:50:43 +02:00
let socket = s.sockets.get_mut::<tcp::Socket>(self.handle);
let res = f(socket, &mut s.iface);
s.waker.wake();
res
}
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
poll_fn(move |cx| {
// CAUTION: smoltcp semantics around EOF are different to what you'd expect
// from posix-like IO, so we have to tweak things here.
2022-05-23 03:50:43 +02:00
self.with_mut(|s, _| match s.recv_slice(buf) {
// No data ready
Ok(0) => {
s.register_recv_waker(cx.waker());
Poll::Pending
}
// Data ready!
Ok(n) => Poll::Ready(Ok(n)),
// EOF
2022-05-23 03:50:43 +02:00
Err(tcp::RecvError::Finished) => Poll::Ready(Ok(0)),
// Connection reset. TODO: this can also be timeouts etc, investigate.
2022-05-23 03:50:43 +02:00
Err(tcp::RecvError::InvalidState) => Poll::Ready(Err(Error::ConnectionReset)),
})
})
2022-05-23 03:50:43 +02:00
.await
}
2022-05-23 03:50:43 +02:00
async fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
poll_fn(move |cx| {
2022-05-23 03:50:43 +02:00
self.with_mut(|s, _| match s.send_slice(buf) {
// Not ready to send (no space in the tx buffer)
Ok(0) => {
s.register_send_waker(cx.waker());
Poll::Pending
}
// Some data sent
Ok(n) => Poll::Ready(Ok(n)),
// Connection reset. TODO: this can also be timeouts etc, investigate.
2022-05-23 03:50:43 +02:00
Err(tcp::SendError::InvalidState) => Poll::Ready(Err(Error::ConnectionReset)),
})
})
2022-05-23 03:50:43 +02:00
.await
}
async fn flush(&mut self) -> Result<(), Error> {
2023-02-22 13:57:40 +01:00
poll_fn(move |cx| {
self.with_mut(|s, _| {
let waiting_close = s.state() == tcp::State::Closed && s.remote_endpoint().is_some();
2023-02-22 13:57:40 +01:00
// If there are outstanding send operations, register for wake up and wait
// smoltcp issues wake-ups when octets are dequeued from the send buffer
if s.send_queue() > 0 || waiting_close {
2023-02-22 13:57:40 +01:00
s.register_send_waker(cx.waker());
Poll::Pending
// No outstanding sends, socket is flushed
} else {
Poll::Ready(Ok(()))
}
})
2022-05-23 03:50:43 +02:00
})
.await
}
}
#[cfg(feature = "nightly")]
mod embedded_io_impls {
use super::*;
impl embedded_io::Error for ConnectError {
fn kind(&self) -> embedded_io::ErrorKind {
embedded_io::ErrorKind::Other
}
}
impl embedded_io::Error for Error {
fn kind(&self) -> embedded_io::ErrorKind {
embedded_io::ErrorKind::Other
}
2022-05-23 03:50:43 +02:00
}
impl<'d> embedded_io::Io for TcpSocket<'d> {
type Error = Error;
}
2022-05-23 03:50:43 +02:00
impl<'d> embedded_io::asynch::Read for TcpSocket<'d> {
2022-11-21 23:31:31 +01:00
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
self.io.read(buf).await
}
2022-05-23 03:50:43 +02:00
}
impl<'d> embedded_io::asynch::Write for TcpSocket<'d> {
2022-11-21 23:31:31 +01:00
async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
self.io.write(buf).await
}
2022-11-21 23:31:31 +01:00
async fn flush(&mut self) -> Result<(), Self::Error> {
self.io.flush().await
}
}
impl<'d> embedded_io::Io for TcpReader<'d> {
type Error = Error;
}
2022-05-13 22:15:27 +02:00
impl<'d> embedded_io::asynch::Read for TcpReader<'d> {
2022-11-21 23:31:31 +01:00
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
self.io.read(buf).await
}
}
impl<'d> embedded_io::Io for TcpWriter<'d> {
type Error = Error;
}
impl<'d> embedded_io::asynch::Write for TcpWriter<'d> {
2022-11-21 23:31:31 +01:00
async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
self.io.write(buf).await
}
2022-11-21 23:31:31 +01:00
async fn flush(&mut self) -> Result<(), Self::Error> {
self.io.flush().await
}
}
}
2023-05-15 00:39:57 +02:00
/// TCP client compatible with `embedded-nal-async` traits.
#[cfg(all(feature = "unstable-traits", feature = "nightly"))]
pub mod client {
use core::cell::UnsafeCell;
use core::mem::MaybeUninit;
use core::ptr::NonNull;
use atomic_polyfill::{AtomicBool, Ordering};
use embedded_nal_async::IpAddr;
use super::*;
2023-05-15 00:39:57 +02:00
/// TCP client connection pool compatible with `embedded-nal-async` traits.
///
/// The pool is capable of managing up to N concurrent connections with tx and rx buffers according to TX_SZ and RX_SZ.
pub struct TcpClient<'d, D: Driver, const N: usize, const TX_SZ: usize = 1024, const RX_SZ: usize = 1024> {
stack: &'d Stack<D>,
2022-08-09 14:43:55 +02:00
state: &'d TcpClientState<N, TX_SZ, RX_SZ>,
}
impl<'d, D: Driver, const N: usize, const TX_SZ: usize, const RX_SZ: usize> TcpClient<'d, D, N, TX_SZ, RX_SZ> {
2023-05-15 00:39:57 +02:00
/// Create a new `TcpClient`.
2022-08-09 14:43:55 +02:00
pub fn new(stack: &'d Stack<D>, state: &'d TcpClientState<N, TX_SZ, RX_SZ>) -> Self {
Self { stack, state }
}
}
impl<'d, D: Driver, const N: usize, const TX_SZ: usize, const RX_SZ: usize> embedded_nal_async::TcpConnect
for TcpClient<'d, D, N, TX_SZ, RX_SZ>
{
type Error = Error;
type Connection<'m> = TcpConnection<'m, N, TX_SZ, RX_SZ> where Self: 'm;
2022-11-21 23:31:31 +01:00
async fn connect<'a>(
&'a self,
remote: embedded_nal_async::SocketAddr,
) -> Result<Self::Connection<'a>, Self::Error>
where
Self: 'a,
{
let addr: crate::IpAddress = match remote.ip() {
IpAddr::V4(addr) => crate::IpAddress::Ipv4(crate::Ipv4Address::from_bytes(&addr.octets())),
#[cfg(feature = "proto-ipv6")]
IpAddr::V6(addr) => crate::IpAddress::Ipv6(crate::Ipv6Address::from_bytes(&addr.octets())),
#[cfg(not(feature = "proto-ipv6"))]
IpAddr::V6(_) => panic!("ipv6 support not enabled"),
};
let remote_endpoint = (addr, remote.port());
let mut socket = TcpConnection::new(&self.stack, self.state)?;
socket
.socket
.connect(remote_endpoint)
.await
.map_err(|_| Error::ConnectionReset)?;
Ok(socket)
}
}
2023-05-15 00:39:57 +02:00
/// Opened TCP connection in a [`TcpClient`].
pub struct TcpConnection<'d, const N: usize, const TX_SZ: usize, const RX_SZ: usize> {
socket: TcpSocket<'d>,
2022-08-09 14:43:55 +02:00
state: &'d TcpClientState<N, TX_SZ, RX_SZ>,
bufs: NonNull<([u8; TX_SZ], [u8; RX_SZ])>,
}
impl<'d, const N: usize, const TX_SZ: usize, const RX_SZ: usize> TcpConnection<'d, N, TX_SZ, RX_SZ> {
fn new<D: Driver>(stack: &'d Stack<D>, state: &'d TcpClientState<N, TX_SZ, RX_SZ>) -> Result<Self, Error> {
2022-08-09 14:43:55 +02:00
let mut bufs = state.pool.alloc().ok_or(Error::ConnectionReset)?;
Ok(Self {
socket: unsafe { TcpSocket::new(stack, &mut bufs.as_mut().1, &mut bufs.as_mut().0) },
2022-08-09 14:43:55 +02:00
state,
bufs,
})
}
}
impl<'d, const N: usize, const TX_SZ: usize, const RX_SZ: usize> Drop for TcpConnection<'d, N, TX_SZ, RX_SZ> {
fn drop(&mut self) {
unsafe {
self.socket.close();
2022-08-09 14:43:55 +02:00
self.state.pool.free(self.bufs);
}
}
}
impl<'d, const N: usize, const TX_SZ: usize, const RX_SZ: usize> embedded_io::Io
for TcpConnection<'d, N, TX_SZ, RX_SZ>
{
type Error = Error;
}
impl<'d, const N: usize, const TX_SZ: usize, const RX_SZ: usize> embedded_io::asynch::Read
for TcpConnection<'d, N, TX_SZ, RX_SZ>
{
2022-11-21 23:31:31 +01:00
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
self.socket.read(buf).await
}
}
impl<'d, const N: usize, const TX_SZ: usize, const RX_SZ: usize> embedded_io::asynch::Write
for TcpConnection<'d, N, TX_SZ, RX_SZ>
{
2022-11-21 23:31:31 +01:00
async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
self.socket.write(buf).await
}
2022-11-21 23:31:31 +01:00
async fn flush(&mut self) -> Result<(), Self::Error> {
self.socket.flush().await
}
}
2022-08-09 14:43:55 +02:00
/// State for TcpClient
pub struct TcpClientState<const N: usize, const TX_SZ: usize, const RX_SZ: usize> {
pool: Pool<([u8; TX_SZ], [u8; RX_SZ]), N>,
}
2022-08-09 14:43:55 +02:00
impl<const N: usize, const TX_SZ: usize, const RX_SZ: usize> TcpClientState<N, TX_SZ, RX_SZ> {
2023-05-15 00:39:57 +02:00
/// Create a new `TcpClientState`.
2022-08-09 14:43:55 +02:00
pub const fn new() -> Self {
2022-08-09 14:51:32 +02:00
Self { pool: Pool::new() }
2022-08-09 14:43:55 +02:00
}
}
unsafe impl<const N: usize, const TX_SZ: usize, const RX_SZ: usize> Sync for TcpClientState<N, TX_SZ, RX_SZ> {}
struct Pool<T, const N: usize> {
used: [AtomicBool; N],
data: [UnsafeCell<MaybeUninit<T>>; N],
}
impl<T, const N: usize> Pool<T, N> {
const VALUE: AtomicBool = AtomicBool::new(false);
const UNINIT: UnsafeCell<MaybeUninit<T>> = UnsafeCell::new(MaybeUninit::uninit());
2022-08-09 14:43:55 +02:00
const fn new() -> Self {
Self {
used: [Self::VALUE; N],
data: [Self::UNINIT; N],
}
}
}
impl<T, const N: usize> Pool<T, N> {
fn alloc(&self) -> Option<NonNull<T>> {
for n in 0..N {
if self.used[n].swap(true, Ordering::SeqCst) == false {
let p = self.data[n].get() as *mut T;
return Some(unsafe { NonNull::new_unchecked(p) });
}
}
None
}
/// safety: p must be a pointer obtained from self.alloc that hasn't been freed yet.
unsafe fn free(&self, p: NonNull<T>) {
let origin = self.data.as_ptr() as *mut T;
let n = p.as_ptr().offset_from(origin);
assert!(n >= 0);
assert!((n as usize) < N);
self.used[n as usize].store(false, Ordering::SeqCst);
}
}
}