Skip to main content

iphone_cli/tcp/
stream.rs

1//! Lifetime-bound stream over a borrowed [`Adapter`].
2//!
3//! [`AdapterStream`] wraps a `&mut Adapter` reference, so it borrows the adapter
4//! exclusively for its entire lifetime.  This is the **lowest-overhead** way to
5//! use the stack when all of the following are true:
6//!
7//! - You open **one connection at a time** on the adapter.
8//! - The stream lives entirely within a **single async task**.
9//! - You do **not** need to store the stream alongside other owned data in a
10//!   struct (the lifetime parameter `'a` would appear in the struct definition).
11//!
12//! If any of those constraints are inconvenient, use
13//! [`crate::tcp::handle::AdapterHandle`] / [`crate::tcp::handle::StreamHandle`] instead.
14
15use std::{future::Future, task::Poll};
16
17use tokio::io::{AsyncRead, AsyncWrite};
18use tracing::trace;
19
20use crate::tcp::adapter::ConnectionStatus;
21
22use crate::tcp::adapter::Adapter;
23
24#[derive(Debug)]
25pub struct AdapterStream<'a> {
26    pub(crate) adapter: &'a mut Adapter,
27    pub host_port: u16,
28    pub peer_port: u16,
29}
30
31impl<'a> AdapterStream<'a> {
32    /// Connect to the specified port
33    pub async fn connect(adapter: &'a mut Adapter, port: u16) -> Result<Self, std::io::Error> {
34        let host_port = adapter.connect(port).await?;
35        Ok(Self {
36            adapter,
37            host_port,
38            peer_port: port,
39        })
40    }
41
42    /// Gracefully closes the stream
43    pub async fn close(&mut self) -> Result<(), std::io::Error> {
44        self.adapter.close(self.host_port).await
45    }
46
47    /// Sends data to the target
48    pub async fn psh(&mut self, payload: &[u8]) -> Result<(), std::io::Error> {
49        self.adapter.queue_send(payload, self.host_port)?;
50        self.adapter.write_buffer_flush().await?;
51        Ok(())
52    }
53
54    pub async fn recv(&mut self) -> Result<Vec<u8>, std::io::Error> {
55        self.adapter.recv(self.host_port).await
56    }
57}
58
59impl AsyncRead for AdapterStream<'_> {
60    fn poll_read(
61        mut self: std::pin::Pin<&mut Self>,
62        cx: &mut std::task::Context<'_>,
63        buf: &mut tokio::io::ReadBuf<'_>,
64    ) -> std::task::Poll<std::io::Result<()>> {
65        match self.adapter.get_status(self.host_port) {
66            Ok(ConnectionStatus::Error(e)) => {
67                return std::task::Poll::Ready(Err(std::io::Error::new(e, "io error")));
68            }
69            Err(e) => {
70                return std::task::Poll::Ready(Err(e));
71            }
72            _ => {}
73        }
74
75        // First, check if we have any cached data
76        let p = self.host_port;
77        let cache = match self.adapter.uncache(buf.remaining(), p) {
78            Ok(c) => c,
79            Err(e) => return std::task::Poll::Ready(Err(e)),
80        };
81        if !cache.is_empty() {
82            buf.put_slice(&cache);
83            return std::task::Poll::Ready(Ok(()));
84        }
85
86        // If no cached data, try to receive new data
87        let future = async {
88            match self.adapter.recv(p).await {
89                Ok(data) => {
90                    let len = std::cmp::min(buf.remaining(), data.len());
91                    buf.put_slice(&data[..len]);
92
93                    // If we received more data than needed, cache the rest
94                    if len < data.len() {
95                        self.adapter.cache_read(&data[len..], p)?
96                    }
97
98                    Ok(())
99                }
100                Err(e) => Err(e),
101            }
102        };
103
104        // Pin the future and poll it
105        futures_util::pin_mut!(future);
106        future.poll(cx)
107    }
108}
109
110impl AsyncWrite for AdapterStream<'_> {
111    fn poll_write(
112        mut self: std::pin::Pin<&mut Self>,
113        _cx: &mut std::task::Context<'_>,
114        buf: &[u8],
115    ) -> std::task::Poll<Result<usize, std::io::Error>> {
116        trace!("poll psh {}", buf.len());
117        match self.adapter.get_status(self.host_port) {
118            Ok(ConnectionStatus::Error(e)) => {
119                return std::task::Poll::Ready(Err(std::io::Error::new(e, "io error")));
120            }
121            Err(e) => {
122                return std::task::Poll::Ready(Err(e));
123            }
124            _ => {}
125        }
126        let p = self.host_port;
127        match self.adapter.queue_send(buf, p) {
128            Ok(_) => Poll::Ready(Ok(buf.len())),
129            Err(e) => Poll::Ready(Err(e)),
130        }
131    }
132
133    fn poll_flush(
134        mut self: std::pin::Pin<&mut Self>,
135        cx: &mut std::task::Context<'_>,
136    ) -> std::task::Poll<Result<(), std::io::Error>> {
137        let future = async {
138            match self.adapter.write_buffer_flush().await {
139                Ok(_) => Ok(()),
140                Err(e) => Err(e),
141            }
142        };
143
144        // Pin the future and poll it
145        futures_util::pin_mut!(future);
146        future.poll(cx)
147    }
148
149    fn poll_shutdown(
150        mut self: std::pin::Pin<&mut Self>,
151        cx: &mut std::task::Context<'_>,
152    ) -> std::task::Poll<Result<(), std::io::Error>> {
153        // Create a future that can be polled
154        let future = async { self.close().await };
155
156        // Pin the future and poll it
157        futures_util::pin_mut!(future);
158        future.poll(cx)
159    }
160}
161
162impl Drop for AdapterStream<'_> {
163    fn drop(&mut self) {
164        self.adapter.connection_drop(self.host_port);
165    }
166}