1use std::fmt::{self, Display, Formatter};
4use std::ops::Deref;
5use std::rc::Rc;
6
7use crate::html::ImplicitClone;
8
9#[derive(Clone, ImplicitClone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
13pub struct Key {
14 key: Rc<str>,
15}
16
17impl Display for Key {
18 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
19 self.key.fmt(f)
20 }
21}
22
23impl Deref for Key {
24 type Target = str;
25
26 fn deref(&self) -> &str {
27 self.key.as_ref()
28 }
29}
30
31impl From<Rc<str>> for Key {
32 fn from(key: Rc<str>) -> Self {
33 Self { key }
34 }
35}
36
37impl From<&'_ str> for Key {
38 fn from(key: &'_ str) -> Self {
39 let key: Rc<str> = Rc::from(key);
40 Self::from(key)
41 }
42}
43
44impl From<String> for Key {
45 fn from(key: String) -> Self {
46 Self::from(key.as_str())
47 }
48}
49
50macro_rules! key_impl_from_to_string {
51 ($type:ty) => {
52 impl From<$type> for Key {
53 fn from(key: $type) -> Self {
54 Self::from(key.to_string().as_str())
55 }
56 }
57 };
58}
59
60key_impl_from_to_string!(char);
61key_impl_from_to_string!(u8);
62key_impl_from_to_string!(u16);
63key_impl_from_to_string!(u32);
64key_impl_from_to_string!(u64);
65key_impl_from_to_string!(u128);
66key_impl_from_to_string!(usize);
67key_impl_from_to_string!(i8);
68key_impl_from_to_string!(i16);
69key_impl_from_to_string!(i32);
70key_impl_from_to_string!(i64);
71key_impl_from_to_string!(i128);
72key_impl_from_to_string!(isize);
73
74#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
75#[cfg(test)]
76mod test {
77 use std::rc::Rc;
78
79 use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
80
81 use crate::html;
82
83 wasm_bindgen_test_configure!(run_in_browser);
84
85 #[test]
86 fn all_key_conversions() {
87 let _ = html! {
88 <key="string literal">
89 <img key={"String".to_owned()} />
90 <p key={Rc::<str>::from("rc")}></p>
91 <key='a'>
92 <p key=11_usize></p>
93 <p key=12_u8></p>
94 <p key=13_u16></p>
95 <p key=14_u32></p>
96 <p key=15_u64></p>
97 <p key=16_u128></p>
98 <p key=21_isize></p>
99 <p key=22_i8></p>
100 <p key=23_i16></p>
101 <p key=24_i32></p>
102 <p key=25_i128></p>
103 </>
104 </>
105 };
106 }
107}