s2n_quic/stream/bidirectional.rs
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use s2n_quic_transport::stream::Stream;
5
6/// A QUIC stream that may send and receive data.
7#[derive(Debug)]
8pub struct BidirectionalStream(Stream);
9
10impl BidirectionalStream {
11 pub(crate) const fn new(stream: Stream) -> Self {
12 Self(stream)
13 }
14
15 /// Returns the stream's identifier
16 ///
17 /// This value is unique to a particular connection. The format follows the same as what is
18 /// defined in the
19 /// [QUIC Transport RFC](https://www.rfc-editor.org/rfc/rfc9000.html#name-stream-types-and-identifier).
20 ///
21 /// # Examples
22 ///
23 /// ```rust,no_run
24 /// # async fn test() -> s2n_quic::stream::Result<()> {
25 /// # let connection: s2n_quic::connection::Connection = todo!();
26 /// #
27 /// let stream = connection.open_bidirectional_stream().await?;
28 /// println!("New stream's id: {}", stream.id());
29 /// #
30 /// # Ok(())
31 /// # }
32 /// ```
33 pub fn id(&self) -> u64 {
34 self.0.id().into()
35 }
36
37 impl_connection_api!(|stream| crate::connection::Handle(stream.0.connection().clone()));
38
39 impl_receive_stream_api!(|stream, call| call!(stream.0));
40
41 impl_send_stream_api!(|stream, call| call!(stream.0));
42
43 /// Splits the stream into [`ReceiveStream`](crate::stream::ReceiveStream) and
44 /// [`SendStream`](crate::stream::SendStream) halves.
45 ///
46 /// # Examples
47 ///
48 /// ```rust,no_run
49 /// # use bytes::Bytes;
50 /// # async fn test() -> s2n_quic::stream::Result<()> {
51 /// # let connection: s2n_quic::connection::Connection = todo!();
52 /// #
53 /// let stream = connection.open_bidirectional_stream().await?;
54 /// let (recv, mut send) = stream.split();
55 ///
56 /// tokio::spawn(async move {
57 /// let _ = send.send(Bytes::from_static(&[1, 2, 3])).await;
58 /// });
59 ///
60 /// while let Some(chunk) = recv.receive().await? {
61 /// println!("received: {:?}", chunk);
62 /// }
63 /// #
64 /// # Ok(())
65 /// # }
66 /// ```
67 pub fn split(self) -> (crate::stream::ReceiveStream, crate::stream::SendStream) {
68 let (recv, send) = self.0.split();
69 (
70 crate::stream::ReceiveStream::new(recv),
71 crate::stream::SendStream::new(send),
72 )
73 }
74}
75
76impl_receive_stream_trait!(BidirectionalStream, |stream, call| call!(stream.0));
77impl_send_stream_trait!(BidirectionalStream, |stream, call| call!(stream.0));
78impl_splittable_stream_trait!(BidirectionalStream, |stream| {
79 let (recv, send) = Self::split(stream);
80 (Some(recv), Some(send))
81});