clapi/
typing.rs

1use std::any::TypeId;
2use std::cmp::Ordering;
3use std::hash::{Hash, Hasher};
4
5/// Represents a type.
6///
7/// # Example
8/// ```
9/// use clapi::typing::Type;
10/// use std::any::TypeId;
11///
12/// let r#type = Type::of::<i64>();
13/// assert_eq!(r#type.name(), "i64");
14/// assert_eq!(r#type.id(), TypeId::of::<i64>());
15/// ```
16#[derive(Debug, Clone, Copy)]
17pub struct Type {
18    type_name: &'static str,
19    type_id: TypeId,
20}
21
22impl Type {
23    /// Constructs a new `Type` from the given `T`.
24    pub fn of<T: 'static>() -> Self {
25    // pub const fn of<T: 'static>() -> Self {
26        let type_name = std::any::type_name::<T>();
27        let type_id = std::any::TypeId::of::<T>();
28        Type { type_name, type_id }
29    }
30
31    /// Returns the type name of this type.
32    pub const fn name(&self) -> &'static str {
33        self.type_name
34    }
35
36    /// Returns the `TypeId` of this type.
37    pub const fn id(&self) -> TypeId {
38        self.type_id
39    }
40}
41
42impl Eq for Type {}
43
44impl PartialEq for Type {
45    fn eq(&self, other: &Self) -> bool {
46        self.type_id == other.type_id
47    }
48}
49
50impl Ord for Type {
51    fn cmp(&self, other: &Self) -> Ordering {
52        self.type_id.cmp(&other.type_id)
53    }
54}
55
56impl PartialOrd for Type {
57    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
58        self.type_id.partial_cmp(&other.type_id)
59    }
60}
61
62impl Hash for Type {
63    fn hash<H: Hasher>(&self, state: &mut H) {
64        self.type_id.hash(state)
65    }
66}