Skip to content

Commit cdea355

Browse files
committed
add a test for the critical function max_bytes_to_read
1 parent f6a6528 commit cdea355

File tree

2 files changed

+55
-3
lines changed

2 files changed

+55
-3
lines changed

src/chunked/encoder.rs

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,58 @@ fn max_bytes_to_read(buf_len: usize) -> usize {
2828
}
2929
// the maximum number of bytes that the hex representation of remaining bytes might take
3030
let max_bytes_of_hex_framing = (((buf_len - 5) as f64).log2() / 4f64).floor();
31-
buf_len - 5 - (max_bytes_of_hex_framing as usize)
31+
buf_len - 5 - (max_bytes_of_hex_framing as usize)
32+
}
33+
34+
#[cfg(test)]
35+
mod test_bytes_to_read {
36+
#[test]
37+
fn simple_check_of_known_values() {
38+
// the marked rows are the most important part of this test,
39+
// and a nonobvious but intentional consequence of the
40+
// implementation. in order to avoid overflowing, we must use
41+
// one fewer than the available buffer bytes because
42+
// increasing the read size by one byte would increase the
43+
// number of framed bytes by two. This occurs when the hex
44+
// representation of the content bytes increases order of
45+
// magnitude (F->10, FF->100, FFF-> 1000, etc)
46+
let values = vec![
47+
(6, 1), // 1
48+
(7, 2), // 2
49+
(20, 15), // F
50+
(21, 15), // F <-
51+
(22, 16), // 10
52+
(23, 17), // 11
53+
(260, 254), // FE
54+
(261, 254), // FE <-
55+
(262, 255), // FF
56+
(263, 256), // 100
57+
(4100, 4093), // FFD
58+
(4101, 4093), // FFD <-
59+
(4102, 4094), // FFE
60+
(4103, 4095), // FFF
61+
];
62+
63+
for (input, expected) in values {
64+
let actual = super::max_bytes_to_read(input);
65+
assert_eq!(
66+
actual, expected,
67+
"\n\nexpected max_bytes_to_read({}) to be {}, but it was {}",
68+
input, expected, actual
69+
);
70+
71+
// testing the test:
72+
let used_bytes = expected + 4 + format!("{:X}", expected).len();
73+
assert!(
74+
used_bytes == input || used_bytes == input - 1,
75+
"\n\nfor an input of {}, expected used bytes to be {} or {}, but was {}",
76+
input,
77+
input,
78+
input - 1,
79+
used_bytes
80+
);
81+
}
82+
}
3283
}
3384

3485
impl<R: Read + Unpin> Read for ChunkedEncoder<R> {

tests/client_decode.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@ mod client_decode {
22
use async_h1::client;
33
use async_std::io::Cursor;
44
use http_types::headers;
5+
use http_types::Response;
56
use http_types::Result;
67
use pretty_assertions::assert_eq;
78

8-
async fn decode_lines(s: Vec<&str>) -> http_types::Result<http_types::Response> {
9-
client::decode(Cursor::new(dbg!(s.join("\r\n")))).await
9+
async fn decode_lines(s: Vec<&str>) -> Result<Response> {
10+
client::decode(Cursor::new(s.join("\r\n"))).await
1011
}
1112

1213
#[async_std::test]

0 commit comments

Comments
 (0)