impl Iterator for Chunk

This commit is contained in:
Tangent Wantwight 2020-05-06 21:50:03 -04:00
parent dbcbf2831e
commit 9274fabeea
4 changed files with 38 additions and 5 deletions

2
Cargo.lock generated
View File

@ -1768,7 +1768,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "webmetro"
version = "0.2.3-dev"
version = "0.3.0-dev"
dependencies = [
"bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
"clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)",

View File

@ -1,6 +1,6 @@
[package]
name = "webmetro"
version = "0.2.3-dev"
version = "0.3.0-dev"
authors = ["Tangent 128 <Tangent128@gmail.com>"]
edition = "2018"

View File

@ -61,16 +61,47 @@ pub enum Chunk {
ClusterHead(ClusterHead),
ClusterBody {
bytes: Bytes
},
Empty
}
pub struct Iter(Chunk);
impl Iterator for Chunk {
type Item = Bytes;
fn next(&mut self) -> Option<Bytes> {
match self {
Chunk::Headers {ref mut bytes, ..} => {
let bytes = mem::replace(bytes, Bytes::new());
*self = Chunk::Empty;
Some(bytes)
},
Chunk::ClusterHead(ClusterHead {bytes, ..}) => {
let bytes = mem::replace(bytes, BytesMut::new());
*self = Chunk::Empty;
Some(bytes.freeze())
},
Chunk::ClusterBody {bytes, ..} => {
let bytes = mem::replace(bytes, Bytes::new());
*self = Chunk::Empty;
Some(bytes)
},
Chunk::Empty => None
}
}
}
// impl Buf???
impl Chunk {
/// converts this chunk of data into a Bytes object, perhaps to send over the network
pub fn into_bytes(self) -> Bytes {
match self {
Chunk::Headers {bytes, ..} => bytes,
Chunk::ClusterHead(cluster_head) => cluster_head.bytes.freeze(),
Chunk::ClusterBody {bytes, ..} => bytes
Chunk::ClusterBody {bytes, ..} => bytes,
Chunk::Empty => Bytes::new(),
}
}
}

View File

@ -43,7 +43,9 @@ pub fn run(args: &ArgMatches) -> Result<(), WebmetroError> {
chunk_stream = Box::new(Throttle::new(chunk_stream));
}
Runtime::new().unwrap().block_on(chunk_stream.try_for_each(|chunk| {
ready(io::stdout().write_all(&chunk.into_bytes()).map_err(WebmetroError::from))
Runtime::new().unwrap().block_on(chunk_stream.try_for_each(|mut chunk| {
ready(chunk.try_for_each(|buffer|
io::stdout().write_all(&buffer).map_err(WebmetroError::from)
))
}))
}