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
use super::*;
use core::marker::PhantomData;
/// `Weak` holds a non-owning reference to an object.
///
/// This type is not [`Send`] or [`Sync`]. It does not marshal the native weak reference between
/// apartments. Cross-apartment use requires explicitly marshaling the native `IWeakReference`
/// interface, for example with [`AgileReference`].
/// The native weak interfaces are available through `windows-bindgen` or
/// `windows::Win32::System::WinRT::{IWeakReference, IWeakReferenceSource}`.
#[derive(Clone, PartialEq, Eq)]
pub struct Weak<I: Interface>(Option<imp::IWeakReference>, PhantomData<I>);
impl<I: Interface> Default for Weak<I> {
fn default() -> Self {
Self::new()
}
}
impl<I: Interface> Weak<I> {
/// Creates a new `Weak` object without any backing object.
pub const fn new() -> Self {
Self(None, PhantomData)
}
/// Attempts to upgrade the weak reference to a strong reference.
pub fn upgrade(&self) -> Option<I> {
self.0.as_ref().and_then(|inner| unsafe {
let mut value = core::ptr::null_mut();
// Resolve returns the interface selected by the IID, not necessarily IInspectable.
(inner.vtable().Resolve)(inner.as_raw(), &I::IID, &mut value)
.and_then(|| imp::from_abi(value))
.ok()
})
}
pub(crate) fn downgrade(source: &imp::IWeakReferenceSource) -> Self {
let reference = unsafe { source.GetWeakReference().ok() };
Self(reference, PhantomData)
}
}