feat: Add TemplateOnce::render_once_to_string method

This commit is contained in:
Kogia-sima 2020-06-18 18:35:39 +09:00
parent b5d035493f
commit f40926122b
2 changed files with 17 additions and 6 deletions

View File

@ -264,23 +264,27 @@ fn derive_template_impl(tokens: TokenStream) -> Result<TokenStream, syn::Error>
let tokens = quote! {
impl #impl_generics sailfish::TemplateOnce for #name #ty_generics #where_clause {
fn render_once(self) -> sailfish::runtime::RenderResult {
fn render_once_to_string(self, buf: &mut String) -> Result<(), sailfish::runtime::RenderError> {
#include_bytes_seq;
use sailfish::runtime as sfrt;
use sfrt::RenderInternal as _;
static SIZE_HINT: sfrt::SizeHint = sfrt::SizeHint::new();
let _size_hint = SIZE_HINT.get();
let mut _ctx = sfrt::Context {
buf: sfrt::Buffer::with_capacity(_size_hint)
buf: sfrt::Buffer::from(std::mem::take(buf))
};
let _size_hint = SIZE_HINT.get();
_ctx.buf.reserve(_size_hint);
let #name { #field_names } = self;
include!(#output_file_string);
SIZE_HINT.update(_ctx.buf.len());
_ctx.into_result()
*buf = _ctx.buf.into_string();
Ok(())
}
}
};

View File

@ -41,8 +41,15 @@ pub mod runtime;
pub use runtime::{RenderError, RenderResult};
/// Template that can be rendered with consuming itself.
pub trait TemplateOnce {
fn render_once(self) -> runtime::RenderResult;
pub trait TemplateOnce: Sized {
#[inline]
fn render_once(self) -> runtime::RenderResult {
let mut buf = String::new();
self.render_once_to_string(&mut buf)?;
Ok(buf)
}
fn render_once_to_string(self, buf: &mut String) -> Result<(), RenderError>;
}
/// WIP