Skip to main content

windows_wmi_com/
value.rs

1use crate::error::{Error, Result};
2
3#[derive(Debug, Clone, PartialEq)]
4pub enum WmiValue {
5    String(String),
6    U32(u32),
7    U64(u64),
8    Bool(bool),
9    Null,
10    Array(Vec<WmiValue>),
11}
12
13impl WmiValue {
14    pub fn kind(&self) -> &'static str {
15        match self {
16            WmiValue::String(_) => "String",
17            WmiValue::U32(_) => "U32",
18            WmiValue::U64(_) => "U64",
19            WmiValue::Bool(_) => "Bool",
20            WmiValue::Null => "Null",
21            WmiValue::Array(_) => "Array",
22        }
23    }
24
25    pub fn as_str(&self) -> Result<&str> {
26        match self {
27            WmiValue::String(s) => Ok(s.as_str()),
28            other => Err(Error::TypeMismatch {
29                name: String::new(),
30                expected: "String",
31                got: other.kind(),
32            }),
33        }
34    }
35
36    pub fn as_u32(&self) -> Result<u32> {
37        match self {
38            WmiValue::U32(v) => Ok(*v),
39            other => Err(Error::TypeMismatch {
40                name: String::new(),
41                expected: "U32",
42                got: other.kind(),
43            }),
44        }
45    }
46
47    pub fn as_u64(&self) -> Result<u64> {
48        match self {
49            WmiValue::U64(v) => Ok(*v),
50            WmiValue::U32(v) => Ok(*v as u64),
51            other => Err(Error::TypeMismatch {
52                name: String::new(),
53                expected: "U64",
54                got: other.kind(),
55            }),
56        }
57    }
58
59    pub fn as_bool(&self) -> Result<bool> {
60        match self {
61            WmiValue::Bool(b) => Ok(*b),
62            other => Err(Error::TypeMismatch {
63                name: String::new(),
64                expected: "Bool",
65                got: other.kind(),
66            }),
67        }
68    }
69
70    pub fn is_null(&self) -> bool {
71        matches!(self, WmiValue::Null)
72    }
73}
74
75#[cfg(windows)]
76pub(crate) mod convert {
77    //! `windows-core` v0.58 exposes `VARIANT` as an opaque `#[repr(transparent)]`
78    //! wrapper around the C VARIANT struct, so we shadow it here with an
79    //! identical layout and reach in via a reference transmute. The
80    //! `size_of` static assert catches any layout drift on version bumps.
81    //!
82    //! Only tags we can round-trip into `WmiValue` are decoded; everything
83    //! else lands as `WmiValue::Null` (see the TODO block at the bottom).
84
85    use super::WmiValue;
86    use windows::Win32::System::Variant::{
87        VT_BOOL, VT_BSTR, VT_EMPTY, VT_I1, VT_I2, VT_I4, VT_I8, VT_NULL, VT_UI1, VT_UI2, VT_UI4,
88        VT_UI8,
89    };
90    use windows_core::VARIANT;
91
92    #[repr(C)]
93    struct RawVariant {
94        vt: u16,
95        _r1: u16,
96        _r2: u16,
97        _r3: u16,
98        payload: RawPayload,
99        // On x64, C VARIANT is 24 bytes total — pad the payload region to match.
100        #[cfg(target_pointer_width = "64")]
101        _tail: u64,
102    }
103
104    #[repr(C)]
105    union RawPayload {
106        ll: i64,
107        ull: u64,
108        l: i32,
109        ul: u32,
110        i: i16,
111        ui: u16,
112        b: u8,
113        bstr: *mut u16,
114        var_bool: i16,
115    }
116
117    const _: () = assert!(std::mem::size_of::<RawVariant>() == std::mem::size_of::<VARIANT>());
118
119    /// Length of a BSTR is stored as a 4-byte byte-count immediately before
120    /// the string pointer. We use the null terminator instead — WMI property
121    /// names and typical string properties never contain embedded NULs, so
122    /// this is safer than trusting the prefix on an unfamiliar allocator.
123    unsafe fn bstr_to_string(ptr: *const u16) -> String {
124        if ptr.is_null() {
125            return String::new();
126        }
127        let mut len = 0usize;
128        while *ptr.add(len) != 0 {
129            len += 1;
130        }
131        let slice = std::slice::from_raw_parts(ptr, len);
132        String::from_utf16_lossy(slice)
133    }
134
135    pub unsafe fn from_variant(v: &VARIANT) -> WmiValue {
136        let raw: &RawVariant = &*(v as *const VARIANT as *const RawVariant);
137        let tag = raw.vt as i32;
138        let p = &raw.payload;
139
140        if tag == VT_NULL.0 as i32 || tag == VT_EMPTY.0 as i32 {
141            return WmiValue::Null;
142        }
143        if tag == VT_BSTR.0 as i32 {
144            return WmiValue::String(bstr_to_string(p.bstr));
145        }
146        if tag == VT_BOOL.0 as i32 {
147            return WmiValue::Bool(p.var_bool != 0);
148        }
149        if tag == VT_I4.0 as i32 {
150            return WmiValue::U32(p.l as u32);
151        }
152        if tag == VT_UI4.0 as i32 {
153            return WmiValue::U32(p.ul);
154        }
155        if tag == VT_I2.0 as i32 {
156            return WmiValue::U32(p.i as u32);
157        }
158        if tag == VT_UI2.0 as i32 {
159            return WmiValue::U32(p.ui as u32);
160        }
161        if tag == VT_I1.0 as i32 {
162            return WmiValue::U32((p.b as i8) as u32);
163        }
164        if tag == VT_UI1.0 as i32 {
165            return WmiValue::U32(p.b as u32);
166        }
167        if tag == VT_I8.0 as i32 {
168            return WmiValue::U64(p.ll as u64);
169        }
170        if tag == VT_UI8.0 as i32 {
171            return WmiValue::U64(p.ull);
172        }
173
174        // TODO(0.2): decode VT_R4/R8, VT_DATE, VT_DECIMAL, and 1-D SAFEARRAYs
175        // (VT_ARRAY | VT_BSTR is the common one — string[] properties).
176        WmiValue::Null
177    }
178}