async_http_codec/body/
mod.rs1pub(crate) mod common;
2mod decode;
3mod encode;
4
5pub use decode::*;
6pub use encode::*;
7
8#[cfg(test)]
9mod tests {
10 use crate::BodyDecode;
11 use crate::BodyEncode;
12 use futures::executor::block_on;
13 use futures::io::Cursor;
14 use futures::prelude::*;
15 use rand::{thread_rng, Rng};
16 use std::io::SeekFrom;
17
18 const CHUNKED: &[u8] = b"\
196\r\n\
20hello \r\n\
2113\r\n\
22world! hello world!\r\n\
230\r\n\
24\r\n";
25 const DECODED: &[u8] = b"hello world! hello world!";
26 const CHUNKED_PARTS: [&[u8]; 2] = [b"hello ", b"world! hello world!"];
27
28 #[test]
29 fn decode_chunked() {
30 block_on(async {
31 let mut decoded = Vec::new();
32 BodyDecode::new(Cursor::new(CHUNKED), None)
33 .read_to_end(&mut decoded)
34 .await
35 .unwrap();
36 assert_eq!(
37 String::from_utf8(decoded).unwrap(),
38 String::from_utf8(DECODED.to_vec()).unwrap()
39 );
40 })
41 }
42
43 #[test]
44 fn decode_fixed_length() {
45 block_on(async {
46 const LENGTH: u64 = 10;
47 let mut decoded = Vec::new();
48 BodyDecode::new(Cursor::new(DECODED), Some(LENGTH))
49 .read_to_end(&mut decoded)
50 .await
51 .unwrap();
52 assert_eq!(
53 String::from_utf8(decoded).unwrap(),
54 String::from_utf8(DECODED[0..LENGTH as usize].to_vec()).unwrap()
55 );
56 })
57 }
58
59 #[test]
60 fn decode_empty() {
61 block_on(async {
62 let mut decoded = Vec::new();
63 BodyDecode::new(Cursor::new(""), Some(0))
64 .read_to_end(&mut decoded)
65 .await
66 .unwrap();
67 assert_eq!(
68 String::from_utf8(decoded).unwrap(),
69 String::from_utf8(b"".to_vec()).unwrap()
70 );
71 })
72 }
73
74 #[test]
75 fn encode_chunked_flush() {
76 block_on(async {
77 let mut transport = Cursor::new(Vec::new());
78 let mut encode = BodyEncode::new(&mut transport, None);
79 for part in CHUNKED_PARTS {
80 encode.write(part).await.unwrap();
81 encode.flush().await.unwrap();
82 }
83 encode.close().await.unwrap();
84 assert_eq!(
85 String::from_utf8(transport.into_inner()).unwrap(),
86 String::from_utf8(CHUNKED.to_vec()).unwrap()
87 );
88 })
89 }
90
91 #[test]
92 fn encode_chunked_long() {
93 block_on(async {
94 let mut input = [0u8; 1500];
95 thread_rng().fill(&mut input[..]);
96
97 let mut transport = Cursor::new(Vec::new());
98 let mut encode = BodyEncode::new(&mut transport, None);
99 encode.write_all(&input).await.unwrap();
100 encode.close().await.unwrap();
101
102 let mut output = Vec::new();
103 transport.seek(SeekFrom::Start(0)).await.unwrap();
104 BodyDecode::new(transport, None)
105 .read_to_end(&mut output)
106 .await
107 .unwrap();
108 assert_eq!(&input, &output[..]);
109 })
110 }
111}