Skip to main content

http_streams_core/
text_format.rs

1//! Raw UTF-8 text. Encode only.
2//!
3//! There is no decoder and there cannot be one. The framing writes each string's bytes with no
4//! delimiter at all, so `["ab", "c"]` and `["a", "bc"]` produce identical bytes and splitting
5//! them back into the original items is not merely unimplemented but impossible. Offering a
6//! decoder that handed back HTTP chunk boundaries as though they were items would make `text`
7//! the one format whose round trip silently lies.
8//!
9//! If a raw byte stream is what is wanted, take the body as bytes directly rather than through
10//! this format.
11
12use crate::content_type::ContentType;
13use crate::error::StreamError;
14use crate::format::{DefaultFormat, ItemEncoder, StreamFormat, StreamFormatEncode};
15use bytes::BytesMut;
16
17const TEXT_CONTENT_TYPE: &str = "text/plain; charset=utf-8";
18
19/// Raw UTF-8 text, undelimited.
20#[derive(Debug, Clone, Copy, Default)]
21pub struct TextStreamFormat;
22
23impl TextStreamFormat {
24    /// A raw text format.
25    pub fn new() -> Self {
26        Self
27    }
28}
29
30impl DefaultFormat for TextStreamFormat {
31    fn default_format() -> Self {
32        Self
33    }
34}
35
36impl StreamFormat for TextStreamFormat {
37    fn format_name(&self) -> &'static str {
38        "text"
39    }
40
41    fn default_content_type(&self) -> &'static str {
42        TEXT_CONTENT_TYPE
43    }
44
45    fn accepts_content_type(&self, ct: &ContentType<'_>) -> bool {
46        ct.matches("text/plain")
47    }
48}
49
50/// Per-stream state for [`TextStreamFormat`]. There is none.
51#[derive(Debug, Clone, Copy, Default)]
52pub struct TextEncoder;
53
54impl ItemEncoder<String> for TextEncoder {
55    fn encode(&mut self, item: &String, _index: u64, buf: &mut BytesMut) -> Result<(), StreamError> {
56        buf.extend_from_slice(item.as_bytes());
57        Ok(())
58    }
59}
60
61impl StreamFormatEncode<String> for TextStreamFormat {
62    type Encoder = TextEncoder;
63
64    fn encoder(&self) -> Self::Encoder {
65        TextEncoder
66    }
67}