tf2_enum/
grade.rs

1use strum_macros::{Display, EnumString, EnumIter, EnumCount};
2use num_enum::{TryFromPrimitive, IntoPrimitive};
3use serde_repr::{Serialize_repr, Deserialize_repr};
4
5/// Grade.
6#[derive(
7    Serialize_repr,
8    Deserialize_repr,
9    Debug,
10    Hash,
11    Eq,
12    PartialEq,
13    Ord,
14    PartialOrd,
15    Display,
16    EnumString,
17    EnumIter,
18    EnumCount,
19    TryFromPrimitive,
20    IntoPrimitive,
21    Clone,
22    Copy,
23)]
24#[repr(u32)]
25pub enum Grade {
26    Civilian = 1,
27    Freelance = 2,
28    Mercenary = 3,
29    Commando = 4,
30    Assassin = 5,
31    Elite = 6,
32}
33
34impl Grade {
35    /// Gets the related color of this grade as a hexadecimal color.
36    pub fn color(&self) -> u32 {
37        match self {
38            Self::Civilian => 0xB0C3D9,
39            Self::Freelance => 0x5E98D9,
40            Self::Mercenary => 0x4B69FF,
41            Self::Commando => 0x8847FF,
42            Self::Assassin => 0xD32CE6,
43            Self::Elite => 0xEB4B4B,
44        }
45    }
46    
47    /// Converts a hexadecimal color into a [`Grade`].
48    /// 
49    /// # Examples
50    /// ```
51    /// use tf2_enum::Grade;
52    /// 
53    /// assert_eq!(Grade::from_color(0xEB4B4B).unwrap(), Grade::Elite);
54    /// ```
55    pub fn from_color(color: u32) -> Option<Self> {
56        match color {
57            0xB0C3D9 => Some(Self::Civilian),
58            0x5E98D9 => Some(Self::Freelance),
59            0x4B69FF => Some(Self::Mercenary),
60            0x8847FF => Some(Self::Commando),
61            0xD32CE6 => Some(Self::Assassin),
62            0xEB4B4B => Some(Self::Elite),
63            _ => None,
64        }
65    }
66    
67    /// Converts a hexadecimal color string into a [`Grade`].
68    /// 
69    /// # Examples
70    /// ```
71    /// use tf2_enum::Grade;
72    /// 
73    /// assert_eq!(Grade::from_color_str("#EB4B4B").unwrap(), Grade::Elite);
74    /// ```
75    pub fn from_color_str(color: &str) -> Option<Self> {
76        let len = color.len();
77        let mut color = color;
78        
79        if len == 7 && color.starts_with('#') {
80            color = &color[1..len];
81        } else if len != 6 {
82            return None;
83        }
84        
85        let color = u32::from_str_radix(color, 16).ok()?;
86        
87        Self::from_color(color)
88    }
89}