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
/// Marker supertrait for types which may be used as font keys. Note that although
/// the data itself must be static, `str` is a valid FontKey as the key will always
/// be taken by pointer.
pub trait FontKey: Send + Sync + 'static {}
impl<T> FontKey for T where T: Send + Sync + ?Sized + 'static {}

#[repr(C)]
pub(crate) struct KeyPayload<'a, K: FontKey + ?Sized> {
    ty_id: u64,
    pub(crate) data: &'a K,
}

impl<'a, K: FontKey + ?Sized> KeyPayload<'a, K> {
    pub(crate) fn new(data: &'a K) -> Self {
        KeyPayload {
            ty_id: Self::id(),
            data,
        }
    }

    pub(crate) fn valid(&self) -> bool {
        self.ty_id == Self::id()
    }

    pub(crate) fn id() -> u64 {
        use std::hash::Hash;
        let tid = std::any::TypeId::of::<K>();
        let mut h = FnvHasher::default();
        tid.hash(&mut h);
        h.0
    }
}

struct FnvHasher(u64);

impl Default for FnvHasher {
    #[inline]
    fn default() -> FnvHasher {
        FnvHasher(0xcbf29ce484222325)
    }
}

impl std::hash::Hasher for FnvHasher {
    #[inline]
    fn finish(&self) -> u64 {
        self.0
    }

    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        let FnvHasher(mut hash) = *self;

        for byte in bytes.iter() {
            hash = hash ^ (*byte as u64);
            hash = hash.wrapping_mul(0x100000001b3);
        }

        *self = FnvHasher(hash);
    }
}