1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
//! This module contains the implementation yew's virtual nodes' keys.

use crate::html::ImplicitClone;
use std::fmt::{self, Display, Formatter};
use std::ops::Deref;
use std::rc::Rc;

/// Represents the (optional) key of Yew's virtual nodes.
///
/// Keys are cheap to clone.
#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Key {
    key: Rc<str>,
}

impl Display for Key {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.key.fmt(f)
    }
}

impl Deref for Key {
    type Target = str;

    fn deref(&self) -> &str {
        self.key.as_ref()
    }
}

impl From<Rc<str>> for Key {
    fn from(key: Rc<str>) -> Self {
        Self { key }
    }
}

impl From<&'_ str> for Key {
    fn from(key: &'_ str) -> Self {
        let key: Rc<str> = Rc::from(key);
        Self::from(key)
    }
}

impl ImplicitClone for Key {}

macro_rules! key_impl_from_to_string {
    ($type:ty) => {
        impl From<$type> for Key {
            fn from(key: $type) -> Self {
                Self::from(key.to_string().as_str())
            }
        }
    };
}

key_impl_from_to_string!(String);
key_impl_from_to_string!(char);
key_impl_from_to_string!(u8);
key_impl_from_to_string!(u16);
key_impl_from_to_string!(u32);
key_impl_from_to_string!(u64);
key_impl_from_to_string!(u128);
key_impl_from_to_string!(usize);
key_impl_from_to_string!(i8);
key_impl_from_to_string!(i16);
key_impl_from_to_string!(i32);
key_impl_from_to_string!(i64);
key_impl_from_to_string!(i128);
key_impl_from_to_string!(isize);

#[cfg(test)]
mod test {
    use crate::html;
    use std::rc::Rc;

    #[cfg(feature = "wasm_test")]
    use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};

    #[cfg(feature = "wasm_test")]
    wasm_bindgen_test_configure!(run_in_browser);

    #[test]
    fn all_key_conversions() {
        html! {
            <key="string literal">
                <img key="String".to_owned() />
                <p key=Rc::<str>::from("rc")></p>
                <key='a'>
                    <p key=11_usize></p>
                    <p key=12_u8></p>
                    <p key=13_u16></p>
                    <p key=14_u32></p>
                    <p key=15_u64></p>
                    <p key=15_u128></p>
                    <p key=21_isize></p>
                    <p key=22_i8></p>
                    <p key=23_i16></p>
                    <p key=24_i32></p>
                    <p key=25_i128></p>
                </>
            </>
        };
    }
}