1use std::{
2 any::Any,
3 hash::{
4 Hash,
5 Hasher,
6 },
7 rc::Rc,
8};
9
10use rustc_hash::FxHasher;
11
12use crate::{
13 diff_key::DiffKey,
14 element::Element,
15};
16
17#[cfg(feature = "test")]
18pub fn from_fn_captured<T: Fn() -> Element + 'static>(comp: T) -> Element {
19 use std::rc::Rc;
20
21 use crate::diff_key::DiffKey;
22
23 Element::Component {
24 key: DiffKey::None,
25 comp: Rc::new(move |_| comp()),
26 props: Rc::new(()),
27 }
28}
29
30#[cfg(feature = "test")]
31pub fn from_fn_standalone(comp: fn() -> Element) -> Element {
32 Element::Component {
33 key: comp.into(),
34 comp: Rc::new(move |_| comp()),
35 props: Rc::new(()),
36 }
37}
38
39#[cfg(feature = "test")]
40pub fn from_fn_standalone_borrowed<P: 'static + PartialEq>(
41 props: P,
42 comp: fn(&P) -> Element,
43) -> Element {
44 Element::Component {
45 key: comp.into(),
46 comp: Rc::new(move |props| {
47 let props = (&*props as &dyn Any).downcast_ref::<P>().unwrap();
48 comp(props)
49 }),
50 props: Rc::new(props),
51 }
52}
53
54pub fn from_fn<P: PartialEq + 'static>(
56 key: impl Hash,
57 props: P,
58 comp: impl Fn(&P) -> Element + 'static,
59) -> Element {
60 let mut hasher = FxHasher::default();
61 key.hash(&mut hasher);
62 Element::Component {
63 key: DiffKey::U64(hasher.finish()),
64 comp: Rc::new(move |props| {
65 let props = (&*props as &dyn Any).downcast_ref::<P>().unwrap();
66 comp(props)
67 }),
68 props: Rc::new(props),
69 }
70}
71
72pub fn from_fn_owned<P: PartialEq + Clone + 'static>(
74 key: impl Hash,
75 props: P,
76 comp: impl Fn(P) -> Element + 'static,
77) -> Element {
78 let mut hasher = FxHasher::default();
79 key.hash(&mut hasher);
80 Element::Component {
81 key: DiffKey::U64(hasher.finish()),
82 comp: Rc::new(move |props| {
83 let props = (&*props as &dyn Any).downcast_ref::<P>().cloned().unwrap();
84 comp(props)
85 }),
86 props: Rc::new(props),
87 }
88}
89
90pub fn from_fn_standalone_borrowed_keyed<K: Hash, P: 'static + PartialEq>(
91 key: K,
92 props: P,
93 comp: fn(&P) -> Element,
94) -> Element {
95 let mut hasher = FxHasher::default();
96 key.hash(&mut hasher);
97 Element::Component {
98 key: DiffKey::U64(hasher.finish()),
99 comp: Rc::new(move |props| {
100 let props = (&*props as &dyn Any).downcast_ref::<P>().unwrap();
101 comp(props)
102 }),
103 props: Rc::new(props),
104 }
105}