Skip to content

Commit 1f397c4

Browse files
committed
feat: CSSInliner.inline_to associated method that writes the inlined document to a generic writer
1 parent 89092df commit 1f397c4

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
- `CSSInliner` and customization options. [#9](https://github.com/Stranger6667/css-inline/issues/9)
88
- Option to remove "style" tags. [#11](https://github.com/Stranger6667/css-inline/issues/11)
99
- `CSSInliner::compact()` constructor for producing smaller HTML output.
10+
- `CSSInliner.inline_to` that writes the output to a generic writer. [#24](https://github.com/Stranger6667/css-inline/issues/24)
1011

1112
### Changed
1213

src/lib.rs

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ mod parser;
134134

135135
pub use error::InlineError;
136136
use std::collections::HashMap;
137+
use std::io::Write;
137138

138139
#[derive(Debug)]
139140
struct Rule<'i> {
@@ -201,9 +202,19 @@ impl CSSInliner {
201202
}
202203
}
203204

204-
/// Inline CSS styles from <style> tags to matching elements in the HTML tree.
205+
/// Inline CSS styles from <style> tags to matching elements in the HTML tree and return a
206+
/// string.
205207
#[inline]
206208
pub fn inline(&self, html: &str) -> Result<String, InlineError> {
209+
let mut out = vec![];
210+
self.inline_to(html, &mut out)?;
211+
Ok(String::from_utf8_lossy(&out).to_string())
212+
}
213+
214+
/// Inline CSS & write the result to a generic writer. Use it if you want to write
215+
/// the inlined document to a file.
216+
#[inline]
217+
pub fn inline_to<W: Write>(&self, html: &str, target: &mut W) -> Result<(), InlineError> {
207218
let document = parse_html().one(html);
208219
for style_tag in document
209220
.select("style")
@@ -245,9 +256,8 @@ impl CSSInliner {
245256
style_tag.as_node().detach()
246257
}
247258
}
248-
let mut out = vec![];
249-
document.serialize(&mut out)?;
250-
Ok(String::from_utf8_lossy(&out).to_string())
259+
document.serialize(target)?;
260+
Ok(())
251261
}
252262
}
253263

@@ -264,6 +274,12 @@ pub fn inline(html: &str) -> Result<String, InlineError> {
264274
CSSInliner::default().inline(html)
265275
}
266276

277+
/// Shortcut for inlining CSS with default parameters and writing the output to a generic writer.
278+
#[inline]
279+
pub fn inline_to<W: Write>(html: &str, target: &mut W) -> Result<(), InlineError> {
280+
CSSInliner::default().inline_to(html, target)
281+
}
282+
267283
fn merge_styles(
268284
existing_style: &str,
269285
new_styles: &[parser::Declaration],

0 commit comments

Comments
 (0)