rocket_community/response/stream/
text.rs

1use futures::stream::{Stream, StreamExt};
2
3use crate::http::ContentType;
4use crate::request::Request;
5use crate::response::stream::ReaderStream;
6use crate::response::{self, Responder, Response};
7
8/// A potentially infinite stream of text: `T: AsRef<str>`.
9///
10/// A `TextStream` can be constructed from any [`Stream`] of items of type `T`
11/// where `T: AsRef<str>`. This includes `&str`, `String`, `Cow<str>`,
12/// `&RawStr`, and more. The stream can be constructed directly, via
13/// `TextStream(..)` or [`TextStream::from()`], or through generator syntax via
14/// [`TextStream!`].
15///
16/// [`Stream`]: https://docs.rs/futures/0.3/futures/stream/trait.Stream.html
17///
18/// # Responder
19///
20/// `TextStream` is a (potentially infinite) responder. The response
21/// `Content-Type` is set to [`Text`](ContentType::Text). The body is
22/// [unsized](crate::response::Body#unsized), and values are sent as soon as
23/// they are yielded by the internal iterator.
24///
25/// # Example
26///
27/// Use [`TextStream!`] to yield 10 strings, one every second, of the form `"n:
28/// $k"` for `$k` from `0` to `10` exclusive:
29///
30/// ```rust
31/// # extern crate rocket_community as rocket;
32/// # use rocket::*;
33/// use rocket::response::stream::TextStream;
34/// use rocket::futures::stream::{repeat, StreamExt};
35/// use rocket::tokio::time::{self, Duration};
36///
37/// #[get("/text")]
38/// fn text() -> TextStream![&'static str] {
39///     TextStream(repeat("hi"))
40/// }
41///
42/// #[get("/text/stream")]
43/// fn stream() -> TextStream![String] {
44///     TextStream! {
45///         let mut interval = time::interval(Duration::from_secs(1));
46///         for i in 0..10 {
47///             yield format!("n: {}", i);
48///             interval.tick().await;
49///         }
50///     }
51/// }
52/// ```
53///
54/// The syntax of [`TextStream!`] as an expression is identical to that of
55/// [`stream!`](crate::response::stream::stream).
56#[derive(Debug, Clone)]
57pub struct TextStream<S>(pub S);
58
59impl<S> From<S> for TextStream<S> {
60    /// Creates a `TextStream` from any `S: Stream`.
61    fn from(stream: S) -> Self {
62        TextStream(stream)
63    }
64}
65
66impl<'r, S: Stream> Responder<'r, 'r> for TextStream<S>
67where
68    S: Send + 'r,
69    S::Item: AsRef<str> + Send + Unpin + 'r,
70{
71    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'r> {
72        struct ByteStr<T>(T);
73
74        impl<T: AsRef<str>> AsRef<[u8]> for ByteStr<T> {
75            fn as_ref(&self) -> &[u8] {
76                self.0.as_ref().as_bytes()
77            }
78        }
79
80        let inner = self.0.map(ByteStr).map(std::io::Cursor::new);
81        Response::build()
82            .header(ContentType::Text)
83            .streamed_body(ReaderStream::from(inner))
84            .ok()
85    }
86}
87
88crate::export! {
89    /// Type and stream expression macro for [`struct@TextStream`].
90    ///
91    /// See [`stream!`](crate::response::stream::stream) for the syntax
92    /// supported by this macro.
93    ///
94    /// See [`struct@TextStream`] and the [module level
95    /// docs](crate::response::stream#typed-streams) for usage details.
96    macro_rules! TextStream {
97        ($($s:tt)*) => ($crate::_typed_stream!(TextStream, $($s)*));
98    }
99}