mirror of
https://github.com/askama-rs/askama.git
synced 2025-10-02 07:20:55 +00:00
Speed up writing into io::Write
e.g. Vec<u8>
```text $ cd testing $ cargo bench --bench all Big table (io) time: [109.07 µs 109.25 µs 109.45 µs] change: [-42.044% -41.581% -41.182%] (p = 0.00 < 0.05) Performance has improved. Teams (io) time: [265.28 ns 266.07 ns 267.12 ns] change: [-20.221% -19.898% -19.538%] (p = 0.00 < 0.05) Performance has improved. ```
This commit is contained in:
parent
cb35670afc
commit
324e5fc76b
@ -88,9 +88,30 @@ pub trait Template: fmt::Display {
|
||||
fn render_into<W: fmt::Write + ?Sized>(&self, writer: &mut W) -> Result<()>;
|
||||
|
||||
/// Renders the template to the given `writer` io buffer
|
||||
#[inline]
|
||||
fn write_into<W: io::Write + ?Sized>(&self, writer: &mut W) -> io::Result<()> {
|
||||
writer.write_fmt(format_args!("{self}"))
|
||||
struct Wrapped<W: io::Write> {
|
||||
writer: W,
|
||||
err: Option<io::Error>,
|
||||
}
|
||||
|
||||
impl<W: io::Write> fmt::Write for Wrapped<W> {
|
||||
fn write_str(&mut self, s: &str) -> fmt::Result {
|
||||
if let Err(err) = self.writer.write_all(s.as_bytes()) {
|
||||
self.err = Some(err);
|
||||
Err(fmt::Error)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut wrapped = Wrapped { writer, err: None };
|
||||
if self.render_into(&mut wrapped).is_ok() {
|
||||
Ok(())
|
||||
} else {
|
||||
let err = wrapped.err.take();
|
||||
Err(err.unwrap_or_else(|| io::Error::new(io::ErrorKind::Other, fmt::Error)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The template's extension, if provided
|
||||
|
Loading…
x
Reference in New Issue
Block a user