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 predates completion of the handshake on an incoming connection.
290 ///
291 /// True only if the stream was accepted before the handshake completed, which is only possible
292 /// if you successfully called [`Connecting::into_0rtt`](crate::Connecting::into_0rtt) and the
293 /// client chose to send 0-RTT data.
294 ///
295 /// Under those conditions, depending on cryptographic layer configuration, 0-RTT application
296 /// data may be a replay attack. To guard against this, applications should not execute
297 /// non-idempotent operations until
298 /// [`Connection::authenticated`](crate::Connection::authenticated) succeeds.
299 pub fn is_0rtt(&self) -> bool {
300 self.is_0rtt
301 }
302
303 /// Get the identity of this stream
304 pub fn id(&self) -> StreamId {
305 self.stream
306 }
307
308 /// Returns the number of bytes read from this stream.
309 ///
310 /// This is the offset of the next byte to be read, i.e. the length of the contiguous
311 /// prefix of the stream consumed by the application.
312 pub fn bytes_read(&self) -> Result<u64, ClosedStream> {
313 let mut conn = self.conn.lock_without_waking("RecvStream::bytes_read");
314 conn.inner.recv_stream(self.stream).bytes_read()
315 }
316
317 /// Completes when the stream has been reset by the peer or otherwise closed
318 ///
319 /// Yields `Some` with the reset error code when the stream is reset by the peer. Yields `None`
320 /// when the stream was previously [`stop()`](Self::stop)ed, or when the stream was
321 /// [`finish()`](crate::SendStream::finish)ed by the peer and all data has been received, after
322 /// which it is no longer meaningful for the stream to be reset.
323 ///
324 /// This operation is cancel-safe.
325 pub async fn received_reset(&mut self) -> Result<Option<VarInt>, ResetError> {
326 poll_fn(|cx| {
327 let mut conn = self.conn.lock_without_waking("RecvStream::reset");
328 if self.is_0rtt && conn.check_0rtt().is_err() {
329 return Poll::Ready(Err(ResetError::ZeroRttRejected));
330 }
331
332 if let Some(code) = self.reset {
333 return Poll::Ready(Ok(Some(code)));
334 }
335
336 match conn.inner.recv_stream(self.stream).received_reset() {
337 Err(_) => Poll::Ready(Ok(None)),
338 Ok(Some(error_code)) => {
339 // Stream state has just now been freed, so the connection may need to issue new
340 // stream ID flow control credit
341 conn.wake();
342 Poll::Ready(Ok(Some(error_code)))
343 }
344 Ok(None) => {
345 if let Some(e) = &conn.error {
346 return Poll::Ready(Err(e.clone().into()));
347 }
348 // Resets always notify readers, since a reset is an immediate read error. We
349 // could introduce a dedicated channel to reduce the risk of spurious wakeups,
350 // but that increased complexity is probably not justified, as an application
351 // that is expecting a reset is not likely to receive large amounts of data.
352 conn.blocked_readers.insert(self.stream, cx.waker().clone());
353 Poll::Pending
354 }
355 }
356 })
357 .await
358 }
359
360 /// Handle common logic related to reading out of a receive stream
361 ///
362 /// This takes an `FnMut` closure that takes care of the actual reading process, matching
363 /// the detailed read semantics for the calling function with a particular return type.
364 /// The closure can read from the passed `&mut Chunks` and has to return the status after
365 /// reading: the amount of data read, and the status after the final read call.
366 fn poll_read_generic<T, U>(
367 &mut self,
368 cx: &mut Context<'_>,
369 ordered: bool,
370 mut read_fn: T,
371 ) -> Poll<Result<Option<U>, ReadError>>
372 where
373 T: FnMut(&mut Chunks<'_>) -> ReadStatus<U>,
374 {
375 use proto::ReadError::*;
376 if self.all_data_read {
377 return Poll::Ready(Ok(None));
378 }
379
380 let mut conn = self.conn.lock_without_waking("RecvStream::poll_read");
381 if self.is_0rtt {
382 conn.check_0rtt().map_err(|()| ReadError::ZeroRttRejected)?;
383 }
384
385 // If we stored an error during a previous call, return it now. This can happen if a
386 // `read_fn` both wants to return data and also returns an error in its final stream status.
387 let status = match self.reset {
388 Some(code) => ReadStatus::Failed(None, Reset(code)),
389 None => {
390 let mut recv = conn.inner.recv_stream(self.stream);
391 let mut chunks = recv.read(ordered).map_err(|e| match e {
392 ReadableError::ClosedStream => ReadError::ClosedStream,
393 ReadableError::IllegalOrderedRead => {
394 // We should never get here because the only way to do unordered reads is
395 // via UnorderedRecvStream, which allows only unordered reads. It is not
396 // possible to get a RecvStream from an UnorderedRecvStream.
397 unreachable!("ordered read after unordered read")
398 }
399 })?;
400 let status = read_fn(&mut chunks);
401 if chunks.finalize().should_transmit() {
402 conn.wake();
403 }
404 status
405 }
406 };
407
408 match status {
409 ReadStatus::Readable(read) => Poll::Ready(Ok(Some(read))),
410 ReadStatus::Finished(read) => {
411 self.all_data_read = true;
412 Poll::Ready(Ok(read))
413 }
414 ReadStatus::Failed(read, Blocked) => match read {
415 Some(val) => Poll::Ready(Ok(Some(val))),
416 None => {
417 if let Some(ref x) = conn.error {
418 return Poll::Ready(Err(ReadError::ConnectionLost(x.clone())));
419 }
420 conn.blocked_readers.insert(self.stream, cx.waker().clone());
421 Poll::Pending
422 }
423 },
424 ReadStatus::Failed(read, Reset(error_code)) => match read {
425 None => {
426 self.all_data_read = true;
427 self.reset = Some(error_code);
428 Poll::Ready(Err(ReadError::Reset(error_code)))
429 }
430 done => {
431 self.reset = Some(error_code);
432 Poll::Ready(Ok(done))
433 }
434 },
435 }
436 }
437
438 /// Converts this stream into an unordered stream.
439 pub fn into_unordered(self) -> UnorderedRecvStream {
440 UnorderedRecvStream { inner: self }
441 }
442}
443
444/// A stream that can be used to receive data out-of-order.
445///
446/// Obtained by converting a [`RecvStream`] via [`RecvStream::into_unordered`].
447///
448/// This variant of `RecvStream` allows reading chunks of data *exclusively*
449/// out of order. Once you have done an unordered read, ordered reads are no
450/// longer possible since data may have been consumed out of order.
451///
452/// The stream state related fns like [`Self::id`], [`Self::is_0rtt`], [`Self::stop`], and
453/// [`Self::received_reset`] behave exactly as on [`RecvStream`].
454#[derive(Debug)]
455pub struct UnorderedRecvStream {
456 inner: RecvStream,
457}
458
459impl UnorderedRecvStream {
460 /// Reads the next segment of data.
461 ///
462 /// Yields `None` if the stream was finished. Otherwise, yields a segment of data and its
463 /// offset in the stream. Segments may be received in any order, and the `Chunk`'s `offset`
464 /// field can be used to determine ordering in the caller. Unordered reads are less prone
465 /// to head-of-line blocking within a stream, but require the application to manage
466 /// reassembling the original data.
467 ///
468 /// This operation is cancel-safe.
469 pub async fn read_chunk(&mut self, max_length: usize) -> Result<Option<Chunk>, ReadError> {
470 ReadChunk {
471 stream: &mut self.inner,
472 max_length,
473 ordered: false,
474 }
475 .await
476 }
477
478 /// Get the identity of this stream
479 pub fn id(&self) -> StreamId {
480 self.inner.id()
481 }
482
483 /// Check if this stream has been opened during 0-RTT.
484 ///
485 /// In which case any non-idempotent request should be considered dangerous at the application
486 /// level. Because read data is subject to replay attacks.
487 pub fn is_0rtt(&self) -> bool {
488 self.inner.is_0rtt()
489 }
490
491 /// Stop accepting data
492 ///
493 /// Discards unread data and notifies the peer to stop transmitting. Once stopped, further
494 /// attempts to operate on a stream will yield `ClosedStream` errors.
495 pub fn stop(&mut self, error_code: VarInt) -> Result<(), ClosedStream> {
496 self.inner.stop(error_code)
497 }
498
499 /// Completes when the stream has been reset by the peer or otherwise closed
500 ///
501 /// Yields `Some` with the reset error code when the stream is reset by the peer. Yields `None`
502 /// when the stream was previously [`stop()`](Self::stop)ed, or when the stream was
503 /// [`finish()`](crate::SendStream::finish)ed by the peer and all data has been received, after
504 /// which it is no longer meaningful for the stream to be reset.
505 ///
506 /// This operation is cancel-safe.
507 pub async fn received_reset(&mut self) -> Result<Option<VarInt>, ResetError> {
508 self.inner.received_reset().await
509 }
510}
511
512enum ReadStatus<T> {
513 Readable(T),
514 Finished(Option<T>),
515 Failed(Option<T>, proto::ReadError),
516}
517
518impl<T> From<(Option<T>, Option<proto::ReadError>)> for ReadStatus<T> {
519 fn from(status: (Option<T>, Option<proto::ReadError>)) -> Self {
520 match status {
521 (read, None) => Self::Finished(read),
522 (read, Some(e)) => Self::Failed(read, e),
523 }
524 }
525}
526
527/// Future produced by [`RecvStream::read_to_end()`].
528///
529/// [`RecvStream::read_to_end()`]: crate::RecvStream::read_to_end
530struct ReadToEnd<'a> {
531 stream: &'a mut RecvStream,
532 read: Vec<(Bytes, u64)>,
533 start: u64,
534 end: u64,
535 size_limit: usize,
536}
537
538impl Future for ReadToEnd<'_> {
539 type Output = Result<Vec<u8>, ReadToEndError>;
540 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
541 loop {
542 match ready!(self.stream.poll_read_chunk(cx, usize::MAX, false))? {
543 Some(chunk) => {
544 self.start = self.start.min(chunk.offset);
545 let end = chunk.bytes.len() as u64 + chunk.offset;
546 if (end - self.start) > self.size_limit as u64 {
547 return Poll::Ready(Err(ReadToEndError::TooLong));
548 }
549 self.end = self.end.max(end);
550 self.read.push((chunk.bytes, chunk.offset));
551 }
552 None => {
553 if self.end == 0 {
554 // Never received anything
555 return Poll::Ready(Ok(Vec::new()));
556 }
557 let start = self.start;
558 let mut buffer = vec![0; (self.end - start) as usize];
559 for (data, offset) in self.read.drain(..) {
560 let offset = (offset - start) as usize;
561 buffer[offset..offset + data.len()].copy_from_slice(&data);
562 }
563 return Poll::Ready(Ok(buffer));
564 }
565 }
566 }
567 }
568}
569
570/// Errors from [`RecvStream::read_to_end`]
571#[derive(Debug, Error, Clone, PartialEq, Eq)]
572pub enum ReadToEndError {
573 /// An error occurred during reading
574 #[error("read error: {0}")]
575 Read(#[from] ReadError),
576 /// The stream is larger than the user-supplied limit
577 #[error("stream too long")]
578 TooLong,
579}
580
581#[cfg(feature = "futures-io")]
582impl futures_io::AsyncRead for RecvStream {
583 fn poll_read(
584 self: Pin<&mut Self>,
585 cx: &mut Context<'_>,
586 buf: &mut [u8],
587 ) -> Poll<io::Result<usize>> {
588 let mut buf = ReadBuf::new(buf);
589 ready!(Self::poll_read_buf(self.get_mut(), cx, &mut buf))?;
590 Poll::Ready(Ok(buf.filled().len()))
591 }
592}
593
594impl tokio::io::AsyncRead for RecvStream {
595 fn poll_read(
596 self: Pin<&mut Self>,
597 cx: &mut Context<'_>,
598 buf: &mut ReadBuf<'_>,
599 ) -> Poll<io::Result<()>> {
600 ready!(Self::poll_read_buf(self.get_mut(), cx, buf))?;
601 Poll::Ready(Ok(()))
602 }
603}
604
605impl Drop for RecvStream {
606 fn drop(&mut self) {
607 if self.all_data_read {
608 debug_assert!(
609 !self
610 .conn
611 .lock_without_waking("RecvStream:drop")
612 .blocked_readers
613 .contains_key(&self.stream),
614 "Stream {} should not have a blocked reader when all data read is true",
615 self.stream
616 );
617 return;
618 }
619 let mut conn = self.conn.lock_and_wake("RecvStream::drop");
620
621 // clean up any previously registered wakers
622 conn.blocked_readers.remove(&self.stream);
623
624 if conn.error.is_some() || (self.is_0rtt && conn.check_0rtt().is_err()) {
625 conn.skip_waking();
626 return;
627 }
628
629 // Ignore ClosedStream errors
630 let _ = conn.inner.recv_stream(self.stream).stop(0u32.into());
631 }
632}
633
634/// Errors that arise from reading from a stream.
635#[derive(Debug, Error, Clone, PartialEq, Eq)]
636pub enum ReadError {
637 /// The peer abandoned transmitting data on this stream
638 ///
639 /// Carries an application-defined error code.
640 #[error("stream reset by peer: error {0}")]
641 Reset(VarInt),
642 /// The connection was lost
643 #[error("connection lost")]
644 ConnectionLost(#[from] ConnectionError),
645 /// The stream has already been stopped, finished, or reset
646 #[error("closed stream")]
647 ClosedStream,
648 /// This was a 0-RTT stream and the server rejected it
649 ///
650 /// Can only occur on clients for 0-RTT streams, which can be opened using
651 /// [`Connecting::into_0rtt()`].
652 ///
653 /// [`Connecting::into_0rtt()`]: crate::Connecting::into_0rtt()
654 #[error("0-RTT rejected")]
655 ZeroRttRejected,
656}
657
658impl From<ResetError> for ReadError {
659 fn from(e: ResetError) -> Self {
660 match e {
661 ResetError::ConnectionLost(e) => Self::ConnectionLost(e),
662 ResetError::ZeroRttRejected => Self::ZeroRttRejected,
663 }
664 }
665}
666
667impl From<ReadError> for io::Error {
668 fn from(x: ReadError) -> Self {
669 use ReadError::*;
670 let kind = match x {
671 Reset { .. } | ZeroRttRejected => io::ErrorKind::ConnectionReset,
672 ConnectionLost(_) | ClosedStream => io::ErrorKind::NotConnected,
673 };
674 Self::new(kind, x)
675 }
676}
677
678/// Errors that arise while waiting for a stream to be reset
679#[derive(Debug, Error, Clone, PartialEq, Eq)]
680pub enum ResetError {
681 /// The connection was lost
682 #[error("connection lost")]
683 ConnectionLost(#[from] ConnectionError),
684 /// This was a 0-RTT stream and the server rejected it
685 ///
686 /// Can only occur on clients for 0-RTT streams, which can be opened using
687 /// [`Connecting::into_0rtt()`].
688 ///
689 /// [`Connecting::into_0rtt()`]: crate::Connecting::into_0rtt()
690 #[error("0-RTT rejected")]
691 ZeroRttRejected,
692}
693
694impl From<ResetError> for io::Error {
695 fn from(x: ResetError) -> Self {
696 use ResetError::*;
697 let kind = match x {
698 ZeroRttRejected => io::ErrorKind::ConnectionReset,
699 ConnectionLost(_) => io::ErrorKind::NotConnected,
700 };
701 Self::new(kind, x)
702 }
703}
704
705/// Future produced by [`RecvStream::read()`].
706///
707/// [`RecvStream::read()`]: crate::RecvStream::read
708struct Read<'a> {
709 stream: &'a mut RecvStream,
710 buf: ReadBuf<'a>,
711}
712
713impl Future for Read<'_> {
714 type Output = Result<Option<usize>, ReadError>;
715
716 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
717 let this = self.get_mut();
718 ready!(this.stream.poll_read_buf(cx, &mut this.buf))?;
719 match this.buf.filled().len() {
720 0 if this.buf.capacity() != 0 => Poll::Ready(Ok(None)),
721 n => Poll::Ready(Ok(Some(n))),
722 }
723 }
724}
725
726/// Future produced by [`RecvStream::read_exact()`].
727///
728/// [`RecvStream::read_exact()`]: crate::RecvStream::read_exact
729struct ReadExact<'a> {
730 stream: &'a mut RecvStream,
731 buf: ReadBuf<'a>,
732}
733
734impl Future for ReadExact<'_> {
735 type Output = Result<(), ReadExactError>;
736 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
737 let this = self.get_mut();
738 let mut remaining = this.buf.remaining();
739 while remaining > 0 {
740 ready!(this.stream.poll_read_buf(cx, &mut this.buf))?;
741 let new = this.buf.remaining();
742 if new == remaining {
743 return Poll::Ready(Err(ReadExactError::FinishedEarly(this.buf.filled().len())));
744 }
745 remaining = new;
746 }
747 Poll::Ready(Ok(()))
748 }
749}
750
751/// Errors that arise from reading from a stream.
752#[derive(Debug, Error, Clone, PartialEq, Eq)]
753pub enum ReadExactError {
754 /// The stream finished before all bytes were read
755 #[error("stream finished early ({0} bytes read)")]
756 FinishedEarly(usize),
757 /// A read error occurred
758 #[error(transparent)]
759 ReadError(#[from] ReadError),
760}
761
762/// Future produced by [`RecvStream::read_chunk()`] or [`UnorderedRecvStream::read_chunk()`].
763///
764/// [`RecvStream::read_chunk()`]: crate::RecvStream::read_chunk
765/// [`UnorderedRecvStream::read_chunk()`]: crate::UnorderedRecvStream::read_chunk
766struct ReadChunk<'a> {
767 stream: &'a mut RecvStream,
768 max_length: usize,
769 ordered: bool,
770}
771
772impl Future for ReadChunk<'_> {
773 type Output = Result<Option<Chunk>, ReadError>;
774 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
775 let (max_length, ordered) = (self.max_length, self.ordered);
776 self.stream.poll_read_chunk(cx, max_length, ordered)
777 }
778}
779
780/// Future produced by [`RecvStream::read_many_chunks()`].
781///
782/// [`RecvStream::read_many_chunks()`]: crate::RecvStream::read_many_chunks
783struct ReadChunks<'a> {
784 stream: &'a mut RecvStream,
785 bufs: &'a mut [Bytes],
786}
787
788impl Future for ReadChunks<'_> {
789 type Output = Result<Option<usize>, ReadError>;
790 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
791 let this = self.get_mut();
792 this.stream.poll_read_chunks(cx, this.bufs)
793 }
794}