Skip to main content

tray_icon/
tray_icon_id.rs

1use std::{convert::Infallible, str::FromStr};
2
3use crate::COUNTER;
4
5/// An unique id that is associated with a tray icon.
6#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub struct TrayIconId(pub String);
9
10impl TrayIconId {
11    /// Create a new tray icon id.
12    pub fn new<S: AsRef<str>>(id: S) -> Self {
13        Self(id.as_ref().to_string())
14    }
15
16    /// Generate id based on process id for internal use
17    pub(crate) fn new_unique() -> Self {
18        Self(format!("{}-{}", std::process::id(), COUNTER.next()))
19    }
20}
21
22impl AsRef<str> for TrayIconId {
23    fn as_ref(&self) -> &str {
24        self.0.as_ref()
25    }
26}
27
28impl<T: ToString> From<T> for TrayIconId {
29    fn from(value: T) -> Self {
30        Self::new(value.to_string())
31    }
32}
33
34impl FromStr for TrayIconId {
35    type Err = Infallible;
36
37    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
38        Ok(Self::new(s))
39    }
40}
41
42impl PartialEq<&str> for TrayIconId {
43    fn eq(&self, other: &&str) -> bool {
44        self.0 == *other
45    }
46}
47
48impl PartialEq<&str> for &TrayIconId {
49    fn eq(&self, other: &&str) -> bool {
50        self.0 == *other
51    }
52}
53
54impl PartialEq<String> for TrayIconId {
55    fn eq(&self, other: &String) -> bool {
56        self.0 == *other
57    }
58}
59
60impl PartialEq<String> for &TrayIconId {
61    fn eq(&self, other: &String) -> bool {
62        self.0 == *other
63    }
64}
65
66impl PartialEq<&String> for TrayIconId {
67    fn eq(&self, other: &&String) -> bool {
68        self.0 == **other
69    }
70}
71
72impl PartialEq<&TrayIconId> for TrayIconId {
73    fn eq(&self, other: &&TrayIconId) -> bool {
74        other.0 == self.0
75    }
76}
77
78#[cfg(test)]
79mod test {
80    use crate::TrayIconId;
81
82    #[test]
83    fn is_eq() {
84        assert_eq!(TrayIconId::new("t"), "t",);
85        assert_eq!(TrayIconId::new("t"), String::from("t"));
86        assert_eq!(TrayIconId::new("t"), &String::from("t"));
87        assert_eq!(TrayIconId::new("t"), TrayIconId::new("t"));
88        assert_eq!(TrayIconId::new("t"), &TrayIconId::new("t"));
89        assert_eq!(&TrayIconId::new("t"), &TrayIconId::new("t"));
90        assert_eq!(TrayIconId::new("t").as_ref(), "t");
91    }
92}