Skip to content

Commit

Permalink
perf: Bypass UTF-8 validation overhead
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Nov 20, 2018
1 parent 58eec66 commit c759fc3
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ impl Template {
const BEST_GUESS: usize = 10_000;
let mut data = Vec::with_capacity(BEST_GUESS);
self.render_to(&mut data, globals)?;
Ok(String::from_utf8(data).expect("render only writes UTF-8"))

Ok(convert_buffer(data))
}

/// Renders an instance of the Template, using the given globals.
Expand All @@ -29,3 +30,14 @@ impl Template {
self.template.render_to(writer, &mut data)
}
}

#[cfg(debug_assertions)]
fn convert_buffer(buffer: Vec<u8>) -> String {
String::from_utf8(buffer)
.expect("render can only write UTF-8 because all inputs and processing preserve utf-8")
}

#[cfg(not(debug_assertions))]
fn convert_buffer(buffer: Vec<u8>) -> String {
unsafe { String::from_utf8_unchecked(buffer) }
}

0 comments on commit c759fc3

Please sign in to comment.