chunked_transfer-1.4.0/.cargo_vcs_info.json 0000644 00000000112 00000000000 0014354 0 ustar {
"git": {
"sha1": "060ad65dc3d937b853b0aa0e791af3ad416e69e4"
}
}
chunked_transfer-1.4.0/.gitignore 0000644 0000000 0000000 00000000022 00000000000 0015112 0 ustar 0000000 0000000 target
Cargo.lock
chunked_transfer-1.4.0/.travis.yml 0000644 0000000 0000000 00000000452 00000000000 0015242 0 ustar 0000000 0000000 language: rust
after_success: |
cargo doc && \
echo '' > target/doc/index.html && \
sudo pip install ghp-import && \
ghp-import -n target/doc && \
git push -qf https://${TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
chunked_transfer-1.4.0/Cargo.toml 0000644 00000001612 00000000000 0012360 0 ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies
#
# If you believe there's an error in this file please file an
# issue against the rust-lang/cargo repository. If you're
# editing this file be aware that the upstream Cargo.toml
# will likely look very different (and much more reasonable)
[package]
edition = "2018"
name = "chunked_transfer"
version = "1.4.0"
authors = ["Corey Farwell "]
description = "Encoder and decoder for HTTP chunked transfer coding (RFC 7230 § 4.1)"
license = "Apache-2.0"
repository = "https://github.com/frewsxcv/rust-chunked-transfer"
[[bench]]
name = "encode"
harness = false
[dev-dependencies.criterion]
version = "0.3"
chunked_transfer-1.4.0/Cargo.toml.orig 0000644 0000000 0000000 00000000566 00000000000 0016026 0 ustar 0000000 0000000 [package]
name = "chunked_transfer"
version = "1.4.0"
authors = ["Corey Farwell "]
license = "Apache-2.0"
repository = "https://github.com/frewsxcv/rust-chunked-transfer"
description = "Encoder and decoder for HTTP chunked transfer coding (RFC 7230 § 4.1)"
edition = "2018"
[dev-dependencies]
criterion = "0.3"
[[bench]]
name = "encode"
harness = false
chunked_transfer-1.4.0/LICENSE 0000644 0000000 0000000 00000025137 00000000000 0014145 0 ustar 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
chunked_transfer-1.4.0/README.md 0000644 0000000 0000000 00000002674 00000000000 0014420 0 ustar 0000000 0000000 # rust-chunked-transfer
[](https://travis-ci.org/frewsxcv/rust-chunked-transfer)
[](https://crates.io/crates/chunked\_transfer)
[Documentation](https://docs.rs/chunked_transfer/)
Encoder and decoder for HTTP chunked transfer coding. For more information about chunked transfer encoding:
* [RFC 7230 § 4.1](https://tools.ietf.org/html/rfc7230#section-4.1)
* [RFC 2616 § 3.6.1](http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1) (deprecated)
* [Wikipedia: Chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding)
## Example
### Decoding
```rust
use chunked_transfer::Decoder;
use std::io::Read;
let encoded = b"3\r\nhel\r\nb\r\nlo world!!!\r\n0\r\n\r\n";
let mut decoded = String::new();
let mut decoder = Decoder::new(encoded as &[u8]);
decoder.read_to_string(&mut decoded);
assert_eq!(decoded, "hello world!!!");
```
### Encoding
```rust
use chunked_transfer::Encoder;
use std::io::Write;
let mut decoded = "hello world";
let mut encoded: Vec = vec![];
{
let mut encoder = Encoder::with_chunks_size(&mut encoded, 5);
encoder.write_all(decoded.as_bytes());
}
assert_eq!(encoded, b"5\r\nhello\r\n5\r\n worl\r\n1\r\nd\r\n0\r\n\r\n");
```
## Authors
* [tomaka](https://github.com/tomaka)
* [frewsxcv](https://github.com/frewsxcv)
chunked_transfer-1.4.0/benches/encode.rs 0000644 0000000 0000000 00000001033 00000000000 0016337 0 ustar 0000000 0000000 #![feature(test)]
use chunked_transfer;
use criterion::{criterion_group, criterion_main, Criterion};
use std::io::Write;
extern crate test;
fn encode_benchmark(c: &mut Criterion) {
c.bench_function("encode", |b| {
let writer = vec![];
let mut encoder = chunked_transfer::Encoder::new(writer);
let mut to_write = vec![b'a'; 1000];
b.iter(|| {
test::black_box(encoder.write_all(&mut to_write));
});
});
}
criterion_group!(benches, encode_benchmark);
criterion_main!(benches);
chunked_transfer-1.4.0/src/decoder.rs 0000644 0000000 0000000 00000021135 00000000000 0015674 0 ustar 0000000 0000000 // Copyright 2015 The tiny-http Contributors
// Copyright 2015 The rust-chunked-transfer Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::error::Error;
use std::fmt;
use std::io::Error as IoError;
use std::io::ErrorKind;
use std::io::Read;
use std::io::Result as IoResult;
/// Reads HTTP chunks and sends back real data.
///
/// # Example
///
/// ```
/// use chunked_transfer::Decoder;
/// use std::io::Read;
///
/// let encoded = b"3\r\nhel\r\nb\r\nlo world!!!\r\n0\r\n\r\n";
/// let mut decoded = String::new();
///
/// let mut decoder = Decoder::new(encoded as &[u8]);
/// decoder.read_to_string(&mut decoded);
///
/// assert_eq!(decoded, "hello world!!!");
/// ```
pub struct Decoder {
// where the chunks come from
source: R,
// remaining size of the chunk being read
// none if we are not in a chunk
remaining_chunks_size: Option,
}
impl Decoder
where
R: Read,
{
pub fn new(source: R) -> Decoder {
Decoder {
source,
remaining_chunks_size: None,
}
}
/// Returns the remaining bytes left in the chunk being read.
pub fn remaining_chunks_size(&self) -> Option {
self.remaining_chunks_size
}
/// Unwraps the Decoder into its inner `Read` source.
pub fn into_inner(self) -> R {
self.source
}
fn read_chunk_size(&mut self) -> IoResult {
let mut chunk_size_bytes = Vec::new();
let mut has_ext = false;
loop {
let byte = match self.source.by_ref().bytes().next() {
Some(b) => b?,
None => return Err(IoError::new(ErrorKind::InvalidInput, DecoderError)),
};
if byte == b'\r' {
break;
}
if byte == b';' {
has_ext = true;
break;
}
chunk_size_bytes.push(byte);
}
// Ignore extensions for now
if has_ext {
loop {
let byte = match self.source.by_ref().bytes().next() {
Some(b) => b?,
None => return Err(IoError::new(ErrorKind::InvalidInput, DecoderError)),
};
if byte == b'\r' {
break;
}
}
}
self.read_line_feed()?;
let chunk_size = String::from_utf8(chunk_size_bytes)
.ok()
.and_then(|c| usize::from_str_radix(c.trim(), 16).ok())
.ok_or_else(|| IoError::new(ErrorKind::InvalidInput, DecoderError))?;
Ok(chunk_size)
}
fn read_carriage_return(&mut self) -> IoResult<()> {
match self.source.by_ref().bytes().next() {
Some(Ok(b'\r')) => Ok(()),
_ => Err(IoError::new(ErrorKind::InvalidInput, DecoderError)),
}
}
fn read_line_feed(&mut self) -> IoResult<()> {
match self.source.by_ref().bytes().next() {
Some(Ok(b'\n')) => Ok(()),
_ => Err(IoError::new(ErrorKind::InvalidInput, DecoderError)),
}
}
}
impl Read for Decoder
where
R: Read,
{
fn read(&mut self, buf: &mut [u8]) -> IoResult {
let remaining_chunks_size = match self.remaining_chunks_size {
Some(c) => c,
None => {
// first possibility: we are not in a chunk, so we'll attempt to determine
// the chunks size
let chunk_size = self.read_chunk_size()?;
// if the chunk size is 0, we are at EOF
if chunk_size == 0 {
self.read_carriage_return()?;
self.read_line_feed()?;
return Ok(0);
}
chunk_size
}
};
// second possibility: we continue reading from a chunk
if buf.len() < remaining_chunks_size {
let read = self.source.read(buf)?;
self.remaining_chunks_size = Some(remaining_chunks_size - read);
return Ok(read);
}
// third possibility: the read request goes further than the current chunk
// we simply read until the end of the chunk and return
assert!(buf.len() >= remaining_chunks_size);
let buf = &mut buf[..remaining_chunks_size];
let read = self.source.read(buf)?;
self.remaining_chunks_size = if read == remaining_chunks_size {
self.read_carriage_return()?;
self.read_line_feed()?;
None
} else {
Some(remaining_chunks_size - read)
};
Ok(read)
}
}
#[derive(Debug, Copy, Clone)]
struct DecoderError;
impl fmt::Display for DecoderError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(fmt, "Error while decoding chunks")
}
}
impl Error for DecoderError {
fn description(&self) -> &str {
"Error while decoding chunks"
}
}
#[cfg(test)]
mod test {
use super::Decoder;
use std::io;
use std::io::Read;
/// This unit test is taken from from Hyper
/// https://github.com/hyperium/hyper
/// Copyright (c) 2014 Sean McArthur
#[test]
fn test_read_chunk_size() {
fn read(s: &str, expected: usize) {
let mut decoded = Decoder::new(s.as_bytes());
let actual = decoded.read_chunk_size().unwrap();
assert_eq!(expected, actual);
}
fn read_err(s: &str) {
let mut decoded = Decoder::new(s.as_bytes());
let err_kind = decoded.read_chunk_size().unwrap_err().kind();
assert_eq!(err_kind, io::ErrorKind::InvalidInput);
}
read("1\r\n", 1);
read("01\r\n", 1);
read("0\r\n", 0);
read("00\r\n", 0);
read("A\r\n", 10);
read("a\r\n", 10);
read("Ff\r\n", 255);
read("Ff \r\n", 255);
// Missing LF or CRLF
read_err("F\rF");
read_err("F");
// Invalid hex digit
read_err("X\r\n");
read_err("1X\r\n");
read_err("-\r\n");
read_err("-1\r\n");
// Acceptable (if not fully valid) extensions do not influence the size
read("1;extension\r\n", 1);
read("a;ext name=value\r\n", 10);
read("1;extension;extension2\r\n", 1);
read("1;;; ;\r\n", 1);
read("2; extension...\r\n", 2);
read("3 ; extension=123\r\n", 3);
read("3 ;\r\n", 3);
read("3 ; \r\n", 3);
// Invalid extensions cause an error
read_err("1 invalid extension\r\n");
read_err("1 A\r\n");
read_err("1;no CRLF");
}
#[test]
fn test_valid_chunk_decode() {
let source = io::Cursor::new(
"3\r\nhel\r\nb\r\nlo world!!!\r\n0\r\n\r\n"
.to_string()
.into_bytes(),
);
let mut decoded = Decoder::new(source);
let mut string = String::new();
decoded.read_to_string(&mut string).unwrap();
assert_eq!(string, "hello world!!!");
}
#[test]
fn test_decode_zero_length() {
let mut decoder = Decoder::new(b"0\r\n\r\n" as &[u8]);
let mut decoded = String::new();
decoder.read_to_string(&mut decoded).unwrap();
assert_eq!(decoded, "");
}
#[test]
fn test_decode_invalid_chunk_length() {
let mut decoder = Decoder::new(b"m\r\n\r\n" as &[u8]);
let mut decoded = String::new();
assert!(decoder.read_to_string(&mut decoded).is_err());
}
#[test]
fn invalid_input1() {
let source = io::Cursor::new(
"2\r\nhel\r\nb\r\nlo world!!!\r\n0\r\n"
.to_string()
.into_bytes(),
);
let mut decoded = Decoder::new(source);
let mut string = String::new();
assert!(decoded.read_to_string(&mut string).is_err());
}
#[test]
fn invalid_input2() {
let source = io::Cursor::new(
"3\rhel\r\nb\r\nlo world!!!\r\n0\r\n"
.to_string()
.into_bytes(),
);
let mut decoded = Decoder::new(source);
let mut string = String::new();
assert!(decoded.read_to_string(&mut string).is_err());
}
}
chunked_transfer-1.4.0/src/encoder.rs 0000644 0000000 0000000 00000014154 00000000000 0015711 0 ustar 0000000 0000000 // Copyright 2015 The tiny-http Contributors
// Copyright 2015 The rust-chunked-transfer Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::Result as IoResult;
use std::io::Write;
/// Splits the incoming data into HTTP chunks.
///
/// # Example
///
/// ```
/// use chunked_transfer::Encoder;
/// use std::io::Write;
///
/// let mut decoded = "hello world";
/// let mut encoded: Vec = vec![];
///
/// {
/// let mut encoder = Encoder::with_chunks_size(&mut encoded, 5);
/// encoder.write_all(decoded.as_bytes());
/// }
///
/// assert_eq!(encoded, b"5\r\nhello\r\n5\r\n worl\r\n1\r\nd\r\n0\r\n\r\n");
/// ```
pub struct Encoder
where
W: Write,
{
// where to send the result
output: W,
// size of each chunk
chunks_size: usize,
// data waiting to be sent is stored here
// This will always be at least 6 bytes long. The first 6 bytes
// are reserved for the chunk size and \r\n.
buffer: Vec,
// Flushes the internal buffer after each write. This might be useful
// if data should be sent immediately to downstream consumers
flush_after_write: bool,
}
const MAX_CHUNK_SIZE: usize = std::u32::MAX as usize;
// This accounts for four hex digits (enough to hold a u32) plus two bytes
// for the \r\n
const MAX_HEADER_SIZE: usize = 6;
impl Encoder
where
W: Write,
{
pub fn new(output: W) -> Encoder {
Encoder::with_chunks_size(output, 8192)
}
pub fn with_chunks_size(output: W, chunks: usize) -> Encoder {
let chunks_size = chunks.min(MAX_CHUNK_SIZE);
let mut encoder = Encoder {
output,
chunks_size,
buffer: vec![0; MAX_HEADER_SIZE],
flush_after_write: false,
};
encoder.reset_buffer();
encoder
}
pub fn with_flush_after_write(output: W) -> Encoder {
let mut encoder = Encoder {
output,
chunks_size: 8192,
buffer: vec![0; MAX_HEADER_SIZE],
flush_after_write: true,
};
encoder.reset_buffer();
encoder
}
fn reset_buffer(&mut self) {
// Reset buffer, still leaving space for the chunk size. That space
// will be populated once we know the size of the chunk.
self.buffer.truncate(MAX_HEADER_SIZE);
}
fn is_buffer_empty(&self) -> bool {
self.buffer.len() == MAX_HEADER_SIZE
}
fn buffer_len(&self) -> usize {
self.buffer.len() - MAX_HEADER_SIZE
}
fn send(&mut self) -> IoResult<()> {
// Never send an empty buffer, because that would be interpreted
// as the end of the stream, which we indicate explicitly on drop.
if self.is_buffer_empty() {
return Ok(());
}
// Prepend the length and \r\n to the buffer.
let prelude = format!("{:x}\r\n", self.buffer_len());
let prelude = prelude.as_bytes();
// This should never happen because MAX_CHUNK_SIZE of u32::MAX
// can always be encoded in 4 hex bytes.
assert!(
prelude.len() <= MAX_HEADER_SIZE,
"invariant failed: prelude longer than MAX_HEADER_SIZE"
);
// Copy the prelude into the buffer. For small chunks, this won't necessarily
// take up all the space that was reserved for the prelude.
let offset = MAX_HEADER_SIZE - prelude.len();
self.buffer[offset..MAX_HEADER_SIZE].clone_from_slice(&prelude);
// Append the chunk-finishing \r\n to the buffer.
self.buffer.write_all(b"\r\n")?;
self.output.write_all(&self.buffer[offset..])?;
self.reset_buffer();
Ok(())
}
}
impl Write for Encoder
where
W: Write,
{
fn write(&mut self, data: &[u8]) -> IoResult {
let remaining_buffer_space = self.chunks_size - self.buffer_len();
let bytes_to_buffer = std::cmp::min(remaining_buffer_space, data.len());
self.buffer.extend_from_slice(&data[0..bytes_to_buffer]);
let more_to_write: bool = bytes_to_buffer < data.len();
if self.flush_after_write || more_to_write {
self.send()?;
}
// If we didn't write the whole thing, keep working on it.
if more_to_write {
self.write_all(&data[bytes_to_buffer..])?;
}
Ok(data.len())
}
fn flush(&mut self) -> IoResult<()> {
self.send()
}
}
impl Drop for Encoder
where
W: Write,
{
fn drop(&mut self) {
self.flush().ok();
write!(self.output, "0\r\n\r\n").ok();
}
}
#[cfg(test)]
mod test {
use super::Encoder;
use std::io;
use std::io::Write;
use std::str::from_utf8;
#[test]
fn test() {
let mut source = io::Cursor::new("hello world".to_string().into_bytes());
let mut dest: Vec = vec![];
{
let mut encoder = Encoder::with_chunks_size(dest.by_ref(), 5);
io::copy(&mut source, &mut encoder).unwrap();
assert!(!encoder.is_buffer_empty());
}
let output = from_utf8(&dest).unwrap();
assert_eq!(output, "5\r\nhello\r\n5\r\n worl\r\n1\r\nd\r\n0\r\n\r\n");
}
#[test]
fn flush_after_write() {
let mut source = io::Cursor::new("hello world".to_string().into_bytes());
let mut dest: Vec = vec![];
{
let mut encoder = Encoder::with_flush_after_write(dest.by_ref());
io::copy(&mut source, &mut encoder).unwrap();
// The internal buffer has been flushed.
assert!(encoder.is_buffer_empty());
}
let output = from_utf8(&dest).unwrap();
assert_eq!(output, "b\r\nhello world\r\n0\r\n\r\n");
}
}
chunked_transfer-1.4.0/src/lib.rs 0000644 0000000 0000000 00000001356 00000000000 0015040 0 ustar 0000000 0000000 // Copyright 2015 The tiny-http Contributors
// Copyright 2015 The rust-chunked-transfer Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod decoder;
pub use crate::decoder::Decoder;
mod encoder;
pub use crate::encoder::Encoder;