Skip to main content

base_endpoint/
stream.rs

1// Released under the MIT License.
2// Copyright, 2026, by Samuel Williams.
3
4//! Plaintext byte-stream capabilities for established transports.
5//!
6//! These contracts describe one direction, independently of whether the
7//! transport encrypts its bytes. Packet transports retain their own message
8//! boundaries and do not implement this interface by flattening packets.
9
10use base_scheduler::{Cancellation, OperationResult, SocketStreamReader, SocketStreamWriter};
11use std::{future::Future, io};
12
13/// A sequential input direction. A nonempty read returns zero at EOF.
14/// Independent input and output directions must be able to make progress.
15pub trait ReadableStream: Send {
16    /// Read a possibly short prefix. Empty storage does not establish EOF.
17    fn read_into(
18        &mut self,
19        buffer: &mut [u8],
20        cancellation: &Cancellation,
21    ) -> impl Future<Output = OperationResult<usize>> + Send;
22
23    /// Retire this direction. Transport ownership and final closure are separate.
24    fn close(&mut self) -> impl Future<Output = io::Result<()>> + Send;
25}
26
27/// An ordered output direction. Accepted bytes must not be replayed after a
28/// cancelled flush; flush establishes delivery to the underlying transport.
29pub trait WritableStream: Send {
30    /// Accept a possibly short prefix, reporting progress before another wait.
31    fn write(
32        &mut self,
33        buffer: &[u8],
34        cancellation: &Cancellation,
35    ) -> impl Future<Output = OperationResult<usize>> + Send;
36
37    /// Deliver all previously accepted bytes, without closing the direction.
38    fn flush(
39        &mut self,
40        cancellation: &Cancellation,
41    ) -> impl Future<Output = OperationResult<()>> + Send;
42
43    /// Retire this direction. Flush first when delivery is required.
44    fn close(&mut self) -> impl Future<Output = io::Result<()>> + Send;
45}
46
47impl<R: SocketStreamReader> ReadableStream for R {
48    async fn read_into(
49        &mut self,
50        buffer: &mut [u8],
51        cancellation: &Cancellation,
52    ) -> OperationResult<usize> {
53        SocketStreamReader::read_into(self, buffer, cancellation).await
54    }
55    async fn close(&mut self) -> io::Result<()> {
56        SocketStreamReader::close(self).await
57    }
58}
59
60impl<W: SocketStreamWriter> WritableStream for W {
61    async fn write(
62        &mut self,
63        buffer: &[u8],
64        cancellation: &Cancellation,
65    ) -> OperationResult<usize> {
66        SocketStreamWriter::write(self, buffer, cancellation).await
67    }
68    async fn flush(&mut self, cancellation: &Cancellation) -> OperationResult<()> {
69        SocketStreamWriter::flush(self, cancellation).await
70    }
71    async fn close(&mut self) -> io::Result<()> {
72        SocketStreamWriter::close(self).await
73    }
74}