glib/
quark.rs

1// Copyright 2018, The Gtk-rs Project Developers.
2// See the COPYRIGHT file at the top-level directory of this distribution.
3// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
4
5use glib_sys;
6use std::ffi::CStr;
7use std::fmt;
8use translate::*;
9
10#[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Clone, Copy)]
11#[repr(C)]
12pub struct Quark(glib_sys::GQuark);
13
14impl Quark {
15    pub fn from_string(s: &str) -> Quark {
16        unsafe { from_glib(glib_sys::g_quark_from_static_string(s.to_glib_full())) }
17    }
18
19    #[allow(clippy::trivially_copy_pass_by_ref)]
20    pub fn to_string(&self) -> &'static str {
21        unsafe {
22            CStr::from_ptr(glib_sys::g_quark_to_string(self.to_glib()))
23                .to_str()
24                .unwrap()
25        }
26    }
27
28    pub fn try_string(s: &str) -> Option<Quark> {
29        unsafe {
30            match glib_sys::g_quark_try_string(s.to_glib_none().0) {
31                0 => None,
32                x => Some(from_glib(x)),
33            }
34        }
35    }
36}
37
38impl fmt::Debug for Quark {
39    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
40        f.write_str(Quark::to_string(self))
41    }
42}
43
44#[doc(hidden)]
45impl FromGlib<glib_sys::GQuark> for Quark {
46    fn from_glib(value: glib_sys::GQuark) -> Self {
47        Quark(value)
48    }
49}
50
51#[doc(hidden)]
52impl ToGlib for Quark {
53    type GlibType = glib_sys::GQuark;
54
55    fn to_glib(&self) -> glib_sys::GQuark {
56        self.0
57    }
58}