From 5d2f786d20deb1aecd4716947837199f3ce28a93 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Sun, 20 Sep 2026 12:05:15 +0800 Subject: [PATCH 1/2] Fix metadata-directed WinRT struct collection equality Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: bdea384f-3022-47e8-8c74-11fd768c2105 --- bindings/js/README.md | 9 + .../collection-struct-equality.e2e.mjs | 81 +++++ bindings/js/package.json | 2 +- bindings/py/README.md | 9 + crates/dynwinrt/src/collection_element.rs | 285 ++++++++++++++++ crates/dynwinrt/src/map.rs | 45 ++- crates/dynwinrt/src/vector.rs | 56 +++- crates/dynwinrt/src/vector_abi_tests.rs | 308 ++++++++++++++++++ 8 files changed, 772 insertions(+), 23 deletions(-) create mode 100644 bindings/js/__test__/collection-struct-equality.e2e.mjs diff --git a/bindings/js/README.md b/bindings/js/README.md index 9b7404b2..d506f219 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -391,11 +391,20 @@ I8/U8/Char16. For example, I32 `255` is accepted for U8; I32 `257` throws instea of wrapping. Reference inputs are retained and queried for the declared IID; an incompatible interface throws, while a null reference remains null. +For admitted POD structs, vector `IndexOf` and map key operations compare +metadata-declared fields by value, including nested fields, and ignore padding. +Floating fields use numerical equality: `+0` and `-0` match, while NaN does not +match even the same NaN bits. This also applies to collection views; a +NaN-containing struct map key is not found by lookup. Stored field bits are +not normalized. + The JavaScript helpers use validated typed core factories. Rust callers can use the safe `create_vector_from_values` / `create_map_from_values` factories for the same checks. The metadata-free Rust `create_value_vector`, `create_vector`, and `create_map` constructors require `unsafe`: callers must prove the native ABI, ownership, element types, and complete IID set themselves. +The metadata-free `create_value_vector` retains packed-byte equality, including +padding, rather than metadata-directed field equality. Complete native struct collection support is tracked in [microsoft/dynwinrt#161](https://github.com/microsoft/dynwinrt/issues/161). diff --git a/bindings/js/__test__/collection-struct-equality.e2e.mjs b/bindings/js/__test__/collection-struct-equality.e2e.mjs new file mode 100644 index 00000000..d7b2729e --- /dev/null +++ b/bindings/js/__test__/collection-struct-equality.e2e.mjs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { createRequire } from 'node:module' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const require = createRequire(import.meta.url) +const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const { DynWinRtType, DynWinRtStruct, DynWinRtValue, DynWinRtMethodSig, WinGuid, roInitialize } = require( + resolve(process.env.DYNWINRT_JS_PACKAGE ?? packageRoot), +) +roInitialize(1) + +const pointType = DynWinRtType.structType('Windows.Foundation.Point', [DynWinRtType.f32(), DynWinRtType.f32()]) +const mapIid = DynWinRtType.parameterized(WinGuid.parse('3c2925fe-8519-45c1-aa79-197b6718c1c1'), [ + pointType, + DynWinRtType.i32(), +]).iid() +const reader = DynWinRtType.registerInterface('StructEquality.PointMap', mapIid) + .addMethod('Lookup', new DynWinRtMethodSig().addIn(pointType).addOut(DynWinRtType.i32())) + .addMethod('get_Size', new DynWinRtMethodSig().addOut(DynWinRtType.u32())) + +function own(t) { + const values = [] + t.after(() => { + for (const value of values.reverse()) value.release() + }) + return (value) => { + values.push(value) + return value + } +} + +function point(x, y) { + const value = DynWinRtStruct.create(pointType) + value.setF32(0, x) + value.setF32(1, y) + return value.toValue() +} + +test('checked Point map keys compare fields numerically', { skip: process.arch !== 'x64' }, (t) => { + const keep = own(t) + for (const [stored, query, equal] of [ + [[+0, 1], [-0, 1], true], + [[-0, 1], [+0, 1], true], + [[2, 1], [2, 1], true], + [[2, 1], [3, 1], false], + [[2, 1], [2, 3], false], + [[NaN, 1], [NaN, 1], false], + [[1, NaN], [1, NaN], false], + ]) { + const source = keep(point(...stored)) + const needle = keep(point(...query)) + const value = keep(DynWinRtValue.i32(7)) + const map = keep(DynWinRtValue.createMap([source], [value], pointType, DynWinRtType.i32())) + const typed = keep(map.cast(mapIid)) + assert.equal(keep(reader.method(7).invoke(typed, [])).toNumber(), 1) + if (equal) { + assert.equal(keep(reader.method(6).invoke(typed, [needle])).toNumber(), 7) + } else { + assert.throws(() => reader.method(6).invoke(typed, [needle])) + } + assert.ok(Object.is(source.asStruct().getF32(0), stored[0])) + assert.ok(Object.is(source.asStruct().getF32(1), stored[1])) + } +}) + +test('Point collection admission is unchanged on non-x64 targets', { skip: process.arch === 'x64' }, (t) => { + const keep = own(t) + const source = keep(point(0, 1)) + const value = keep(DynWinRtValue.i32(7)) + for (const items of [[], [source]]) { + assert.throws(() => DynWinRtValue.createVector(items, pointType)) + assert.throws(() => + DynWinRtValue.createMap(items, items.map(() => value), pointType, DynWinRtType.i32()), + ) + } +}) diff --git a/bindings/js/package.json b/bindings/js/package.json index cd6afd75..9acf42fc 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -110,7 +110,7 @@ "lint": "oxlint", "test": "npm run test:types && ava", "test:imports": "ava __test__/native-imports.spec.ts", - "test:collection-factories": "node --test __test__/collection-factories.e2e.mjs", + "test:collection-factories": "node --test __test__/collection-factories.e2e.mjs __test__/collection-struct-equality.e2e.mjs", "test:generated-unsafe": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/generated-unsafe-companion.e2e.ts", "test:winrt-implementation": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/winrt-implementation.spec.ts", "test:native-completion": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/native-completion.e2e.ts", diff --git a/bindings/py/README.md b/bindings/py/README.md index 518ff4e9..caeab146 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -144,11 +144,20 @@ I8/U8/Char16. For example, `from_i32(255)` is accepted for U8; queried for the declared IID; an incompatible interface raises, while `DynWinRTValue.null_value()` remains a null reference. +For admitted POD structs, vector `IndexOf` and map key operations compare +metadata-declared fields by value, including nested fields, and ignore padding. +Floating fields use numerical equality: `+0` and `-0` match, while NaN does not +match even the same NaN bits. This also applies to collection views; a +NaN-containing struct map key is not found by lookup. Stored field bits are +not normalized. + The Python helpers use validated typed core factories. Rust callers can use the safe `create_vector_from_values` / `create_map_from_values` factories for the same checks. The metadata-free Rust `create_value_vector`, `create_vector`, and `create_map` constructors require `unsafe`: callers must prove the native ABI, ownership, element types, and complete IID set themselves. +The metadata-free `create_value_vector` retains packed-byte equality, including +padding, rather than metadata-directed field equality. Unsupported layouts raise `RuntimeError`; HRESULT-backed type, range, or QueryInterface failures raise `OSError`. Complete native struct collection support is tracked in diff --git a/crates/dynwinrt/src/collection_element.rs b/crates/dynwinrt/src/collection_element.rs index d0271aa7..c24ca834 100644 --- a/crates/dynwinrt/src/collection_element.rs +++ b/crates/dynwinrt/src/collection_element.rs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +use std::sync::Arc; use windows_core::{HSTRING, IUnknown, Interface}; use crate::{Error, Result, TypeHandle, TypeKind, WinRTValue}; @@ -186,9 +187,127 @@ fn pod_layout(typ: &TypeHandle, depth: usize) -> Result { }) } +#[derive(Clone)] +pub(crate) enum CollectionEquality { + Storage, + Struct(Arc<[StructEqualityField]>), +} + +pub(crate) struct StructEqualityField { + offset: usize, + kind: ScalarEqualityKind, +} + +enum ScalarEqualityKind { + U8, + U16, + U32, + U64, + F32, + F64, +} + +impl StructEqualityField { + fn read(&self, word: &[u8]) -> [u8; N] { + let mut bytes = [0; N]; + bytes.copy_from_slice(&word[self.offset..self.offset + N]); + bytes + } + + fn equal(&self, left: &[u8], right: &[u8]) -> bool { + match self.kind { + ScalarEqualityKind::U8 => left[self.offset] == right[self.offset], + ScalarEqualityKind::U16 => { + u16::from_ne_bytes(self.read(left)) == u16::from_ne_bytes(self.read(right)) + } + ScalarEqualityKind::U32 => { + u32::from_ne_bytes(self.read(left)) == u32::from_ne_bytes(self.read(right)) + } + ScalarEqualityKind::U64 => { + u64::from_ne_bytes(self.read(left)) == u64::from_ne_bytes(self.read(right)) + } + ScalarEqualityKind::F32 => { + f32::from_ne_bytes(self.read(left)) == f32::from_ne_bytes(self.read(right)) + } + ScalarEqualityKind::F64 => { + f64::from_ne_bytes(self.read(left)) == f64::from_ne_bytes(self.read(right)) + } + } + } +} + +impl CollectionEquality { + fn for_struct(typ: &TypeHandle, size: usize) -> Result { + let mut fields = Vec::with_capacity(size); + Self::collect_fields(typ, 0, size, 0, &mut fields)?; + Ok(Self::Struct(fields.into())) + } + + fn collect_fields( + typ: &TypeHandle, + offset: usize, + size: usize, + depth: usize, + fields: &mut Vec, + ) -> Result<()> { + let unsupported = || Error::UnsupportedCollectionElement(typ.kind()); + if depth > 64 + || offset + .checked_add(typ.size_of()) + .is_none_or(|end| end > size) + { + return Err(unsupported()); + } + let kind = match typ.kind() { + TypeKind::Struct(_) => { + if typ.field_count() == 0 { + return Err(unsupported()); + } + for index in 0..typ.field_count() { + let field_offset = offset + .checked_add(typ.field_offset(index)) + .ok_or_else(unsupported)?; + Self::collect_fields( + &typ.field_type(index), + field_offset, + size, + depth + 1, + fields, + )?; + } + return Ok(()); + } + TypeKind::Bool | TypeKind::I8 | TypeKind::U8 => ScalarEqualityKind::U8, + TypeKind::I16 | TypeKind::U16 | TypeKind::Char16 => ScalarEqualityKind::U16, + TypeKind::I32 | TypeKind::U32 | TypeKind::Enum(_) | TypeKind::HResult => { + ScalarEqualityKind::U32 + } + TypeKind::I64 | TypeKind::U64 => ScalarEqualityKind::U64, + TypeKind::F32 => ScalarEqualityKind::F32, + TypeKind::F64 => ScalarEqualityKind::F64, + _ => return Err(unsupported()), + }; + if fields.len() >= size { + return Err(unsupported()); + } + fields.push(StructEqualityField { offset, kind }); + Ok(()) + } + + pub(crate) fn struct_words_equal(&self, left: usize, right: usize) -> Option { + let Self::Struct(fields) = self else { + return None; + }; + let left = left.to_ne_bytes(); + let right = right.to_ne_bytes(); + Some(fields.iter().all(|field| field.equal(&left, &right))) + } +} + pub(crate) struct CollectionElementPlan { typ: TypeHandle, pub(crate) storage: CollectionStorage, + pub(crate) equality: CollectionEquality, } impl CollectionElementPlan { @@ -240,9 +359,17 @@ impl CollectionElementPlan { { return Err(unsupported()); } + let equality = match (typ.kind(), storage) { + // Layout and argument admission precede compilation; only scalar leaves survive. + (TypeKind::Struct(_), CollectionStorage::Word(size)) => { + CollectionEquality::for_struct(typ, size).map_err(|_| unsupported())? + } + _ => CollectionEquality::Storage, + }; Ok(Self { typ: typ.clone(), storage, + equality, }) } @@ -337,6 +464,164 @@ mod tests { use super::*; use crate::{MetadataTable, map::create_map_from_values, vector::create_vector_from_values}; + fn word(bytes: &[u8]) -> usize { + let mut storage = [0; size_of::()]; + storage[..bytes.len()].copy_from_slice(bytes); + usize::from_ne_bytes(storage) + } + + fn assert_fields_equal(typ: &TypeHandle, left: &[u8], right: &[u8], expected: bool) { + let plan = CollectionElementPlan::new(typ, false).unwrap(); + assert_eq!(left.len(), typ.size_of()); + assert_eq!(right.len(), typ.size_of()); + assert_eq!( + plan.equality.struct_words_equal(word(left), word(right)), + Some(expected) + ); + } + + #[test] + fn struct_equality_ignores_nested_internal_and_tail_padding() { + let table = MetadataTable::new(); + let internal = + table.struct_type("Test.InternalPadding", &[table.u8_type(), table.u16_type()]); + let tail = table.struct_type("Test.TailPadding", &[table.u16_type(), table.u8_type()]); + for (inner, left, right, changed) in [ + ( + internal, + [7, 0, 0x34, 0x12], + [7, 0xff, 0x34, 0x12], + [8, 0, 0x34, 0x12], + ), + ( + tail, + [0x34, 0x12, 7, 0], + [0x34, 0x12, 7, 0xff], + [0x34, 0x12, 8, 0], + ), + ] { + let nested = table.struct_type(&format!("Test.Nested{inner:?}"), &[inner]); + assert_fields_equal(&nested, &left, &right, true); + assert_fields_equal(&nested, &left, &changed, false); + if size_of::() > left.len() { + let plan = CollectionElementPlan::new(&nested, false).unwrap(); + let mut high_bits = [0xff; size_of::()]; + high_bits[..right.len()].copy_from_slice(&right); + assert_eq!( + plan.equality + .struct_words_equal(word(&left), usize::from_ne_bytes(high_bits)), + Some(true) + ); + } + } + #[cfg(target_pointer_width = "64")] + { + let inner = table.struct_type("Test.OffsetInner", &[table.u16_type(), table.u8_type()]); + let outer = table.struct_type( + "Test.OffsetOuter", + &[table.u8_type(), inner, table.u8_type()], + ); + let left = [1, 0, 2, 3, 4, 0, 5, 0]; + let right = [1, 0xff, 2, 3, 4, 0xff, 5, 0xff]; + assert_fields_equal(&outer, &left, &right, true); + for offset in [0, 2, 3, 4, 6] { + let mut changed = right; + changed[offset] ^= 1; + assert_fields_equal(&outer, &left, &changed, false); + } + } + } + + #[test] + fn struct_equality_uses_floating_leaf_values_without_normalizing_bits() { + let table = MetadataTable::new(); + let inner = table.struct_type("Test.InnerFloat", &[table.f32_type()]); + let typ = table.struct_type("Test.NestedFloat", &[inner]); + // Exercise the descriptor independently of ARM64's HFA admission rejection. + let plan = CollectionElementPlan::for_target(&typ, false, CollectionTarget::X64).unwrap(); + let nan = f32::from_bits(0x7fc0_0001); + for (left, right, expected) in [ + (0.0f32, -0.0f32, true), + (-0.0, 0.0, true), + (2.0, 2.0, true), + (2.0, 3.0, false), + (f32::INFINITY, f32::INFINITY, true), + (nan, nan, false), + (nan, f32::from_bits(0x7fc0_0002), false), + ] { + assert_eq!( + plan.equality + .struct_words_equal(word(&left.to_ne_bytes()), word(&right.to_ne_bytes())), + Some(expected) + ); + } + #[cfg(target_pointer_width = "64")] + { + let typ = table.struct_type("Test.Double", &[table.f64_type()]); + let plan = + CollectionElementPlan::for_target(&typ, false, CollectionTarget::X64).unwrap(); + let nan = f64::from_bits(0x7ff8_0000_0000_0001); + for (left, right, expected) in [ + (0.0f64, -0.0f64, true), + (2.0, 2.0, true), + (2.0, 3.0, false), + (nan, nan, false), + (nan, f64::from_bits(0x7ff8_0000_0000_0002), false), + ] { + assert_eq!( + plan.equality + .struct_words_equal(word(&left.to_ne_bytes()), word(&right.to_ne_bytes())), + Some(expected) + ); + } + } + } + + #[test] + fn struct_equality_preserves_scalar_widths_and_nonstruct_plans() { + fn assert_send_sync() {} + assert_send_sync::(); + let table = MetadataTable::new(); + for field in [ + table.bool_type(), + table.i8_type(), + table.u8_type(), + table.i16_type(), + table.u16_type(), + table.char16_type(), + table.i32_type(), + table.u32_type(), + table.hresult(), + table.enum_type("Test.FieldEnum", vec![]), + table.i64_type(), + table.u64_type(), + ] { + if field.size_of() > size_of::() { + continue; + } + let typ = table.struct_type( + &format!("Test.Scalar{field:?}"), + std::slice::from_ref(&field), + ); + let zero = vec![0; typ.size_of()]; + let mut one = zero.clone(); + one[0] = 1; + assert_fields_equal(&typ, &zero, &zero, true); + assert_fields_equal(&typ, &zero, &one, false); + assert_fields_equal(&typ, &one, &one, true); + assert!(matches!( + CollectionElementPlan::new(&field, false).unwrap().equality, + CollectionEquality::Storage + )); + } + for typ in [table.hstring(), table.object()] { + assert!(matches!( + CollectionElementPlan::new(&typ, false).unwrap().equality, + CollectionEquality::Storage + )); + } + } + #[test] fn target_argument_classification_and_empty_policy() { use ArgumentAbi::*; diff --git a/crates/dynwinrt/src/map.rs b/crates/dynwinrt/src/map.rs index b83fb7aa..78b29037 100644 --- a/crates/dynwinrt/src/map.rs +++ b/crates/dynwinrt/src/map.rs @@ -11,7 +11,7 @@ use core::ffi::c_void; use std::sync::Mutex; use windows_core::{GUID, HRESULT, IUnknown, Interface}; -use crate::collection_element::{CollectionElementPlan, CollectionStorage}; +use crate::collection_element::{CollectionElementPlan, CollectionEquality, CollectionStorage}; use crate::com_helpers::{E_BOUNDS, E_FAIL, IInspectableVtbl, S_OK}; #[allow(unused_imports)] use crate::com_helpers::{dual_vtable_com, inspectable_stubs, lock_or, single_vtable_com}; @@ -84,6 +84,7 @@ unsafe fn find_key_index( entries: &[(usize, usize)], key: *mut c_void, storage: CollectionStorage, + equality: &CollectionEquality, ) -> Option { let key = key as usize; if !storage.is_hstring() @@ -96,7 +97,7 @@ unsafe fn find_key_index( } entries .iter() - .position(|(stored, _)| stored_items_equal(storage, *stored, key)) + .position(|(stored, _)| stored_items_equal(storage, equality, *stored, key)) } unsafe fn boxed_hstring(raw: usize) -> Option { @@ -125,6 +126,7 @@ struct SingleThreadedMap { entries: Mutex>, key_storage: CollectionStorage, value_storage: CollectionStorage, + key_equality: CollectionEquality, iids: MapIids, } @@ -201,7 +203,7 @@ impl SingleThreadedMap { ) -> HRESULT { let me = Self::from_map_ptr(this); let entries = lock_or!(me.entries, E_FAIL); - match find_key_index(&entries, key, me.key_storage) { + match find_key_index(&entries, key, me.key_storage, &me.key_equality) { Some(i) => { write_item_out(me.value_storage, entries[i].1, result); S_OK @@ -223,7 +225,7 @@ impl SingleThreadedMap { ) -> HRESULT { let me = Self::from_map_ptr(this); let entries = lock_or!(me.entries, E_FAIL); - *result = find_key_index(&entries, key, me.key_storage).is_some(); + *result = find_key_index(&entries, key, me.key_storage, &me.key_equality).is_some(); S_OK } @@ -242,6 +244,7 @@ impl SingleThreadedMap { snapshot, me.key_storage, me.value_storage, + me.key_equality.clone(), me.iids.clone(), ); // WinRT ABI: get_view must return an IMapView pointer (second vtable), @@ -259,7 +262,7 @@ impl SingleThreadedMap { ) -> HRESULT { let me = Self::from_map_ptr(this); let mut entries = lock_or!(me.entries, E_FAIL); - match find_key_index(&entries, key, me.key_storage) { + match find_key_index(&entries, key, me.key_storage, &me.key_equality) { Some(i) => { let old_value = entries[i].1; entries[i].1 = store_abi_item(me.value_storage, value); @@ -280,7 +283,7 @@ impl SingleThreadedMap { unsafe extern "system" fn remove(this: *mut c_void, key: *mut c_void) -> HRESULT { let me = Self::from_map_ptr(this); let mut entries = lock_or!(me.entries, E_FAIL); - match find_key_index(&entries, key, me.key_storage) { + match find_key_index(&entries, key, me.key_storage, &me.key_equality) { Some(i) => { let (key, value) = entries.remove(i); release_stored_item(me.key_storage, key); @@ -327,6 +330,7 @@ struct SingleThreadedMapView { entries: Vec<(usize, usize)>, key_storage: CollectionStorage, value_storage: CollectionStorage, + key_equality: CollectionEquality, iids: MapIids, } @@ -369,6 +373,7 @@ impl SingleThreadedMapView { entries: Vec<(usize, usize)>, key_storage: CollectionStorage, value_storage: CollectionStorage, + key_equality: CollectionEquality, iids: MapIids, ) -> IUnknown { let view = Box::new(Self { @@ -378,6 +383,7 @@ impl SingleThreadedMapView { entries, key_storage, value_storage, + key_equality, iids, }); unsafe { IUnknown::from_raw(Box::into_raw(view) as *mut c_void) } @@ -417,7 +423,7 @@ impl SingleThreadedMapView { result: *mut *mut c_void, ) -> HRESULT { let me = Self::from_view_ptr(this); - match find_key_index(&me.entries, key, me.key_storage) { + match find_key_index(&me.entries, key, me.key_storage, &me.key_equality) { Some(i) => { write_item_out(me.value_storage, me.entries[i].1, result); S_OK @@ -438,7 +444,7 @@ impl SingleThreadedMapView { result: *mut bool, ) -> HRESULT { let me = Self::from_view_ptr(this); - *result = find_key_index(&me.entries, key, me.key_storage).is_some(); + *result = find_key_index(&me.entries, key, me.key_storage, &me.key_equality).is_some(); S_OK } @@ -568,13 +574,15 @@ pub unsafe fn create_map(entries: Vec<(IUnknown, IUnknown)>, iids: MapIids) -> I .map(|(key, value)| (key.into_raw() as usize, value.into_raw() as usize)) .collect(); let storage = CollectionStorage::Object; - new_map(entries, storage, storage, iids) + new_map(entries, storage, storage, CollectionEquality::Storage, iids) } /// Create a checked map, validating element types, layouts, ownership and all IIDs. /// /// Keys and values must use the same metadata table. Large values are unsupported /// even in an empty map; reference values are queried for the declared interface. +/// Admitted struct keys compare their fields by value, ignoring padding. +/// Floating fields use numerical equality: signed zeros match, but NaNs do not. pub fn create_map_from_values( entries: &[(crate::WinRTValue, crate::WinRTValue)], key_type: &crate::TypeHandle, @@ -603,13 +611,20 @@ pub fn create_map_from_values( .into_iter() .map(|(key, value)| (key.into_raw(), value.into_raw())) .collect(); - Ok(new_map(entries, key_plan.storage, value_plan.storage, iids)) + Ok(new_map( + entries, + key_plan.storage, + value_plan.storage, + key_plan.equality, + iids, + )) } fn new_map( entries: Vec<(usize, usize)>, key_storage: CollectionStorage, value_storage: CollectionStorage, + key_equality: CollectionEquality, iids: MapIids, ) -> IUnknown { let map = Box::new(SingleThreadedMap { @@ -619,6 +634,7 @@ fn new_map( entries: Mutex::new(entries), key_storage, value_storage, + key_equality, iids, }); unsafe { IUnknown::from_raw(Box::into_raw(map) as *mut c_void) } @@ -690,7 +706,14 @@ mod tests { let entries = vec![(stored_raw, 0)]; assert_eq!( - unsafe { find_key_index(&entries, search.as_raw(), object_storage()) }, + unsafe { + find_key_index( + &entries, + search.as_raw(), + object_storage(), + &CollectionEquality::Storage, + ) + }, Some(0) ); diff --git a/crates/dynwinrt/src/vector.rs b/crates/dynwinrt/src/vector.rs index fcd5669b..43d26899 100644 --- a/crates/dynwinrt/src/vector.rs +++ b/crates/dynwinrt/src/vector.rs @@ -15,7 +15,9 @@ use std::sync::{ }; use windows_core::{GUID, HRESULT, HSTRING, IUnknown, Interface}; -use crate::collection_element::{CollectionElementPlan, CollectionStorage, PreparedCollectionItem}; +use crate::collection_element::{ + CollectionElementPlan, CollectionEquality, CollectionStorage, PreparedCollectionItem, +}; use crate::com_helpers::{ E_BOUNDS, E_FAIL, E_NOTIMPL, IInspectableVtbl, S_OK, com_to_usize, com_usize_addref_out, com_usize_release, @@ -274,9 +276,13 @@ pub(crate) unsafe fn release_stored_item(storage: CollectionStorage, raw: usize) pub(crate) unsafe fn stored_items_equal( storage: CollectionStorage, + equality: &CollectionEquality, left: usize, right: usize, ) -> bool { + if let Some(equal) = equality.struct_words_equal(left, right) { + return equal; + } if !storage.is_hstring() { return if storage.is_value_type() { normalize_value_word(left, storage.element_size()) @@ -330,6 +336,7 @@ struct SingleThreadedVector { handlers: Mutex>, next_token: AtomicI64, storage: CollectionStorage, + equality: CollectionEquality, iids: VectorIids, } @@ -530,7 +537,12 @@ impl SingleThreadedVector { .iter() .map(|&raw| unsafe { clone_stored_item(me.storage, raw) }) .collect(); - let view = SingleThreadedVectorView::create(snapshot, me.storage, me.iids.clone()); + let view = SingleThreadedVectorView::create( + snapshot, + me.storage, + me.equality.clone(), + me.iids.clone(), + ); // WinRT ABI: get_view must return an IVectorView pointer (second vtable), // not the identity/IIterable pointer (first vtable). let identity = view.into_raw(); @@ -552,7 +564,7 @@ impl SingleThreadedVector { let items = lock_or!(me.items, E_FAIL); let needle = value as usize; for (i, &item) in items.iter().enumerate() { - if stored_items_equal(me.storage, item, needle) { + if stored_items_equal(me.storage, &me.equality, item, needle) { *index = i as u32; *found = true; return S_OK; @@ -734,7 +746,7 @@ impl SingleThreadedVector { let items = lock_or!(me.items, E_FAIL); let needle = value as usize; for (i, &item) in items.iter().enumerate() { - if stored_items_equal(me.storage, item, needle) { + if stored_items_equal(me.storage, &me.equality, item, needle) { *index = i as u32; *found = true; return S_OK; @@ -789,6 +801,7 @@ struct SingleThreadedVectorView { ref_count: windows_core::imp::RefCount, items: Vec, storage: CollectionStorage, + equality: CollectionEquality, iids: VectorIids, } @@ -827,13 +840,19 @@ impl SingleThreadedVectorView { get_many: Self::get_many, }; - fn create(items: Vec, storage: CollectionStorage, iids: VectorIids) -> IUnknown { + fn create( + items: Vec, + storage: CollectionStorage, + equality: CollectionEquality, + iids: VectorIids, + ) -> IUnknown { let view = Box::new(Self { vtable_iterable: &Self::ITERABLE_VTBL, vtable_view: &Self::VIEW_VTBL, ref_count: windows_core::imp::RefCount::new(1), items, storage, + equality, iids, }); unsafe { IUnknown::from_raw(Box::into_raw(view) as *mut c_void) } @@ -890,7 +909,7 @@ impl SingleThreadedVectorView { } let needle = value as usize; for (i, &item) in me.items.iter().enumerate() { - if stored_items_equal(me.storage, item, needle) { + if stored_items_equal(me.storage, &me.equality, item, needle) { *index = i as u32; *found = true; return S_OK; @@ -1050,6 +1069,8 @@ impl Drop for SingleThreadedIterator { /// Validates the complete IID set, exact element types, native argument ABI, /// and ownership before publication. Only word-sized POD values are stored. /// Some indirectly passed large POD types support empty-only vectors. +/// Admitted struct fields compare by value, ignoring padding; floating fields +/// use numerical equality, including equal signed zeros and unequal NaNs. pub fn create_vector_from_values( items: &[crate::WinRTValue], element_type: &crate::TypeHandle, @@ -1069,7 +1090,7 @@ pub fn create_vector_from_values( .into_iter() .map(PreparedCollectionItem::into_raw) .collect(); - Ok(new_vector(packed, plan.storage, iids)) + Ok(new_vector(packed, plan.storage, plan.equality, iids)) } /// Create an IVector COM object from a Vec of IUnknown items (reference types). @@ -1087,12 +1108,19 @@ pub unsafe fn create_vector(items: Vec, iids: VectorIids) -> IUnknown .into_iter() .map(|obj| obj.into_raw() as usize) .collect(); - new_vector(raw_items, CollectionStorage::Object, iids) + new_vector( + raw_items, + CollectionStorage::Object, + CollectionEquality::Storage, + iids, + ) } /// Create an IVector COM object from raw POD value bytes. /// -/// Prefer [`create_vector_from_values`] for checked construction. +/// This metadata-free constructor compares packed bytes, including padding, +/// rather than typed struct fields. Prefer [`create_vector_from_values`] for +/// checked construction and metadata-directed value equality. /// /// # Safety /// @@ -1130,10 +1158,15 @@ pub unsafe fn create_value_vector( val }) .collect(); - new_vector(packed, storage, iids) + new_vector(packed, storage, CollectionEquality::Storage, iids) } -fn new_vector(items: Vec, storage: CollectionStorage, iids: VectorIids) -> IUnknown { +fn new_vector( + items: Vec, + storage: CollectionStorage, + equality: CollectionEquality, + iids: VectorIids, +) -> IUnknown { let vector = Box::new(SingleThreadedVector { vtable_iterable: &SingleThreadedVector::ITERABLE_VTBL, vtable_vector: &SingleThreadedVector::VECTOR_VTBL, @@ -1144,6 +1177,7 @@ fn new_vector(items: Vec, storage: CollectionStorage, iids: VectorIids) - handlers: Mutex::new(HashMap::new()), next_token: AtomicI64::new(1), storage, + equality, iids, }); unsafe { IUnknown::from_raw(Box::into_raw(vector) as *mut c_void) } diff --git a/crates/dynwinrt/src/vector_abi_tests.rs b/crates/dynwinrt/src/vector_abi_tests.rs index 4a90e37e..c3253807 100644 --- a/crates/dynwinrt/src/vector_abi_tests.rs +++ b/crates/dynwinrt/src/vector_abi_tests.rs @@ -276,6 +276,258 @@ fn typed_point_size_and_integer_pair_boundaries() { } } +#[cfg(target_arch = "x86_64")] +fn point_value(typ: &TypeHandle, point: Point) -> WinRTValue { + let mut value = typ.default_value(); + value.set_field(0, point.X); + value.set_field(1, point.Y); + WinRTValue::Struct(value) +} + +#[cfg(target_arch = "x86_64")] +#[test] +fn struct_equality_point_signed_zero_matches_all_views() { + let table = MetadataTable::new(); + let typ = table.struct_type( + "Windows.Foundation.Point", + &[table.f32_type(), table.f32_type()], + ); + for zero in [0.0f32, -0.0] { + let stored = Point { X: zero, Y: 1.0 }; + let opposite = Point { X: -zero, Y: 1.0 }; + assert_eq!(stored, opposite); + assert_ne!(stored.X.to_bits(), opposite.X.to_bits()); + let object = + create_vector_from_values(&[point_value(&typ, stored)], &typ, table.vector_iids(&typ)) + .unwrap(); + let vector: IVector = object.cast().unwrap(); + let live: IVectorView = object.cast().unwrap(); + let snapshot = vector.GetView().unwrap(); + for (query, expected) in [ + (stored, true), + (opposite, true), + (Point { X: 2.0, Y: 1.0 }, false), + (Point { X: zero, Y: 2.0 }, false), + ] { + let mut index = u32::MAX; + assert_eq!(vector.IndexOf(query, &mut index).unwrap(), expected); + assert_eq!(index, 0); + for view in [&live, &snapshot] { + index = u32::MAX; + assert_eq!(view.IndexOf(query, &mut index).unwrap(), expected); + assert_eq!(index, 0); + } + } + assert_eq!(vector.GetAt(0).unwrap().X.to_bits(), zero.to_bits()); + } +} + +#[cfg(target_arch = "x86_64")] +#[test] +fn struct_equality_point_nan_never_matches_even_identical_bits() { + let table = MetadataTable::new(); + let typ = table.struct_type( + "Windows.Foundation.Point", + &[table.f32_type(), table.f32_type()], + ); + let nan = f32::from_bits(0x7fc0_0001); + let other_nan = f32::from_bits(0x7fc0_0002); + for (stored, other) in [ + ( + Point { X: nan, Y: 1.0 }, + Point { + X: other_nan, + Y: 1.0, + }, + ), + ( + Point { X: 1.0, Y: nan }, + Point { + X: 1.0, + Y: other_nan, + }, + ), + ] { + assert_ne!(stored, stored); + let object = + create_vector_from_values(&[point_value(&typ, stored)], &typ, table.vector_iids(&typ)) + .unwrap(); + let vector: IVector = object.cast().unwrap(); + let live: IVectorView = object.cast().unwrap(); + let snapshot = vector.GetView().unwrap(); + for query in [stored, other] { + let mut index = u32::MAX; + assert!(!vector.IndexOf(query, &mut index).unwrap()); + assert_eq!(index, 0); + for view in [&live, &snapshot] { + assert!(!view.IndexOf(query, &mut index).unwrap()); + assert_eq!(index, 0); + } + } + let output = vector.GetAt(0).unwrap(); + assert_eq!(output.X.to_bits(), stored.X.to_bits()); + assert_eq!(output.Y.to_bits(), stored.Y.to_bits()); + } +} + +#[cfg(target_arch = "x86_64")] +#[test] +fn struct_equality_survives_mutation_snapshots_and_metadata_drop() { + let (object, weak) = { + let table = MetadataTable::new(); + let typ = table.struct_type( + "Windows.Foundation.Point", + &[table.f32_type(), table.f32_type()], + ); + ( + create_vector_from_values(&[], &typ, table.vector_iids(&typ)).unwrap(), + std::sync::Arc::downgrade(&table), + ) + }; + assert!(weak.upgrade().is_none()); + let vector: IVector = object.cast().unwrap(); + let live: IVectorView = object.cast().unwrap(); + let positive = Point { X: 0.0, Y: 1.0 }; + let negative = Point { X: -0.0, Y: 1.0 }; + let different = Point { X: 2.0, Y: 3.0 }; + let mut index = u32::MAX; + vector.Append(positive).unwrap(); + assert!(vector.IndexOf(negative, &mut index).unwrap()); + assert!(live.IndexOf(negative, &mut index).unwrap()); + let snapshot = vector.GetView().unwrap(); + vector.SetAt(0, different).unwrap(); + assert!(!live.IndexOf(negative, &mut index).unwrap()); + assert!(snapshot.IndexOf(negative, &mut index).unwrap()); + vector.InsertAt(0, negative).unwrap(); + assert!(live.IndexOf(positive, &mut index).unwrap()); + assert_eq!(index, 0); + assert_eq!(vector.GetAt(0).unwrap().X.to_bits(), (-0.0f32).to_bits()); + vector.ReplaceAll(&[different, positive]).unwrap(); + assert!(vector.IndexOf(negative, &mut index).unwrap()); + assert_eq!(index, 1); + assert!(live.IndexOf(negative, &mut index).unwrap()); + assert_eq!(index, 1); + vector.Clear().unwrap(); + drop(live); + drop(vector); + drop(object); + assert!(snapshot.IndexOf(negative, &mut index).unwrap()); + assert_eq!(index, 0); + assert_eq!(snapshot.GetAt(0).unwrap().X.to_bits(), 0); +} + +#[cfg(target_arch = "x86_64")] +#[test] +fn struct_equality_point_map_keys_agree_with_mutators_and_snapshot() { + use windows_collections::IMap; + + let positive = Point { X: 0.0, Y: 1.0 }; + let negative = Point { X: -0.0, Y: 1.0 }; + let (object, weak) = { + let table = MetadataTable::new(); + let typ = table.struct_type( + "Windows.Foundation.Point", + &[table.f32_type(), table.f32_type()], + ); + ( + crate::map::create_map_from_values( + &[(point_value(&typ, positive), WinRTValue::I32(7))], + &typ, + &table.i32_type(), + table.map_iids(&typ, &table.i32_type()), + ) + .unwrap(), + std::sync::Arc::downgrade(&table), + ) + }; + assert!(weak.upgrade().is_none()); + let map: IMap = object.cast().unwrap(); + assert_eq!(map.Lookup(negative).unwrap(), 7); + assert!(map.HasKey(negative).unwrap()); + assert!(!map.HasKey(Point { X: 1.0, Y: 1.0 }).unwrap()); + let snapshot = map.GetView().unwrap(); + assert!(map.Insert(negative, 9).unwrap()); + assert_eq!(map.Size().unwrap(), 1); + assert_eq!(map.Lookup(positive).unwrap(), 9); + assert_eq!(map.Lookup(negative).unwrap(), 9); + assert_eq!( + map.First() + .unwrap() + .Current() + .unwrap() + .Key() + .unwrap() + .X + .to_bits(), + 0 + ); + map.Remove(negative).unwrap(); + assert_eq!(map.Size().unwrap(), 0); + assert!(!map.HasKey(positive).unwrap()); + drop(map); + drop(object); + assert!(snapshot.HasKey(negative).unwrap()); + assert_eq!(snapshot.Lookup(negative).unwrap(), 7); +} + +#[cfg(target_arch = "x86_64")] +#[test] +fn struct_equality_point_nan_map_key_is_not_found() { + use windows_collections::IMap; + + let table = MetadataTable::new(); + let typ = table.struct_type( + "Windows.Foundation.Point", + &[table.f32_type(), table.f32_type()], + ); + let point = Point { + X: f32::from_bits(0x7fc0_0001), + Y: 1.0, + }; + let object = crate::map::create_map_from_values( + &[(point_value(&typ, point), WinRTValue::I32(7))], + &typ, + &table.i32_type(), + table.map_iids(&typ, &table.i32_type()), + ) + .unwrap(); + let map: IMap = object.cast().unwrap(); + let snapshot = map.GetView().unwrap(); + assert!(!map.HasKey(point).unwrap()); + assert_eq!(map.Lookup(point).unwrap_err().code(), E_BOUNDS); + assert_eq!(map.Remove(point).unwrap_err().code(), E_BOUNDS); + assert!(!snapshot.HasKey(point).unwrap()); + assert_eq!(snapshot.Lookup(point).unwrap_err().code(), E_BOUNDS); + assert_eq!(map.Size().unwrap(), 1); + map.Clear().unwrap(); + assert_eq!(map.Size().unwrap(), 0); +} + +#[cfg(target_arch = "x86_64")] +#[test] +fn struct_equality_raw_constructor_preserves_packed_byte_comparison() { + let table = MetadataTable::new(); + let typ = table.struct_type( + "Windows.Foundation.Point", + &[table.f32_type(), table.f32_type()], + ); + for x in [0.0f32, f32::from_bits(0x7fc0_0001)] { + let bytes = [x.to_ne_bytes(), 1.0f32.to_ne_bytes()].concat(); + let object = unsafe { create_value_vector(vec![bytes], 8, table.vector_iids(&typ)) }; + let vector: IVector = object.cast().unwrap(); + let mut index = u32::MAX; + assert!(vector.IndexOf(Point { X: x, Y: 1.0 }, &mut index).unwrap()); + assert_eq!(index, 0); + if x == 0.0 { + assert!( + !vector + .IndexOf(Point { X: -0.0, Y: 1.0 }, &mut index) + .unwrap() + ); + } + } +} + #[test] fn typed_empty_only_uses_indirect_argument_abi() { let table = MetadataTable::new(); @@ -401,6 +653,62 @@ fn tracked_value(dropped: &std::sync::Arc) -> Wi WinRTValue::Object(unsafe { IUnknown::from_raw(source.into_raw()) }) } +#[test] +fn nonstruct_collection_comparison_preserves_content_and_identity() { + use windows::Foundation::IStringable; + use windows_collections::IMap; + + let table = MetadataTable::new(); + let strings = create_vector_from_values( + &[WinRTValue::HString(HSTRING::from("same content"))], + &table.hstring(), + table.vector_iids(&table.hstring()), + ) + .unwrap(); + let vector: IVector = strings.cast().unwrap(); + let mut index = u32::MAX; + assert!( + vector + .IndexOf(&HSTRING::from("same content"), &mut index) + .unwrap() + ); + assert_eq!(index, 0); + assert!( + !vector + .IndexOf(&HSTRING::from("different"), &mut index) + .unwrap() + ); + + let dropped = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let first: IStringable = Tracked(dropped.clone()).into(); + let other: IStringable = Tracked(dropped.clone()).into(); + assert_eq!(first.ToString().unwrap(), other.ToString().unwrap()); + let typ = table.interface(IStringable::IID); + let value = WinRTValue::Object(first.cast().unwrap()); + let object = + create_vector_from_values(std::slice::from_ref(&value), &typ, table.vector_iids(&typ)) + .unwrap(); + let vector: IVector = object.cast().unwrap(); + assert!(vector.IndexOf(&first, &mut index).unwrap()); + assert_eq!(index, 0); + assert!(!vector.IndexOf(&other, &mut index).unwrap()); + let mapping = crate::map::create_map_from_values( + &[(value, WinRTValue::I32(7))], + &typ, + &table.i32_type(), + table.map_iids(&typ, &table.i32_type()), + ) + .unwrap(); + let map: IMap = mapping.cast().unwrap(); + assert_eq!(map.Lookup(&first).unwrap(), 7); + assert!(!map.HasKey(&other).unwrap()); + vector.Clear().unwrap(); + map.Clear().unwrap(); + drop(first); + drop(other); + assert_eq!(dropped.load(std::sync::atomic::Ordering::SeqCst), 2); +} + #[test] fn typed_interface_preparation_adjusts_and_retains_the_expected_view() { use std::sync::{ From 543d1d8de11dd92a8173a4032658ed96138cf199 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Sun, 20 Sep 2026 12:15:16 +0800 Subject: [PATCH 2/2] Keep collection test factories in a live MTA Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: bdea384f-3022-47e8-8c74-11fd768c2105 --- crates/dynwinrt/src/lib.rs | 3 +++ crates/dynwinrt/src/map.rs | 7 +++---- crates/dynwinrt/src/test_apartment.rs | 16 +++++++++++++++ crates/dynwinrt/src/vector.rs | 29 +++++++++------------------ 4 files changed, 31 insertions(+), 24 deletions(-) create mode 100644 crates/dynwinrt/src/test_apartment.rs diff --git a/crates/dynwinrt/src/lib.rs b/crates/dynwinrt/src/lib.rs index c81668eb..9b5b4f2e 100644 --- a/crates/dynwinrt/src/lib.rs +++ b/crates/dynwinrt/src/lib.rs @@ -36,6 +36,9 @@ pub mod metadata_table; mod reference; pub mod vector; +#[cfg(test)] +mod test_apartment; + pub use crate::array::ArrayData; pub use crate::composition::{ LocalOverrideAbi, LocalOverrideInterface, LocalOverrideSizeCallback, LocalOverrideVoidCallback, diff --git a/crates/dynwinrt/src/map.rs b/crates/dynwinrt/src/map.rs index 78b29037..c198888d 100644 --- a/crates/dynwinrt/src/map.rs +++ b/crates/dynwinrt/src/map.rs @@ -652,8 +652,7 @@ mod tests { #[test] fn test_map_basic_operations() { - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let iids = table.map_iids(&table.hstring(), &table.object()); @@ -696,6 +695,7 @@ mod tests { #[test] fn test_object_keys_compare_boxed_strings_by_value() { + crate::test_apartment::initialize_mta(); let first = windows::Foundation::PropertyValue::CreateString(windows_core::h!("same")).unwrap(); let second = @@ -722,8 +722,7 @@ mod tests { #[test] fn test_key_value_pair() { - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let iids = table.map_iids(&table.hstring(), &table.object()); diff --git a/crates/dynwinrt/src/test_apartment.rs b/crates/dynwinrt/src/test_apartment.rs new file mode 100644 index 00000000..54d92b0c --- /dev/null +++ b/crates/dynwinrt/src/test_apartment.rs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::sync::Once; +use windows::Win32::System::Com::CoIncrementMTAUsage; +use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; + +pub(crate) fn initialize_mta() { + static PROCESS_MTA: Once = Once::new(); + PROCESS_MTA.call_once(|| { + // Retain this native MTA usage until process exit: SDK factory caches outlive + // libtest worker threads, so the last worker must not tear down their MTA. + let _cookie = unsafe { CoIncrementMTAUsage() }.expect("keep the test-process MTA alive"); + }); + unsafe { RoInitialize(RO_INIT_MULTITHREADED) }.expect("initialize the test-thread MTA"); +} diff --git a/crates/dynwinrt/src/vector.rs b/crates/dynwinrt/src/vector.rs index 43d26899..22c24b60 100644 --- a/crates/dynwinrt/src/vector.rs +++ b/crates/dynwinrt/src/vector.rs @@ -1212,8 +1212,7 @@ mod tests { #[test] fn test_vector_basic_operations() { // Create a vector of IUnknown items using Uri objects - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let iids = table.vector_iids(&table.object()); @@ -1278,9 +1277,7 @@ mod tests { fn test_observable_vector_notifications() { use std::sync::Arc; - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let object_type = table.object(); let iids = table.vector_iids(&object_type); @@ -1406,9 +1403,7 @@ mod tests { atomic::{AtomicI64, AtomicUsize, Ordering}, }; - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let iids = table.vector_iids(&table.object()); let vector = checked_object_vector(Vec::new(), iids.clone()); @@ -1567,8 +1562,7 @@ mod tests { #[test] fn test_vector_append_and_clear() { - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let iids = table.vector_iids(&table.object()); @@ -1609,8 +1603,7 @@ mod tests { #[test] fn test_vector_iterator() { - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let iids = table.vector_iids(&table.object()); @@ -1658,8 +1651,7 @@ mod tests { #[test] fn test_vector_qi_vector_view() { // DynVector must support QI for IVectorView (like C++/WinRT's single_threaded_vector) - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let iids = table.vector_iids(&table.object()); @@ -1697,8 +1689,7 @@ mod tests { fn test_vector_get_view_returns_vector_view_ptr() { // get_view() must return an IVectorView pointer, not IIterable. // This was the root cause of ImageObjectExtractor E_NOINTERFACE. - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let iids = table.vector_iids(&table.object()); @@ -1744,8 +1735,7 @@ mod tests { #[test] fn test_vector_get_view_ref_counting() { // Verify ref counting: get_view returns ref=1, Release frees correctly. - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let iids = table.vector_iids(&table.object()); @@ -1837,8 +1827,7 @@ mod tests { /// Accessing from multiple threads should not panic. #[test] fn test_vector_thread_safety() { - use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize}; - let _ = unsafe { RoInitialize(RO_INIT_MULTITHREADED) }; + crate::test_apartment::initialize_mta(); let table = MetadataTable::new(); let iids = table.vector_iids(&table.object());