wincom 0.3.0

A lightweight Rust wrapper for Windows COM IDispatch automation, providing RAII VARIANT management and simplified property/method invocation.
Documentation
//! Error type for all fallible `wincom` operations.
//!
//! [`Error`] preserves the raw `HRESULT` from COM so callers can
//! distinguish specific failures. For example, a missing ProgID
//! (`0x800401F3`, `CO_E_CLASSSTRING`) is distinct from an application that
//! is installed but not running (`0x800401E3`, `MK_E_UNAVAILABLE`):
//!
//! ```no_run
//! # use wincom::{ComObject, Error};
//! match ComObject::new_from_active("AutoCAD.Application") {
//!     Ok(app) => { let _ = app; /* … */ }
//!     Err(Error::Windows(e)) if e.code().0 == 0x800401E3u32 as i32 => {
//!         eprintln!("AutoCAD is not running");
//!     }
//!     Err(e) => eprintln!("unexpected error: {e}"),
//! }
//! ```

use windows::core as wcore;

/// Errors returned by `wincom` operations.
///
/// Most variants carry a [`windows::core::Error`], which wraps an
/// `HRESULT` and an optional message. Inspect `.code()` to branch on
/// specific HRESULTs.
#[derive(Debug)]
pub enum Error {
    /// Underlying Windows error (HRESULT + message).
    Windows(wcore::Error),

    /// A `VARIANT` was expected to contain an `IDispatch` but didn't.
    ///
    /// Returned by [`Variant::to_idispatch`](crate::Variant::to_idispatch)
    /// and
    /// [`Variant::as_idispatch`](crate::Variant::as_idispatch) when the
    /// variant's `vt` is not `VT_DISPATCH` or its pointer is null.
    NoDispatch,

    /// `GetIDsOfNames` did not return a valid dispid.
    NoDispid,

    /// A conversion between `VARIANT` types failed.
    ///
    /// Currently unused; the underlying `VariantChangeType` error is
    /// returned as [`Error::Windows`] instead.
    TypeMismatch {
        /// The expected `VARTYPE` name.
        expected: &'static str,
        /// The actual `VARENUM` value read from the variant.
        actual: u16,
    },
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Windows(e) => write!(f, "windows error: {e}"),
            Error::NoDispatch => write!(f, "VARIANT does not contain an IDispatch"),
            Error::NoDispid => write!(f, "GetIDsOfNames returned no dispid"),
            Error::TypeMismatch { expected, actual } => write!(
                f,
                "type mismatch: expected {expected}, got VARENUM(0x{actual:04X})"
            ),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Windows(e) => Some(e),
            _ => None,
        }
    }
}

impl From<wcore::Error> for Error {
    fn from(e: wcore::Error) -> Self {
        Error::Windows(e)
    }
}

/// Convenience alias for results returned by `wincom`.
pub type Result<T> = std::result::Result<T, Error>;