1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use {
	glib::{
		object::ObjectType,
		translate::{from_glib_borrow, FromGlibPtrBorrow, ToGlibPtr},
		types::StaticType,
		value::FromValue,
		Type, Value,
	},
	std::{marker::PhantomData, mem::ManuallyDrop, ops::Deref},
};

#[derive(Debug)]
#[repr(transparent)]
pub struct BorrowedObject<'a, O> {
	inner: ManuallyDrop<O>,
	_borrow: PhantomData<&'a O>,
}

impl<'a, O> BorrowedObject<'a, O> {
	pub fn forget(inner: O) -> Self {
		Self {
			inner: ManuallyDrop::new(inner),
			_borrow: PhantomData,
		}
	}

	/// If `O` lives beyond `'a`, bad things may happen.
	pub unsafe fn into_inner(self) -> ManuallyDrop<O> {
		self.inner
	}
}

impl<'a, O: ObjectType> BorrowedObject<'a, O> {
	/// Copy this reference
	pub fn copy_ref(&self) -> Self {
		unsafe { std::ptr::read(self) }
	}
}

impl<'a, O> Deref for BorrowedObject<'a, O> {
	type Target = O;

	fn deref(&self) -> &Self::Target {
		&self.inner
	}
}

impl<'a, O> AsRef<O> for BorrowedObject<'a, O> {
	fn as_ref(&self) -> &O {
		&self.inner
	}
}

unsafe impl<'a, O: ObjectType + FromGlibPtrBorrow<*mut O::GlibType>> FromValue<'a> for BorrowedObject<'a, O> {
	type Checker = glib::value::GenericValueTypeChecker<O>;

	unsafe fn from_value(value: &'a Value) -> Self {
		let value = value.to_glib_none();
		let borrowed: glib::translate::Borrowed<O> =
			from_glib_borrow(glib::gobject_ffi::g_value_get_object(value.0) as *mut O::GlibType);
		Self::forget(borrowed.into_inner())
	}
}

impl<'a, O: StaticType> StaticType for BorrowedObject<'a, O> {
	fn static_type() -> Type {
		O::static_type()
	}
}