Skip to main content

gobject_subclass/
guard.rs

1// Copyright (C) 2016-2017 Sebastian Dröge <sebastian@centricular.com>
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use std::ptr;
10
11use glib_ffi;
12use gobject_ffi;
13
14#[macro_export]
15macro_rules! floating_reference_guard {
16    ($obj:ident) => {
17        let _guard = $crate::guard::FloatingReferenceGuard::new($obj as *mut _);
18    };
19}
20
21pub struct FloatingReferenceGuard(ptr::NonNull<gobject_ffi::GObject>);
22
23impl FloatingReferenceGuard {
24    pub unsafe fn new(obj: *mut gobject_ffi::GObject) -> Option<FloatingReferenceGuard> {
25        assert!(!obj.is_null());
26        if gobject_ffi::g_object_is_floating(obj) != glib_ffi::GFALSE {
27            gobject_ffi::g_object_ref_sink(obj);
28            Some(FloatingReferenceGuard(ptr::NonNull::new_unchecked(obj)))
29        } else {
30            None
31        }
32    }
33}
34
35impl Drop for FloatingReferenceGuard {
36    fn drop(&mut self) {
37        unsafe {
38            gobject_ffi::g_object_force_floating(self.0.as_ptr());
39        }
40    }
41}