noq/recv_stream.rs
1use std::{
2 future::{Future, poll_fn},
3 io,
4 pin::Pin,
5 task::{Context, Poll, ready},
6};
7
8use bytes::Bytes;
9use proto::{Chunk, Chunks, ClosedStream, ConnectionError, ReadableError, StreamId};
10use thiserror::Error;
11use tokio::io::ReadBuf;
12
13use crate::{VarInt, connection::ConnectionRef};
14
15/// A stream that can only be used to receive data
16///
17/// `stop(0)` is implicitly called on drop unless:
18/// - A variant of [`ReadError`] has been yielded by a read call
19/// - [`stop()`] was called explicitly
20///
21/// # Cancellation
22///
23/// A `read` method is said to be *cancel-safe* when dropping its future before the future becomes
24/// ready cannot lead to loss of stream data. This is true of methods which succeed immediately when
25/// any progress is made, and is not true of methods which might need to perform multiple reads
26/// internally before succeeding. Each `read` method documents whether it is cancel-safe.
27///
28/// # Common issues
29///
30/// ## Data never received on a locally-opened stream
31///
32/// Peers are not notified of streams until they or a later-numbered stream are used to send
33/// data. If a bidirectional stream is locally opened but never used to send, then the peer may
34/// never see it. Application protocols should always arrange for the endpoint which will first
35/// transmit on a stream to be the endpoint responsible for opening it.
36///
37/// ## Data never received on a remotely-opened stream
38///
39/// Verify that the stream you are receiving is the same one that the server is sending on, e.g. by
40/// logging the [`id`] of each. Streams are always accepted in the same order as they are created,
41/// i.e. ascending order by [`StreamId`]. For example, even if a sender first transmits on
42/// bidirectional stream 1, the first stream yielded by [`Connection::accept_bi`] on the receiver
43/// will be bidirectional stream 0.
44///
45/// [`ReadError`]: crate::ReadError
46/// [`stop()`]: RecvStream::stop
47/// [`SendStream::finish`]: crate::SendStream::finish
48/// [`WriteError::Stopped`]: crate::WriteError::Stopped
49/// [`id`]: RecvStream::id
50/// [`Connection::accept_bi`]: crate::Connection::accept_bi
51#[derive(Debug)]
52pub struct RecvStream {
53 conn: ConnectionRef,
54 stream: StreamId,
55 is_0rtt: bool,
56 all_data_read: bool,
57 reset: Option<VarInt>,
58}
59
60impl RecvStream {
61 pub(crate) fn new(conn: ConnectionRef, stream: StreamId, is_0rtt: bool) -> Self {
62 Self {
63 conn,
64 stream,
65 is_0rtt,
66 all_data_read: false,
67 reset: None,
68 }
69 }
70
71 /// Read data contiguously from the stream.
72 ///
73 /// Yields the number of bytes read into `buf` on success, or `None` if the stream was finished.
74 ///
75 /// This operation is cancel-safe.
76 pub async fn read(&mut self, buf: &mut [u8]) -> Result<Option<usize>, ReadError> {
77 Read {
78 stream: self,
79 buf: ReadBuf::new(buf),
80 }
81 .await
82 }
83
84 /// Read an exact number of bytes contiguously from the stream.
85 ///
86 /// See [`read()`] for details. This operation is *not* cancel-safe.
87 ///
88 /// [`read()`]: RecvStream::read
89 pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), ReadExactError> {
90 ReadExact {
91 stream: self,
92 buf: ReadBuf::new(buf),
93 }
94 .await
95 }
96
97 /// Attempts to read from the stream into the provided buffer
98 ///
99 /// On success, returns `Poll::Ready(Ok(num_bytes_read))` and places data into `buf`. If this
100 /// returns zero bytes read (and `buf` has a non-zero length), that indicates that the remote
101 /// side has [`finish`]ed the stream and the local side has already read all bytes.
102 ///
103 /// If no data is available for reading, this returns `Poll::Pending` and arranges for the
104 /// current task (via `cx.waker()`) to be notified when the stream becomes readable or is
105 /// closed.
106 ///
107 /// [`finish`]: crate::SendStream::finish
108 pub fn poll_read(
109 &mut self,
110 cx: &mut Context<'_>,
111 buf: &mut [u8],
112 ) -> Poll<Result<usize, ReadError>> {
113 let mut buf = ReadBuf::new(buf);
114 ready!(self.poll_read_buf(cx, &mut buf))?;
115 Poll::Ready(Ok(buf.filled().len()))
116 }
117
118 /// Attempts to read from the stream into the provided buffer, which may be uninitialized
119 ///
120 /// On success, returns `Poll::Ready(Ok(()))` and places data into the unfilled portion of
121 /// `buf`. If this does not write any bytes to `buf` (and `buf.remaining()` is non-zero), that
122 /// indicates that the remote side has [`finish`]ed the stream and the local side has already
123 /// read all bytes.
124 ///
125 /// If no data is available for reading, this returns `Poll::Pending` and arranges for the
126 /// current task (via `cx.waker()`) to be notified when the stream becomes readable or is
127 /// closed.
128 ///
129 /// [`finish`]: crate::SendStream::finish
130 pub(crate) fn poll_read_buf(
131 &mut self,
132 cx: &mut Context<'_>,
133 buf: &mut ReadBuf<'_>,
134 ) -> Poll<Result<(), ReadError>> {
135 if buf.remaining() == 0 {
136 return Poll::Ready(Ok(()));
137 }
138
139 self.poll_read_generic(cx, true, |chunks| {
140 let mut read = false;
141 loop {
142 if buf.remaining() == 0 {
143 // We know `read` is `true` because `buf.remaining()` was not 0 before
144 return ReadStatus::Readable(());
145 }
146
147 match chunks.next(buf.remaining()) {
148 Ok(Some(chunk)) => {
149 buf.put_slice(&chunk.bytes);
150 read = true;
151 }
152 res => return (if read { Some(()) } else { None }, res.err()).into(),
153 }
154 }
155 })
156 .map(|res| res.map(|_| ()))
157 }
158
159 /// Reads the next segment of data as zero-copy [`Bytes`].
160 ///
161 /// Yields `None` if the stream was finished. Otherwise, yields the next segment of data. The
162 /// chunk's offset will be immediately after the last data yielded by [`RecvStream::read`] or
163 /// [`RecvStream::read_chunk`]; use [`bytes_read()`](Self::bytes_read) to query that offset
164 /// explicitly.
165 ///
166 /// For unordered reads, convert the stream into an unordered stream using [`Self::into_unordered`].
167 ///
168 /// Slightly more efficient than [`RecvStream::read`] due to not copying. Chunk boundaries do
169 /// not correspond to peer writes, and hence cannot be used as framing.
170 ///
171 /// This operation is cancel-safe.
172 pub async fn read_chunk(&mut self, max_length: usize) -> Result<Option<Bytes>, ReadError> {
173 Ok(ReadChunk {
174 stream: self,
175 max_length,
176 ordered: true,
177 }
178 .await?
179 .map(|chunk| chunk.bytes))
180 }
181
182 /// Attempts to read a chunk from the stream.
183 ///
184 /// On success, returns `Poll::Ready(Ok(Some(chunk)))`. If `Poll::Ready(Ok(None))`
185 /// is returned, it implies that EOF has been reached.
186 ///
187 /// If no data is available for reading, the method returns `Poll::Pending`
188 /// and arranges for the current task (via cx.waker()) to receive a notification
189 /// when the stream becomes readable or is closed.
190 fn poll_read_chunk(
191 &mut self,
192 cx: &mut Context<'_>,
193 max_length: usize,
194 ordered: bool,
195 ) -> Poll<Result<Option<Chunk>, ReadError>> {
196 self.poll_read_generic(cx, ordered, |chunks| match chunks.next(max_length) {
197 Ok(Some(chunk)) => ReadStatus::Readable(chunk),
198 res => (None, res.err()).into(),
199 })
200 }
201
202 /// Reads the next segments of data.
203 ///
204 /// Fills `bufs` with the segments of data beginning immediately after the last data yielded
205 /// by [`read`](Self::read), [`read_chunk`](Self::read_chunk), or
206 /// [`read_many_chunks`](Self::read_many_chunks), or `None` if the stream was finished.
207 ///
208 /// Slightly more efficient than [`read`](Self::read) due to not copying. Chunk boundaries do
209 /// not correspond to peer writes, and hence cannot be used as framing.
210 ///
211 /// This operation is cancel-safe.
212 pub async fn read_many_chunks(
213 &mut self,
214 bufs: &mut [Bytes],
215 ) -> Result<Option<usize>, ReadError> {
216 ReadChunks { stream: self, bufs }.await
217 }
218
219 /// Foundation of [`Self::read_many_chunks`]
220 fn poll_read_chunks(
221 &mut self,
222 cx: &mut Context<'_>,
223 bufs: &mut [Bytes],
224 ) -> Poll<Result<Option<usize>, ReadError>> {
225 if bufs.is_empty() {
226 return Poll::Ready(Ok(Some(0)));
227 }
228
229 self.poll_read_generic(cx, true, |chunks| {
230 let mut read = 0;
231 loop {
232 if read >= bufs.len() {
233 // We know `read > 0` because `bufs` cannot be empty here
234 return ReadStatus::Readable(read);
235 }
236
237 match chunks.next(usize::MAX) {
238 Ok(Some(chunk)) => {
239 bufs[read] = chunk.bytes;
240 read += 1;
241 }
242 res => return (if read == 0 { None } else { Some(read) }, res.err()).into(),
243 }
244 }
245 })
246 }
247
248 /// Convenience method to read all remaining data into a buffer
249 ///
250 /// Fails with [`ReadToEndError::TooLong`] on reading more than `size_limit` bytes, discarding
251 /// all data read. Uses unordered reads to be more efficient than using `AsyncRead` would
252 /// allow. `size_limit` should be set to limit worst-case memory use.
253 ///
254 /// If unordered reads have already been made, the resulting buffer may have gaps containing
255 /// arbitrary data.
256 ///
257 /// This operation is *not* cancel-safe.
258 ///
259 /// [`ReadToEndError::TooLong`]: crate::ReadToEndError::TooLong
260 pub async fn read_to_end(&mut self, size_limit: usize) -> Result<Vec<u8>, ReadToEndError> {
261 ReadToEnd {
262 stream: self,
263 size_limit,
264 read: Vec::new(),
265 start: u64::MAX,
266 end: 0,
267 }
268 .await
269 }
270
271 /// Stop accepting data
272 ///
273 /// Discards unread data and notifies the peer to stop transmitting. Once stopped, further
274 /// attempts to operate on a stream will yield `ClosedStream` errors.
275 pub fn stop(&mut self, error_code: VarInt) -> Result<(), ClosedStream> {
276 let mut conn = self.conn.lock_and_wake("RecvStream::stop");
277 if self.is_0rtt && conn.check_0rtt().is_err() {
278 conn.skip_waking();
279 return Ok(());
280 }
281 conn.inner.recv_stream(self.stream).stop(error_code)?;
282 self.all_data_read = true;
283 // Clean up shared state that might be left over from a cancelled read
284 // operation, so `drop` doesn't have to
285 conn.blocked_readers.remove(&self.stream);
286 Ok(())
287 }
288
289 /// Check if this stream has been opened during 0-RTT.
290 ///
291 /// In which case any non-idempotent request should be considered dangerous at the application
292 /// level. Because read data is subject to replay attacks.
293 pub fn is_0rtt(&self) -> bool {
294 self.is_0rtt
295 }
296
297 /// Get the identity of this stream
298 pub fn id(&self) -> StreamId {
299 self.stream
300 }
301
302 /// Returns the number of bytes read from this stream.
303 ///
304 /// This is the offset of the next byte to be read, i.e. the length of the contiguous
305 /// prefix of the stream consumed by the application.
306 pub fn bytes_read(&self) -> Result<u64, ClosedStream> {
307 let mut conn = self.conn.lock_without_waking("RecvStream::bytes_read");
308 conn.inner.recv_stream(self.stream).bytes_read()
309 }
310
311 /// Completes when the stream has been reset by the peer or otherwise closed
312 ///
313 /// Yields `Some` with the reset error code when the stream is reset by the peer. Yields `None`
314 /// when the stream was previously [`stop()`](Self::stop)ed, or when the stream was
315 /// [`finish()`](crate::SendStream::finish)ed by the peer and all data has been received, after
316 /// which it is no longer meaningful for the stream to be reset.
317 ///
318 /// This operation is cancel-safe.
319 pub async fn received_reset(&mut self) -> Result<Option<VarInt>, ResetError> {
320 poll_fn(|cx| {
321 let mut conn = self.conn.lock_without_waking("RecvStream::reset");
322 if self.is_0rtt && conn.check_0rtt().is_err() {
323 return Poll::Ready(Err(ResetError::ZeroRttRejected));
324 }
325
326 if let Some(code) = self.reset {
327 return Poll::Ready(Ok(Some(code)));
328 }
329
330 match conn.inner.recv_stream(self.stream).received_reset() {
331 Err(_) => Poll::Ready(Ok(None)),
332 Ok(Some(error_code)) => {
333 // Stream state has just now been freed, so the connection may need to issue new
334 // stream ID flow control credit
335 conn.wake();
336 Poll::Ready(Ok(Some(error_code)))
337 }
338 Ok(None) => {
339 if let Some(e) = &conn.error {
340 return Poll::Ready(Err(e.clone().into()));
341 }
342 // Resets always notify readers, since a reset is an immediate read error. We
343 // could introduce a dedicated channel to reduce the risk of spurious wakeups,
344 // but that increased complexity is probably not justified, as an application
345 // that is expecting a reset is not likely to receive large amounts of data.
346 conn.blocked_readers.insert(self.stream, cx.waker().clone());
347 Poll::Pending
348 }
349 }
350 })
351 .await
352 }
353
354 /// Handle common logic related to reading out of a receive stream
355 ///
356 /// This takes an `FnMut` closure that takes care of the actual reading process, matching
357 /// the detailed read semantics for the calling function with a particular return type.
358 /// The closure can read from the passed `&mut Chunks` and has to return the status after
359 /// reading: the amount of data read, and the status after the final read call.
360 fn poll_read_generic<T, U>(
361 &mut self,
362 cx: &mut Context<'_>,
363 ordered: bool,
364 mut read_fn: T,
365 ) -> Poll<Result<Option<U>, ReadError>>
366 where
367 T: FnMut(&mut Chunks<'_>) -> ReadStatus<U>,
368 {
369 use proto::ReadError::*;
370 if self.all_data_read {
371 return Poll::Ready(Ok(None));
372 }
373
374 let mut conn = self.conn.lock_without_waking("RecvStream::poll_read");
375 if self.is_0rtt {
376 conn.check_0rtt().map_err(|()| ReadError::ZeroRttRejected)?;
377 }
378
379 // If we stored an error during a previous call, return it now. This can happen if a
380 // `read_fn` both wants to return data and also returns an error in its final stream status.
381 let status = match self.reset {
382 Some(code) => ReadStatus::Failed(None, Reset(code)),
383 None => {
384 let mut recv = conn.inner.recv_stream(self.stream);
385 let mut chunks = recv.read(ordered).map_err(|e| match e {
386 ReadableError::ClosedStream => ReadError::ClosedStream,
387 ReadableError::IllegalOrderedRead => {
388 // We should never get here because the only way to do unordered reads is
389 // via UnorderedRecvStream, which allows only unordered reads. It is not
390 // possible to get a RecvStream from an UnorderedRecvStream.
391 unreachable!("ordered read after unordered read")
392 }
393 })?;
394 let status = read_fn(&mut chunks);
395 if chunks.finalize().should_transmit() {
396 conn.wake();
397 }
398 status
399 }
400 };
401
402 match status {
403 ReadStatus::Readable(read) => Poll::Ready(Ok(Some(read))),
404 ReadStatus::Finished(read) => {
405 self.all_data_read = true;
406 Poll::Ready(Ok(read))
407 }
408 ReadStatus::Failed(read, Blocked) => match read {
409 Some(val) => Poll::Ready(Ok(Some(val))),
410 None => {
411 if let Some(ref x) = conn.error {
412 return Poll::Ready(Err(ReadError::ConnectionLost(x.clone())));
413 }
414 conn.blocked_readers.insert(self.stream, cx.waker().clone());
415 Poll::Pending
416 }
417 },
418 ReadStatus::Failed(read, Reset(error_code)) => match read {
419 None => {
420 self.all_data_read = true;
421 self.reset = Some(error_code);
422 Poll::Ready(Err(ReadError::Reset(error_code)))
423 }
424 done => {
425 self.reset = Some(error_code);
426 Poll::Ready(Ok(done))
427 }
428 },
429 }
430 }
431
432 /// Converts this stream into an unordered stream.
433 pub fn into_unordered(self) -> UnorderedRecvStream {
434 UnorderedRecvStream { inner: self }
435 }
436}
437
438/// A stream that can be used to receive data out-of-order.
439///
440/// Obtained by converting a [`RecvStream`] via [`RecvStream::into_unordered`].
441///
442/// This variant of `RecvStream` allows reading chunks of data *exclusively*
443/// out of order. Once you have done an unordered read, ordered reads are no
444/// longer possible since data may have been consumed out of order.
445///
446/// The stream state related fns like [`Self::id`], [`Self::is_0rtt`], [`Self::stop`], and
447/// [`Self::received_reset`] behave exactly as on [`RecvStream`].
448#[derive(Debug)]
449pub struct UnorderedRecvStream {
450 inner: RecvStream,
451}
452
453impl UnorderedRecvStream {
454 /// Reads the next segment of data.
455 ///
456 /// Yields `None` if the stream was finished. Otherwise, yields a segment of data and its
457 /// offset in the stream. Segments may be received in any order, and the `Chunk`'s `offset`
458 /// field can be used to determine ordering in the caller. Unordered reads are less prone
459 /// to head-of-line blocking within a stream, but require the application to manage
460 /// reassembling the original data.
461 ///
462 /// This operation is cancel-safe.
463 pub async fn read_chunk(&mut self, max_length: usize) -> Result<Option<Chunk>, ReadError> {
464 ReadChunk {
465 stream: &mut self.inner,
466 max_length,
467 ordered: false,
468 }
469 .await
470 }
471
472 /// Get the identity of this stream
473 pub fn id(&self) -> StreamId {
474 self.inner.id()
475 }
476
477 /// Check if this stream has been opened during 0-RTT.
478 ///
479 /// In which case any non-idempotent request should be considered dangerous at the application
480 /// level. Because read data is subject to replay attacks.
481 pub fn is_0rtt(&self) -> bool {
482 self.inner.is_0rtt()
483 }
484
485 /// Stop accepting data
486 ///
487 /// Discards unread data and notifies the peer to stop transmitting. Once stopped, further
488 /// attempts to operate on a stream will yield `ClosedStream` errors.
489 pub fn stop(&mut self, error_code: VarInt) -> Result<(), ClosedStream> {
490 self.inner.stop(error_code)
491 }
492
493 /// Completes when the stream has been reset by the peer or otherwise closed
494 ///
495 /// Yields `Some` with the reset error code when the stream is reset by the peer. Yields `None`
496 /// when the stream was previously [`stop()`](Self::stop)ed, or when the stream was
497 /// [`finish()`](crate::SendStream::finish)ed by the peer and all data has been received, after
498 /// which it is no longer meaningful for the stream to be reset.
499 ///
500 /// This operation is cancel-safe.
501 pub async fn received_reset(&mut self) -> Result<Option<VarInt>, ResetError> {
502 self.inner.received_reset().await
503 }
504}
505
506enum ReadStatus<T> {
507 Readable(T),
508 Finished(Option<T>),
509 Failed(Option<T>, proto::ReadError),
510}
511
512impl<T> From<(Option<T>, Option<proto::ReadError>)> for ReadStatus<T> {
513 fn from(status: (Option<T>, Option<proto::ReadError>)) -> Self {
514 match status {
515 (read, None) => Self::Finished(read),
516 (read, Some(e)) => Self::Failed(read, e),
517 }
518 }
519}
520
521/// Future produced by [`RecvStream::read_to_end()`].
522///
523/// [`RecvStream::read_to_end()`]: crate::RecvStream::read_to_end
524struct ReadToEnd<'a> {
525 stream: &'a mut RecvStream,
526 read: Vec<(Bytes, u64)>,
527 start: u64,
528 end: u64,
529 size_limit: usize,
530}
531
532impl Future for ReadToEnd<'_> {
533 type Output = Result<Vec<u8>, ReadToEndError>;
534 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
535 loop {
536 match ready!(self.stream.poll_read_chunk(cx, usize::MAX, false))? {
537 Some(chunk) => {
538 self.start = self.start.min(chunk.offset);
539 let end = chunk.bytes.len() as u64 + chunk.offset;
540 if (end - self.start) > self.size_limit as u64 {
541 return Poll::Ready(Err(ReadToEndError::TooLong));
542 }
543 self.end = self.end.max(end);
544 self.read.push((chunk.bytes, chunk.offset));
545 }
546 None => {
547 if self.end == 0 {
548 // Never received anything
549 return Poll::Ready(Ok(Vec::new()));
550 }
551 let start = self.start;
552 let mut buffer = vec![0; (self.end - start) as usize];
553 for (data, offset) in self.read.drain(..) {
554 let offset = (offset - start) as usize;
555 buffer[offset..offset + data.len()].copy_from_slice(&data);
556 }
557 return Poll::Ready(Ok(buffer));
558 }
559 }
560 }
561 }
562}
563
564/// Errors from [`RecvStream::read_to_end`]
565#[derive(Debug, Error, Clone, PartialEq, Eq)]
566pub enum ReadToEndError {
567 /// An error occurred during reading
568 #[error("read error: {0}")]
569 Read(#[from] ReadError),
570 /// The stream is larger than the user-supplied limit
571 #[error("stream too long")]
572 TooLong,
573}
574
575#[cfg(feature = "futures-io")]
576impl futures_io::AsyncRead for RecvStream {
577 fn poll_read(
578 self: Pin<&mut Self>,
579 cx: &mut Context<'_>,
580 buf: &mut [u8],
581 ) -> Poll<io::Result<usize>> {
582 let mut buf = ReadBuf::new(buf);
583 ready!(Self::poll_read_buf(self.get_mut(), cx, &mut buf))?;
584 Poll::Ready(Ok(buf.filled().len()))
585 }
586}
587
588impl tokio::io::AsyncRead for RecvStream {
589 fn poll_read(
590 self: Pin<&mut Self>,
591 cx: &mut Context<'_>,
592 buf: &mut ReadBuf<'_>,
593 ) -> Poll<io::Result<()>> {
594 ready!(Self::poll_read_buf(self.get_mut(), cx, buf))?;
595 Poll::Ready(Ok(()))
596 }
597}
598
599impl Drop for RecvStream {
600 fn drop(&mut self) {
601 if self.all_data_read {
602 debug_assert!(
603 !self
604 .conn
605 .lock_without_waking("RecvStream:drop")
606 .blocked_readers
607 .contains_key(&self.stream),
608 "Stream {} should not have a blocked reader when all data read is true",
609 &self.stream
610 );
611 return;
612 }
613 let mut conn = self.conn.lock_and_wake("RecvStream::drop");
614
615 // clean up any previously registered wakers
616 conn.blocked_readers.remove(&self.stream);
617
618 if conn.error.is_some() || (self.is_0rtt && conn.check_0rtt().is_err()) {
619 conn.skip_waking();
620 return;
621 }
622
623 // Ignore ClosedStream errors
624 let _ = conn.inner.recv_stream(self.stream).stop(0u32.into());
625 }
626}
627
628/// Errors that arise from reading from a stream.
629#[derive(Debug, Error, Clone, PartialEq, Eq)]
630pub enum ReadError {
631 /// The peer abandoned transmitting data on this stream
632 ///
633 /// Carries an application-defined error code.
634 #[error("stream reset by peer: error {0}")]
635 Reset(VarInt),
636 /// The connection was lost
637 #[error("connection lost")]
638 ConnectionLost(#[from] ConnectionError),
639 /// The stream has already been stopped, finished, or reset
640 #[error("closed stream")]
641 ClosedStream,
642 /// This was a 0-RTT stream and the server rejected it
643 ///
644 /// Can only occur on clients for 0-RTT streams, which can be opened using
645 /// [`Connecting::into_0rtt()`].
646 ///
647 /// [`Connecting::into_0rtt()`]: crate::Connecting::into_0rtt()
648 #[error("0-RTT rejected")]
649 ZeroRttRejected,
650}
651
652impl From<ResetError> for ReadError {
653 fn from(e: ResetError) -> Self {
654 match e {
655 ResetError::ConnectionLost(e) => Self::ConnectionLost(e),
656 ResetError::ZeroRttRejected => Self::ZeroRttRejected,
657 }
658 }
659}
660
661impl From<ReadError> for io::Error {
662 fn from(x: ReadError) -> Self {
663 use ReadError::*;
664 let kind = match x {
665 Reset { .. } | ZeroRttRejected => io::ErrorKind::ConnectionReset,
666 ConnectionLost(_) | ClosedStream => io::ErrorKind::NotConnected,
667 };
668 Self::new(kind, x)
669 }
670}
671
672/// Errors that arise while waiting for a stream to be reset
673#[derive(Debug, Error, Clone, PartialEq, Eq)]
674pub enum ResetError {
675 /// The connection was lost
676 #[error("connection lost")]
677 ConnectionLost(#[from] ConnectionError),
678 /// This was a 0-RTT stream and the server rejected it
679 ///
680 /// Can only occur on clients for 0-RTT streams, which can be opened using
681 /// [`Connecting::into_0rtt()`].
682 ///
683 /// [`Connecting::into_0rtt()`]: crate::Connecting::into_0rtt()
684 #[error("0-RTT rejected")]
685 ZeroRttRejected,
686}
687
688impl From<ResetError> for io::Error {
689 fn from(x: ResetError) -> Self {
690 use ResetError::*;
691 let kind = match x {
692 ZeroRttRejected => io::ErrorKind::ConnectionReset,
693 ConnectionLost(_) => io::ErrorKind::NotConnected,
694 };
695 Self::new(kind, x)
696 }
697}
698
699/// Future produced by [`RecvStream::read()`].
700///
701/// [`RecvStream::read()`]: crate::RecvStream::read
702struct Read<'a> {
703 stream: &'a mut RecvStream,
704 buf: ReadBuf<'a>,
705}
706
707impl Future for Read<'_> {
708 type Output = Result<Option<usize>, ReadError>;
709
710 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
711 let this = self.get_mut();
712 ready!(this.stream.poll_read_buf(cx, &mut this.buf))?;
713 match this.buf.filled().len() {
714 0 if this.buf.capacity() != 0 => Poll::Ready(Ok(None)),
715 n => Poll::Ready(Ok(Some(n))),
716 }
717 }
718}
719
720/// Future produced by [`RecvStream::read_exact()`].
721///
722/// [`RecvStream::read_exact()`]: crate::RecvStream::read_exact
723struct ReadExact<'a> {
724 stream: &'a mut RecvStream,
725 buf: ReadBuf<'a>,
726}
727
728impl Future for ReadExact<'_> {
729 type Output = Result<(), ReadExactError>;
730 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
731 let this = self.get_mut();
732 let mut remaining = this.buf.remaining();
733 while remaining > 0 {
734 ready!(this.stream.poll_read_buf(cx, &mut this.buf))?;
735 let new = this.buf.remaining();
736 if new == remaining {
737 return Poll::Ready(Err(ReadExactError::FinishedEarly(this.buf.filled().len())));
738 }
739 remaining = new;
740 }
741 Poll::Ready(Ok(()))
742 }
743}
744
745/// Errors that arise from reading from a stream.
746#[derive(Debug, Error, Clone, PartialEq, Eq)]
747pub enum ReadExactError {
748 /// The stream finished before all bytes were read
749 #[error("stream finished early ({0} bytes read)")]
750 FinishedEarly(usize),
751 /// A read error occurred
752 #[error(transparent)]
753 ReadError(#[from] ReadError),
754}
755
756/// Future produced by [`RecvStream::read_chunk()`] or [`UnorderedRecvStream::read_chunk()`].
757///
758/// [`RecvStream::read_chunk()`]: crate::RecvStream::read_chunk
759/// [`UnorderedRecvStream::read_chunk()`]: crate::UnorderedRecvStream::read_chunk
760struct ReadChunk<'a> {
761 stream: &'a mut RecvStream,
762 max_length: usize,
763 ordered: bool,
764}
765
766impl Future for ReadChunk<'_> {
767 type Output = Result<Option<Chunk>, ReadError>;
768 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
769 let (max_length, ordered) = (self.max_length, self.ordered);
770 self.stream.poll_read_chunk(cx, max_length, ordered)
771 }
772}
773
774/// Future produced by [`RecvStream::read_many_chunks()`].
775///
776/// [`RecvStream::read_many_chunks()`]: crate::RecvStream::read_many_chunks
777struct ReadChunks<'a> {
778 stream: &'a mut RecvStream,
779 bufs: &'a mut [Bytes],
780}
781
782impl Future for ReadChunks<'_> {
783 type Output = Result<Option<usize>, ReadError>;
784 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
785 let this = self.get_mut();
786 this.stream.poll_read_chunks(cx, this.bufs)
787 }
788}