hemplate_runtime/lib.rs
1//! hemplate-runtime: parser-free rendering contract for hemplate templates.
2//!
3//! This crate contains only the symbols needed to render a generated hemplate
4//! template on a target device. It has no parser or proc-macro dependencies,
5//! so it compiles for constrained targets such as `wasm32-unknown-unknown`.
6//!
7//! Applications normally use the `hemplate` facade crate, which re-exports this
8//! runtime API and optionally enables the `derive` feature for
9//! `#[derive(Hemplate)]`.
10
11#![no_std]
12#![warn(missing_docs)]
13
14extern crate alloc;
15
16use alloc::string::String;
17
18#[cfg(test)]
19extern crate std;
20
21/// Error types.
22pub mod error;
23/// HTML escape utility.
24pub mod escape;
25/// Codegen dispatch helpers for interpolation.
26pub mod render;
27
28pub use error::RenderError;
29pub use escape::HtmlEscape;
30
31/// Trait for types that can render themselves as an HTML string.
32///
33/// `Display` is NOT a supertrait — `Hemplate` types produce safe HTML,
34/// while `Display` types produce text that needs escaping. The derive
35/// macro generates a `Hemplate` impl; it does not generate `Display`.
36/// `render_into` is the required method, while `render` is a top-level
37/// convenience that allocates one output string.
38pub trait Hemplate {
39 /// Render this template into the provided buffer.
40 fn render_into(&self, buf: &mut dyn core::fmt::Write) -> Result<(), RenderError>;
41
42 /// Estimated output bytes used to pre-size a rendering buffer.
43 ///
44 /// Manual implementations may keep the conservative default. Derived templates use their
45 /// static source length, which avoids repeated growth without promising an exact output size.
46 fn size_hint(&self) -> usize {
47 0
48 }
49
50 /// Render this template to a new string.
51 fn render(&self) -> Result<String, RenderError> {
52 let mut buf = String::with_capacity(self.size_hint());
53 self.render_into(&mut buf)?;
54 Ok(buf)
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 struct Empty;
63
64 impl Hemplate for Empty {
65 fn render_into(&self, _buf: &mut dyn core::fmt::Write) -> Result<(), RenderError> {
66 Ok(())
67 }
68 }
69
70 struct Text;
71
72 impl Hemplate for Text {
73 fn render_into(&self, buf: &mut dyn core::fmt::Write) -> Result<(), RenderError> {
74 buf.write_str("rendered")?;
75 Ok(())
76 }
77 }
78
79 struct Failing;
80
81 impl Hemplate for Failing {
82 fn render_into(&self, _buf: &mut dyn core::fmt::Write) -> Result<(), RenderError> {
83 Err(core::fmt::Error.into())
84 }
85 }
86
87 #[test]
88 fn manual_implementation_defaults_to_no_size_hint() {
89 assert_eq!(Empty.size_hint(), 0);
90 }
91
92 #[test]
93 fn render_returns_generated_output_and_propagates_failure() -> Result<(), RenderError> {
94 assert_eq!(Text.render()?, "rendered");
95 assert!(Failing.render().is_err());
96 Ok(())
97 }
98}