type_key/
lib.rs

1/*
2 * Created on Thu Jun 22 2023
3 *
4 * Copyright (c) storycraft. Licensed under the MIT Licence.
5 */
6
7#![doc = include_str!("../README.md")]
8
9use core::{
10    any::{Any, TypeId}
11};
12use std::marker::PhantomData;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
15#[repr(transparent)]
16pub struct TypeKey(TypeId);
17
18impl TypeKey {
19    pub fn of<T: ?Sized>() -> TypeKey {
20        TypeKey(
21            (|| {
22                let _ = PhantomData::<T>;
23            })
24            .type_id(),
25        )
26    }
27
28    pub fn of_val<T: ?Sized>(_: &T) -> TypeKey {
29        Self::of::<T>()
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use crate::TypeKey;
36
37    #[test]
38    fn test_same_type() {
39        assert_eq!(TypeKey::of::<()>(), TypeKey::of::<()>())
40    }
41
42    #[test]
43    fn test_different_type() {
44        assert_ne!(TypeKey::of::<u32>(), TypeKey::of::<u8>())
45    }
46
47    #[test]
48    fn test_closures() {
49        assert_ne!(TypeKey::of_val(&|| {}), TypeKey::of_val(&|| {}))
50    }
51}