Skip to content

Commit

Permalink
Append chunks on the fly.
Browse files Browse the repository at this point in the history
  • Loading branch information
gabi-250 committed Nov 15, 2019
1 parent bbf3857 commit a63116a
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 19 deletions.
4 changes: 2 additions & 2 deletions examples/on_end_append/main.rs
Expand Up @@ -17,8 +17,8 @@ fn main() {
Settings {
document_content_handlers: vec![end!(|end| {
end.append("hello\n", ContentType::Text);
end.append("<div>\nworld\n</div>", ContentType::Text);
end.append("<div>\n!!!\n</div>", ContentType::Html);
end.append("<div>\n world\n</div>\n", ContentType::Text);
end.append("<div>\n !!!\n</div>\n", ContentType::Html);
Ok(())
})],
..Settings::default()
Expand Down
21 changes: 9 additions & 12 deletions src/rewritable_units/document_end.rs
Expand Up @@ -2,27 +2,24 @@ use super::mutations::content_to_bytes;
use super::ContentType;
use encoding_rs::Encoding;

pub struct DocumentEnd {
content: Vec<(String, ContentType)>,
pub struct DocumentEnd<'a> {
output_handler: &'a mut dyn FnMut(&[u8]),
encoding: &'static Encoding,
}

impl DocumentEnd {
pub(crate) fn new(encoding: &'static Encoding) -> Self {
impl<'a> DocumentEnd<'a> {
pub(crate) fn new(
output_handler: &'a mut dyn FnMut(&[u8]),
encoding: &'static Encoding,
) -> Self {
DocumentEnd {
content: Default::default(),
output_handler,
encoding,
}
}

#[inline]
pub fn append(&mut self, content: &str, content_type: ContentType) {
self.content.push((content.to_string(), content_type));
}

pub(crate) fn content_to_bytes(self, output_handler: &mut dyn FnMut(&[u8])) {
for (content, content_type) in self.content {
content_to_bytes(&content, content_type, self.encoding, output_handler);
}
content_to_bytes(content, content_type, self.encoding, self.output_handler);
}
}
11 changes: 6 additions & 5 deletions src/transform_stream/dispatcher.rs
Expand Up @@ -108,12 +108,13 @@ where
pub fn finish(&mut self, input: &[u8]) {
self.flush_remaining_input(input, input.len());

let mut document_end = DocumentEnd::new(self.encoding);
let output_sink = &mut self.output_sink;
let mut output_sink_handle_chunk = |c: &[u8]| output_sink.handle_chunk(c);
let mut document_end = DocumentEnd::new(&mut output_sink_handle_chunk, self.encoding);

self.transform_controller.handle_end(&mut document_end);
document_end.content_to_bytes(&mut |c| {
self.output_sink.handle_chunk(c);
});
self.transform_controller
.handle_end(&mut document_end)
.expect("finish failed");

// NOTE: output the finalizing chunk.
self.output_sink.handle_chunk(&[]);
Expand Down

0 comments on commit a63116a

Please sign in to comment.