use crate::SafeHtmlPart;
use crate::types::SafeHtml;
use alloc::string::String;
#[derive(Debug, Clone, Default)]
pub struct SafeHtmlBuilder {
html: String,
}
impl SafeHtmlBuilder {
pub const fn new() -> Self {
SafeHtmlBuilder {
html: String::new(),
}
}
pub fn with_capacity(capacity: usize) -> Self {
SafeHtmlBuilder {
html: String::with_capacity(capacity),
}
}
pub fn reserve(&mut self, additional: usize) {
self.html.reserve(additional);
}
pub fn push(&mut self, part: impl SafeHtmlPart) -> &mut Self {
self.html.reserve(part.size_hint());
let _ = part.write_to(&mut self.html);
self
}
pub fn len(&self) -> usize {
self.html.len()
}
pub fn is_empty(&self) -> bool {
self.html.is_empty()
}
pub fn as_str(&self) -> &str {
&self.html
}
pub fn finish(self) -> SafeHtml {
unsafe { SafeHtml::from_string_unchecked(self.html) }
}
#[doc(hidden)]
pub fn __format_named(&mut self, fmt: &str, parts: &[(&str, &dyn crate::DynPart)]) {
crate::format::format_named_into(&mut self.html, fmt, parts);
}
#[doc(hidden)]
pub fn __format_positional(&mut self, fmt: &str, parts: &[&dyn crate::DynPart]) {
crate::format::format_positional_into(&mut self.html, fmt, parts);
}
}
impl From<SafeHtml> for SafeHtmlBuilder {
fn from(value: SafeHtml) -> Self {
SafeHtmlBuilder {
html: value.into_string(),
}
}
}
impl From<SafeHtmlBuilder> for SafeHtml {
fn from(value: SafeHtmlBuilder) -> Self {
value.finish()
}
}
impl<P: SafeHtmlPart> Extend<P> for SafeHtmlBuilder {
fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) {
for part in iter {
self.push(part);
}
}
}