Skip to main content

decode_stream

Function decode_stream 

Source
pub fn decode_stream(
    input: Pin<Box<ByteStream>>,
    coding: Coding,
) -> Pin<Box<ByteStream>>
Expand description

Wrap a body byte-stream in a decoder for coding.

Trailers are pulled off the frames before this point, so decoding sees data only. A coding this crate cannot decode leaves the stream as it is; can_decode_as never returns one.

Examples found in repository?
examples/codings.rs (line 41)
16async fn main() {
17	let accept = AcceptEncoding::from(DEFAULT_ACCEPT_ENCODING);
18
19	let mut headers = HeaderMap::new();
20	headers.insert("content-encoding", HeaderValue::from_static("gzip"));
21	headers.insert("content-length", HeaderValue::from_static("42"));
22	// Just the header half, so the coding is in hand for the round trip below; `response::decode`
23	// does this and the body together.
24	let coding = ContentEncoding::peel_one_header(&mut headers, &accept)
25		.expect("gzip is in the default Accept-Encoding");
26	println!("negotiated: {coding:?}");
27	println!("headers after decoding: {:?}", headers.keys().count());
28
29	// Round-trip a body through the coding that was negotiated.
30	let original = b"the quick brown fox jumps over the lazy dog".repeat(8);
31	let compressed = compress_buffer(&original, coding.clone())
32		.await
33		.expect("gzip compresses");
34	println!(
35		"{} bytes in, {} bytes out",
36		original.len(),
37		compressed.len()
38	);
39
40	let stream = futures::stream::once(async move { Ok(Bytes::from(compressed)) });
41	let mut decoded = decode_stream(Box::pin(stream), coding);
42	let mut round_tripped = Vec::new();
43	while let Some(chunk) = decoded.next().await {
44		round_tripped.extend_from_slice(&chunk.expect("the body decodes"));
45	}
46	println!("round-tripped intact: {}", round_tripped == original);
47
48	// Compressing a request on top of a coding the caller already applied declares both, in the
49	// order they were applied.
50	let mut request = HeaderMap::new();
51	request.insert("content-encoding", HeaderValue::from_static("br"));
52
53	let layered = ContentEncoding::from(&request).layer(Coding::Gzip);
54	if let Some(value) = layered.to_header_value() {
55		request.insert("content-encoding", value);
56	}
57	println!(
58		"Content-Encoding: {}",
59		request["content-encoding"].to_str().unwrap()
60	);
61}