windows-core 0.101.0

Core type support for COM and Windows
Documentation
use super::*;
use core::ffi::c_void;

/// Revokes an event registration when dropped.
///
/// Returned by event-registration methods such as `Click` and `Closed`.
///
/// Use [`Self::into_token`] to manage revocation manually, or [`Self::forget`] to disable
/// automatic revocation without releasing the retained source interface.
#[must_use = "event registrations are revoked when the EventRevoker is dropped"]
pub struct EventRevoker {
    source: IUnknown,
    token: i64,
    remove: unsafe extern "system" fn(*mut c_void, i64) -> HRESULT,
}

impl EventRevoker {
    #[doc(hidden)]
    pub fn new<I: Interface>(
        source: I,
        token: i64,
        remove: unsafe extern "system" fn(*mut c_void, i64) -> HRESULT,
    ) -> Self {
        let source = unsafe { IUnknown::from_raw(source.into_raw()) };
        Self {
            source,
            token,
            remove,
        }
    }

    /// Returns the registration token without revoking the handler.
    ///
    /// The caller is responsible for passing the token to the corresponding `Remove*` method
    /// when the handler is no longer needed.
    pub fn into_token(self) -> i64 {
        let mut this = core::mem::ManuallyDrop::new(self);
        let token = this.token;
        // Release the source interface reference without calling Remove*.
        unsafe { core::ptr::drop_in_place(&mut this.source) };
        token
    }

    /// Disables automatic revocation without releasing the retained source interface.
    pub fn forget(self) {
        core::mem::forget(self);
    }
}

impl Drop for EventRevoker {
    fn drop(&mut self) {
        // Best-effort: discard errors silently (Drop cannot return Result).
        unsafe {
            let _ = (self.remove)(self.source.as_raw(), self.token);
        }
    }
}