javascriptcore/auto/
weak_value.rs1use crate::Value;
7use glib::{
8 prelude::*,
9 signal::{connect_raw, SignalHandlerId},
10 translate::*,
11};
12use std::{boxed::Box as Box_, fmt, mem::transmute};
13
14glib::wrapper! {
15 #[doc(alias = "JSCWeakValue")]
16 pub struct WeakValue(Object<ffi::JSCWeakValue, ffi::JSCWeakValueClass>);
17
18 match fn {
19 type_ => || ffi::jsc_weak_value_get_type(),
20 }
21}
22
23impl WeakValue {
24 pub const NONE: Option<&'static WeakValue> = None;
25
26 #[doc(alias = "jsc_weak_value_new")]
27 pub fn new(value: &impl IsA<Value>) -> WeakValue {
28 unsafe { from_glib_full(ffi::jsc_weak_value_new(value.as_ref().to_glib_none().0)) }
29 }
30
31 pub fn builder() -> WeakValueBuilder {
36 WeakValueBuilder::new()
37 }
38}
39
40impl Default for WeakValue {
41 fn default() -> Self {
42 glib::object::Object::new::<Self>()
43 }
44}
45
46#[must_use = "The builder must be built to be used"]
51pub struct WeakValueBuilder {
52 builder: glib::object::ObjectBuilder<'static, WeakValue>,
53}
54
55impl WeakValueBuilder {
56 fn new() -> Self {
57 Self {
58 builder: glib::object::Object::builder(),
59 }
60 }
61
62 pub fn value(self, value: &impl IsA<Value>) -> Self {
63 Self {
64 builder: self.builder.property("value", value.clone().upcast()),
65 }
66 }
67
68 #[must_use = "Building the object from the builder is usually expensive and is not expected to have side effects"]
71 pub fn build(self) -> WeakValue {
72 self.builder.build()
73 }
74}
75
76pub trait WeakValueExt: 'static {
77 #[doc(alias = "jsc_weak_value_get_value")]
78 #[doc(alias = "get_value")]
79 fn value(&self) -> Option<Value>;
80
81 #[doc(alias = "cleared")]
82 fn connect_cleared<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
83}
84
85impl<O: IsA<WeakValue>> WeakValueExt for O {
86 fn value(&self) -> Option<Value> {
87 unsafe {
88 from_glib_full(ffi::jsc_weak_value_get_value(
89 self.as_ref().to_glib_none().0,
90 ))
91 }
92 }
93
94 fn connect_cleared<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
95 unsafe extern "C" fn cleared_trampoline<P: IsA<WeakValue>, F: Fn(&P) + 'static>(
96 this: *mut ffi::JSCWeakValue,
97 f: glib::ffi::gpointer,
98 ) {
99 let f: &F = &*(f as *const F);
100 f(WeakValue::from_glib_borrow(this).unsafe_cast_ref())
101 }
102 unsafe {
103 let f: Box_<F> = Box_::new(f);
104 connect_raw(
105 self.as_ptr() as *mut _,
106 b"cleared\0".as_ptr() as *const _,
107 Some(transmute::<_, unsafe extern "C" fn()>(
108 cleared_trampoline::<Self, F> as *const (),
109 )),
110 Box_::into_raw(f),
111 )
112 }
113 }
114}
115
116impl fmt::Display for WeakValue {
117 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
118 f.write_str("WeakValue")
119 }
120}