Skip to content

Commit e9a3e49

Browse files
authored
Add Default trait impl for Lazy to enable struct field defaults (#167)
1 parent 520fcba commit e9a3e49

2 files changed

Lines changed: 51 additions & 1 deletion

File tree

hypertext/src/alloc/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,13 @@ impl<F: Fn(&mut Buffer<C>), C: Context> Debug for Lazy<F, C> {
312312
}
313313
}
314314

315+
impl<C: Context> Default for Lazy<fn(&mut Buffer<C>), C> {
316+
#[inline]
317+
fn default() -> Lazy<fn(&mut Buffer<C>), C> {
318+
Lazy::dangerously_create(|_| ())
319+
}
320+
}
321+
315322
/// A value rendered via its [`Display`] implementation.
316323
///
317324
/// This will handle escaping special characters for you.

hypertext/tests/main.rs

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
use std::fmt::{self, Display, Formatter};
55

6-
use hypertext::{Buffer, Raw, maud_borrow, maud_static, prelude::*, rsx_borrow, rsx_static};
6+
use hypertext::{Buffer, Lazy, Raw, maud_borrow, maud_static, prelude::*, rsx_borrow, rsx_static};
77

88
#[test]
99
fn readme() {
@@ -749,3 +749,46 @@ fn toggles() {
749749
);
750750
assert_eq!(rsx_result.as_inner(), r#"<input type="checkbox" checked>"#);
751751
}
752+
753+
#[test]
754+
fn derive_default() {
755+
#[derive(Default)]
756+
struct Element<'a> {
757+
pub id: &'a str,
758+
pub tabindex: u32,
759+
pub children: Lazy<fn(&mut Buffer)>,
760+
}
761+
762+
impl<'a> Renderable for Element<'a> {
763+
fn render_to(&self, buf: &mut Buffer) {
764+
rsx! {
765+
<div id=(self.id) tabindex=(self.tabindex)>
766+
(self.children)
767+
</div>
768+
}
769+
.render_to(buf)
770+
}
771+
}
772+
773+
let with_children = rsx! {
774+
<Element ..>
775+
<h1>hello</h1>
776+
</Element>
777+
}
778+
.render();
779+
780+
assert_eq!(
781+
with_children.as_inner(),
782+
r#"<div id="" tabindex="0"><h1>hello</h1></div>"#
783+
);
784+
785+
let without_children = rsx! {
786+
<Element ../>
787+
}
788+
.render();
789+
790+
assert_eq!(
791+
without_children.as_inner(),
792+
r#"<div id="" tabindex="0"></div>"#
793+
);
794+
}

0 commit comments

Comments
 (0)