windows-core 0.101.0

Core type support for COM and Windows
Documentation
use super::*;
use crate::{
    ComposeBase, DYNAMIC_CAST_IID, GUID, HRESULT, IInspectable, IUnknown, Interface, InterfaceRef,
};
use core::cell::UnsafeCell;
use core::ffi::c_void;
use core::ptr::null_mut;

/// A `'static` vtable pointer stored at the start of a COM object.
#[doc(hidden)]
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct Vtable(*const c_void);

// SAFETY: vtables are immutable `'static` data.
unsafe impl Send for Vtable {}
// SAFETY: vtables are immutable `'static` data.
unsafe impl Sync for Vtable {}

impl Vtable {
    pub const fn new<V>(vtable: &'static V) -> Self {
        Self((vtable as *const V).cast())
    }
}

#[repr(C)]
struct Layout<const N: usize, B, T> {
    vtables: [Vtable; N],
    count: WeakRefCount,
    base: B,
    this: T,
}

/// Storage for objects generated by `#[implement]` and `implement_decl!`.
///
/// Interface `i` is the address of `vtables[i]`. Interface 0 is the COM identity and the address
/// of the object, so its vtable must begin with `IUnknown_Vtbl`. `B` is `ComposeBase` for objects
/// that support composition and `()` otherwise.
///
/// COM callers update the count and free the object through interface pointers, and composition
/// writes the base slot, all while shared references exist. The contents are therefore in an
/// `UnsafeCell`, and interface pointers are derived from the whole object rather than from a
/// reference to a single vtable field.
#[doc(hidden)]
#[repr(transparent)]
pub struct ComCell<const N: usize, B, T>(UnsafeCell<Layout<N, B, T>>);

// SAFETY: shared access reads the vtables and `this`, updates the atomic count, and reads the
// base slot, which is only written by `compose` before the object is shared.
unsafe impl<const N: usize, B: Sync, T: Sync> Sync for ComCell<N, B, T> {}

impl<const N: usize, B, T> ComCell<N, B, T> {
    /// Constructs unpublished COM storage.
    ///
    /// # Safety
    ///
    /// The vtables must match the enclosing object's layout and implementation. Before exposing
    /// any interfaces, move the object into its final heap allocation or static storage. Safe
    /// code must not gain ownership or mutable access to the enclosing object after publication.
    pub const unsafe fn new(vtables: [Vtable; N], base: B, this: T) -> Self {
        Self(UnsafeCell::new(Layout {
            vtables,
            count: WeakRefCount::new(),
            base,
            this,
        }))
    }

    #[inline(always)]
    pub fn get(&self) -> &T {
        unsafe { &(*self.0.get()).this }
    }

    #[inline(always)]
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.0.get_mut().this
    }

    #[inline(always)]
    pub fn into_inner(self) -> T {
        self.0.into_inner().this
    }

    #[inline(always)]
    pub fn count(&self) -> &WeakRefCount {
        unsafe { &(*self.0.get()).count }
    }

    /// Returns interface `index` without adding a reference.
    #[inline(always)]
    pub fn interface(&self, index: usize) -> *mut c_void {
        assert!(index < N);
        unsafe {
            (&raw mut (*self.0.get()).vtables)
                .cast::<Vtable>()
                .add(index)
                .cast()
        }
    }

    /// Returns a borrowed interface `index`.
    ///
    /// # Safety
    ///
    /// The vtable at `index` must begin with `I::Vtable`.
    #[inline(always)]
    pub unsafe fn interface_ref<I: Interface>(&self, index: usize) -> InterfaceRef<'_, I> {
        unsafe { InterfaceRef::from_raw(core::ptr::NonNull::new_unchecked(self.interface(index))) }
    }

    #[inline(always)]
    fn layout(this: *mut Self) -> *mut Layout<N, B, T> {
        UnsafeCell::raw_get(this.cast::<UnsafeCell<Layout<N, B, T>>>())
    }

    /// Returns a pointer to the contained value without creating a reference.
    ///
    /// # Safety
    ///
    /// `this` must point to a live `ComCell`.
    #[inline(always)]
    pub unsafe fn this_ptr(this: *mut Self) -> *mut T {
        unsafe { &raw mut (*Self::layout(this)).this }
    }
}

/// The aggregation slot of a [`ComCell`].
#[doc(hidden)]
pub trait ComBase {
    fn get(&self) -> Option<&IInspectable>;
}

impl ComBase for () {
    #[inline(always)]
    fn get(&self) -> Option<&IInspectable> {
        None
    }
}

impl ComBase for ComposeBase {
    #[inline(always)]
    fn get(&self) -> Option<&IInspectable> {
        self.as_option().as_ref()
    }
}

impl<const N: usize, B: ComBase, T> ComCell<N, B, T> {
    /// Implements `QueryInterface` for an object whose identity is `Identity`.
    ///
    /// `find` maps an IID to the index of the interface that implements it. `rust_object` is the
    /// index of the private Rust interface, if supported.
    ///
    /// # Safety
    ///
    /// `iid` must be null or readable and `interface` must be null or writable.
    #[inline(always)]
    pub unsafe fn query_interface<Identity: Interface>(
        &self,
        iid: *const GUID,
        interface: *mut *mut c_void,
        agile: bool,
        rust_object: Option<usize>,
        find: impl FnOnce(&GUID) -> Option<usize>,
    ) -> HRESULT {
        unsafe {
            if iid.is_null() || interface.is_null() {
                return E_POINTER;
            }

            let iid = &*iid;

            let index = if *iid == IUnknown::IID
                || (Identity::INSPECTABLE && *iid == IInspectable::IID)
                || (agile && *iid == IAgileObject::IID)
            {
                Some(0)
            } else if *iid == DYNAMIC_CAST_IID {
                rust_object
            } else {
                find(iid)
            };

            if let Some(index) = index {
                *interface = self.interface(index);
                self.count().add_ref();
                return HRESULT(0);
            }

            #[cfg(windows)]
            if agile && *iid == IMarshal::IID {
                self.count().add_ref();
                return marshaler(IUnknown::from_raw(self.interface(0)), interface);
            }

            let tear_off = self.count().query(iid, self.interface(0), agile);

            if !tear_off.is_null() {
                *interface = tear_off;
                return HRESULT(0);
            }

            if let Some(base) = (*self.0.get()).base.get() {
                return base.query(iid, interface);
            }

            *interface = null_mut();
            E_NOINTERFACE
        }
    }
}

impl<const N: usize, T> ComCell<N, ComposeBase, T> {
    /// Returns the outer `IInspectable` and the slot for the inner object of a composed object.
    ///
    /// # Safety
    ///
    /// `this` must point to the object owned by `identity`, and the returned slot must not
    /// outlive it.
    pub unsafe fn compose<'a, Identity: Interface>(
        this: *mut Self,
        identity: IUnknown,
    ) -> (IInspectable, &'a mut Option<IInspectable>) {
        const {
            assert!(
                Identity::INSPECTABLE,
                "composition requires an IInspectable identity"
            );
        };

        unsafe {
            let base = &raw mut (*Self::layout(this)).base;
            (
                core::mem::transmute::<IUnknown, IInspectable>(identity),
                ComposeBase::slot(base),
            )
        }
    }
}