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