Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 23 additions & 13 deletions native/css_inline_nif/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,31 @@ struct Options {
/// since BEAM-managed data must live on the BEAM heap.
#[rustler::nif(schedule = "DirtyCpu")]
fn inline_css(html: &str, opts: Options) -> Result<Vec<u8>, RustlerError> {
let estimated_size = (html.len() as f64 * 1.5) as usize;
let mut buffer: Vec<u8> = Vec::with_capacity(estimated_size);
let inliner = CSSInliner::options()
.inline_style_tags(opts.inline_style_tags)
.keep_style_tags(opts.keep_style_tags)
.keep_link_tags(opts.keep_link_tags)
.load_remote_stylesheets(opts.load_remote_stylesheets)
.minify_css(opts.minify_css)
.build();
std::panic::catch_unwind(|| {
let estimated_size = (html.len() as f64 * 1.5) as usize;
let mut buffer: Vec<u8> = Vec::with_capacity(estimated_size);
let inliner = CSSInliner::options()
.inline_style_tags(opts.inline_style_tags)
.keep_style_tags(opts.keep_style_tags)
.keep_link_tags(opts.keep_link_tags)
.load_remote_stylesheets(opts.load_remote_stylesheets)
.minify_css(opts.minify_css)
.build();

inliner
.inline_to(html, &mut buffer)
.map_err(|e| RustlerError::Term(Box::new(format!("CSS inlining failed: {}", e))))?;
inliner
.inline_to(html, &mut buffer)
.map_err(|e| RustlerError::Term(Box::new(format!("CSS inlining failed: {}", e))))?;

Ok(buffer)
Ok(buffer)
})
.map_err(|e| {
let msg = e
.downcast_ref::<String>()
.map(|s| s.as_str())
.or_else(|| e.downcast_ref::<&str>().copied())
.unwrap_or("unknown panic");
RustlerError::Term(Box::new(format!("NIF panic: {}", msg)))
})?
}

rustler::init!("Elixir.CSSInline.Native");
Loading