glib/subclass/
boxed.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3// rustdoc-stripper-ignore-next
4//! Module for registering boxed types for Rust types.
5
6use crate::{ffi, gobject_ffi, prelude::*, translate::*};
7
8// rustdoc-stripper-ignore-next
9/// Trait for defining boxed types.
10///
11/// Links together the type name with the type itself.
12///
13/// See [`register_boxed_type`] for registering an implementation of this trait
14/// with the type system.
15///
16/// [`register_boxed_type`]: fn.register_boxed_type.html
17pub trait BoxedType: StaticType + Clone + Sized + 'static {
18    // rustdoc-stripper-ignore-next
19    /// Boxed type name.
20    ///
21    /// This must be unique in the whole process.
22    const NAME: &'static str;
23
24    // rustdoc-stripper-ignore-next
25    /// Allow name conflicts for this boxed type.
26    ///
27    /// By default, trying to register a type with a name that was registered before will panic. If
28    /// this is set to `true` then a new name will be selected by appending a counter.
29    ///
30    /// This is useful for defining new types in Rust library crates that might be linked multiple
31    /// times in the same process.
32    ///
33    /// A consequence of setting this to `true` is that it's not guaranteed that
34    /// `glib::Type::from_name(Self::NAME).unwrap() == Self::static_type()`.
35    ///
36    /// Optional.
37    const ALLOW_NAME_CONFLICT: bool = false;
38}
39
40// rustdoc-stripper-ignore-next
41/// Register a boxed `glib::Type` ID for `T`.
42///
43/// This must be called only once and will panic on a second call.
44///
45/// See [`Boxed!`] for defining a function that ensures that
46/// this is only called once and returns the type id.
47///
48/// [`Boxed!`]: ../../derive.Boxed.html
49pub fn register_boxed_type<T: BoxedType>() -> crate::Type {
50    unsafe extern "C" fn boxed_copy<T: BoxedType>(v: ffi::gpointer) -> ffi::gpointer {
51        let v = &*(v as *mut T);
52        let copy = Box::new(v.clone());
53
54        Box::into_raw(copy) as ffi::gpointer
55    }
56    unsafe extern "C" fn boxed_free<T: BoxedType>(v: ffi::gpointer) {
57        let v = v as *mut T;
58        let _ = Box::from_raw(v);
59    }
60    unsafe {
61        use std::ffi::CString;
62
63        let type_name = if T::ALLOW_NAME_CONFLICT {
64            let mut i = 0;
65            loop {
66                let type_name = CString::new(if i == 0 {
67                    T::NAME.to_string()
68                } else {
69                    format!("{}-{}", T::NAME, i)
70                })
71                .unwrap();
72                if gobject_ffi::g_type_from_name(type_name.as_ptr()) == gobject_ffi::G_TYPE_INVALID
73                {
74                    break type_name;
75                }
76                i += 1;
77            }
78        } else {
79            let type_name = CString::new(T::NAME).unwrap();
80            assert_eq!(
81                gobject_ffi::g_type_from_name(type_name.as_ptr()),
82                gobject_ffi::G_TYPE_INVALID,
83                "Type {} has already been registered",
84                type_name.to_str().unwrap()
85            );
86
87            type_name
88        };
89
90        let type_ = crate::Type::from_glib(gobject_ffi::g_boxed_type_register_static(
91            type_name.as_ptr(),
92            Some(boxed_copy::<T>),
93            Some(boxed_free::<T>),
94        ));
95        assert!(type_.is_valid());
96
97        type_
98    }
99}
100
101#[cfg(test)]
102mod test {
103    // We rename the current crate as glib, since the macros in glib-macros
104    // generate the glib namespace through the crate_ident_new utility,
105    // and that returns `glib` (and not `crate`) when called inside the glib crate
106    use crate as glib;
107    use crate::prelude::*;
108    use crate::translate::{FromGlibPtrBorrow, FromGlibPtrFull, IntoGlibPtr};
109
110    #[derive(Clone, Debug, PartialEq, Eq, glib::Boxed)]
111    #[boxed_type(name = "MyBoxed")]
112    struct MyBoxed(String);
113
114    #[test]
115    fn test_register() {
116        assert!(MyBoxed::static_type().is_valid());
117    }
118
119    #[test]
120    fn test_value() {
121        assert!(MyBoxed::static_type().is_valid());
122
123        let b = MyBoxed(String::from("abc"));
124        let v = b.to_value();
125        let b2 = v.get::<&MyBoxed>().unwrap();
126        assert_eq!(&b, b2);
127    }
128
129    #[test]
130    fn test_from_glib_borrow() {
131        assert!(MyBoxed::static_type().is_valid());
132
133        let b = MyBoxed(String::from("abc"));
134        let raw_ptr = unsafe { MyBoxed::into_glib_ptr(b) };
135
136        // test that the from_glib_borrow does not take ownership of the raw_ptr
137        let _ = unsafe { MyBoxed::from_glib_borrow(raw_ptr) };
138
139        let new_b = unsafe { MyBoxed::from_glib_full(raw_ptr) };
140
141        assert_eq!(new_b.0, "abc".to_string());
142    }
143}