1 | // Take a look at the license at the top of the repository in the LICENSE file. |
2 | |
3 | use std::{fmt, num::NonZeroU32}; |
4 | |
5 | use crate::{translate::*, GStr, IntoGStr}; |
6 | |
7 | #[derive (Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)] |
8 | #[repr (transparent)] |
9 | #[doc (alias = "GQuark" )] |
10 | pub struct Quark(NonZeroU32); |
11 | |
12 | impl Quark { |
13 | #[doc (alias = "g_quark_from_string" )] |
14 | #[allow (clippy::should_implement_trait)] |
15 | pub fn from_str(s: impl IntoGStr) -> Quark { |
16 | unsafe { s.run_with_gstr(|s: &GStr| from_glib(val:ffi::g_quark_from_string(s.as_ptr()))) } |
17 | } |
18 | |
19 | #[allow (clippy::trivially_copy_pass_by_ref)] |
20 | #[doc (alias = "g_quark_to_string" )] |
21 | pub fn as_str<'a>(&self) -> &'a GStr { |
22 | unsafe { GStr::from_ptr(ffi::g_quark_to_string(self.into_glib())) } |
23 | } |
24 | |
25 | #[doc (alias = "g_quark_try_string" )] |
26 | pub fn try_from_str(s: &str) -> Option<Quark> { |
27 | unsafe { Self::try_from_glib(val:ffi::g_quark_try_string(s.to_glib_none().0)).ok() } |
28 | } |
29 | } |
30 | |
31 | impl fmt::Debug for Quark { |
32 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { |
33 | f.write_str(data:Quark::as_str(self)) |
34 | } |
35 | } |
36 | |
37 | impl<T: IntoGStr> From<T> for Quark { |
38 | fn from(s: T) -> Self { |
39 | Self::from_str(s) |
40 | } |
41 | } |
42 | |
43 | impl std::str::FromStr for Quark { |
44 | type Err = std::convert::Infallible; |
45 | |
46 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
47 | Ok(Self::from_str(s)) |
48 | } |
49 | } |
50 | |
51 | #[doc (hidden)] |
52 | impl FromGlib<ffi::GQuark> for Quark { |
53 | #[inline ] |
54 | unsafe fn from_glib(value: ffi::GQuark) -> Self { |
55 | debug_assert_ne!(value, 0); |
56 | Self(NonZeroU32::new_unchecked(value)) |
57 | } |
58 | } |
59 | |
60 | #[doc (hidden)] |
61 | impl TryFromGlib<ffi::GQuark> for Quark { |
62 | type Error = GlibNoneError; |
63 | unsafe fn try_from_glib(value: ffi::GQuark) -> Result<Self, Self::Error> { |
64 | if value == 0 { |
65 | Err(GlibNoneError) |
66 | } else { |
67 | Ok(Self(NonZeroU32::new_unchecked(value))) |
68 | } |
69 | } |
70 | } |
71 | |
72 | #[doc (hidden)] |
73 | impl IntoGlib for Quark { |
74 | type GlibType = ffi::GQuark; |
75 | |
76 | #[inline ] |
77 | fn into_glib(self) -> ffi::GQuark { |
78 | self.0.get() |
79 | } |
80 | } |
81 | |
82 | #[doc (hidden)] |
83 | impl IntoGlib for Option<Quark> { |
84 | type GlibType = ffi::GQuark; |
85 | |
86 | #[inline ] |
87 | fn into_glib(self) -> ffi::GQuark { |
88 | self.map(|s| s.0.get()).unwrap_or(default:0) |
89 | } |
90 | } |
91 | |
92 | #[cfg (test)] |
93 | mod tests { |
94 | use super::*; |
95 | |
96 | #[test ] |
97 | fn test_from_str() { |
98 | let q1 = Quark::from_str("some-quark" ); |
99 | let q2 = Quark::try_from_str("some-quark" ); |
100 | assert_eq!(Some(q1), q2); |
101 | assert_eq!(q1.as_str(), "some-quark" ); |
102 | } |
103 | } |
104 | |