Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions bindings/js/__test__/collection-factories.e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,47 @@ test('generated string map factory converts both keys and values', (t) => {
assert.throws(() => generated.IMap_String_String.create(['mismatch'], []), /same length/)
})

test('generated map factory keeps the last duplicate value and first key order', (t) => {
const keep = own(t)
const duplicate = keep(generated.IMap_String_String.create(['same', 'same'], ['first', 'second']))
assert.equal(duplicate.size, 1)
assert.equal(duplicate.lookup('same'), 'second')
duplicate.remove('same')
assert.equal(duplicate.size, 0)
assert.equal(duplicate.hasKey('same'), false)

const map = keep(generated.IMap_String_String.create(['A', 'B', 'A'], ['first', 'middle', 'last']))
const control = keep(generated.IMap_String_String.create([], []))
assert.equal(control.insert('A', 'first'), false)
assert.equal(control.insert('B', 'middle'), false)
assert.equal(control.insert('A', 'last'), true)
const view = keep(map.getView())
const iterableNames = Object.keys(generated).filter((name) =>
name.startsWith('IIterable_WindowsFoundationCollectionsIKeyValuePair_String_String_'),
)
assert.equal(iterableNames.length, 1)
assert.equal(map.size, 2)
for (const source of [map, control, view]) {
assert.equal(source.lookup('A'), 'last')
assert.equal(source.lookup('B'), 'middle')
const iterable = keep(new generated[iterableNames[0]](source._obj))
const iterator = keep(iterable.first())
const entries = []
while (iterator.hasCurrent) {
const pair = keep(iterator.current)
entries.push([pair.key, pair.value])
iterator.moveNext()
}
assert.deepEqual(entries, [
['A', 'last'],
['B', 'middle'],
])
}
map.clear()
assert.equal(view.size, 2)
assert.equal(view.lookup('A'), 'last')
})

test('typed empty factories still support append and insert', (t) => {
const keep = own(t)
const vector = keep(generated.IVector_String.create([]))
Expand Down Expand Up @@ -202,6 +243,7 @@ test('collection-valued map factories preserve managed nulls without weakening n
const uri = keep(generated.Uri.createUri('https://example.invalid/wrong-collection'))
for (const invalid of [uri, uri._obj, {}, { isNull: () => true }, null, undefined]) {
assert.throws(() => Map.create(['invalid'], [invalid]), /QueryInterface|cast/)
assert.throws(() => Map.create(['duplicate', 'duplicate'], [nil, invalid]), /QueryInterface|cast/)
}
let reads = 0
const wrappedNull = {
Expand Down
26 changes: 26 additions & 0 deletions bindings/py/tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,32 @@ def test_create_map_round_trips_values_and_validates_lengths():
)


def test_create_map_duplicate_keys_keep_the_last_value():
key_type = DynWinRTType.hstring()
value_type = DynWinRTType.i32_type()
reader = _collection_map_reader(key_type, value_type)
keys = [DynWinRTValue.from_hstring(key) for key in ["A", "B", "A"]]
values = [DynWinRTValue.from_i32(value) for value in [1, 2, 3]]
mapping = DynWinRTValue.create_map(keys, values, key_type, value_type)
try:
assert _invoke_collection_reader(reader, mapping, 7, []).to_u32() == 2
for key, expected in [("A", 3), ("B", 2)]:
assert _invoke_collection_reader(
reader, mapping, 6, [DynWinRTValue.from_hstring(key)]
).to_int() == expected
assert keys[0].to_string() == "A"
assert values[0].to_int() == 1
with pytest.raises(OSError):
DynWinRTValue.create_map(
[keys[0], keys[0]],
[values[0], DynWinRTValue.from_hstring("invalid later duplicate")],
key_type,
value_type,
)
finally:
mapping.release()


def test_guid_parse():
"""WinGUID.parse should parse valid GUIDs."""
guid = WinGUID.parse("9e365e57-48b2-4160-956f-c7385120bbfc")
Expand Down
9 changes: 9 additions & 0 deletions crates/dynwinrt/src/collection_element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,15 @@ pub(crate) enum PreparedCollectionItem {
}

impl PreparedCollectionItem {
/// Borrow the ABI word without transferring ownership.
pub(crate) fn as_raw(&self) -> usize {
match self {
Self::Word(word) => *word,
Self::HString(value) => unsafe { std::mem::transmute_copy::<HSTRING, usize>(value) },
Self::Object(object) => object.as_ref().map_or(0, |object| object.as_raw() as usize),
}
}

pub(crate) fn into_raw(self) -> usize {
match self {
Self::Word(word) => word,
Expand Down
43 changes: 34 additions & 9 deletions crates/dynwinrt/src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, CollectionStorage, PreparedCollectionItem};
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};
Expand Down Expand Up @@ -85,18 +85,21 @@ unsafe fn find_key_index(
key: *mut c_void,
storage: CollectionStorage,
) -> Option<usize> {
let key = key as usize;
find_key_position(entries.iter().map(|(key, _)| *key), key as usize, storage)
}

unsafe fn find_key_position(
mut keys: impl Iterator<Item = usize>,
key: usize,
storage: CollectionStorage,
) -> Option<usize> {
if !storage.is_hstring()
&& !storage.is_value_type()
&& let Some(search) = boxed_hstring(key)
{
return entries
.iter()
.position(|(stored, _)| boxed_hstring(*stored).is_some_and(|value| value == search));
return keys.position(|stored| boxed_hstring(stored).is_some_and(|value| value == search));
}
entries
.iter()
.position(|(stored, _)| stored_items_equal(storage, *stored, key))
keys.position(|stored| stored_items_equal(storage, stored, key))
}

unsafe fn boxed_hstring(raw: usize) -> Option<windows_core::HSTRING> {
Expand Down Expand Up @@ -575,6 +578,8 @@ pub unsafe fn create_map(entries: Vec<(IUnknown, IUnknown)>, iids: MapIids) -> I
///
/// 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.
/// Duplicate keys use the same equality as `Insert`: the last value wins while
/// retaining the first key and its position. Every input pair is validated.
pub fn create_map_from_values(
entries: &[(crate::WinRTValue, crate::WinRTValue)],
key_type: &crate::TypeHandle,
Expand All @@ -599,7 +604,23 @@ pub fn create_map_from_values(
Ok((key_plan.prepare(key)?, value_plan.prepare(value)?))
})
.collect::<crate::Result<Vec<_>>>()?;
let entries = prepared
let mut unique: Vec<(PreparedCollectionItem, PreparedCollectionItem)> =
Vec::with_capacity(prepared.len());
for (key, value) in prepared {
let index = unsafe {
find_key_position(
unique.iter().map(|(key, _)| key.as_raw()),
key.as_raw(),
key_plan.storage,
)
};
if let Some(index) = index {
unique[index].1 = value;
} else {
unique.push((key, value));
}
}
let entries = unique
.into_iter()
.map(|(key, value)| (key.into_raw(), value.into_raw()))
.collect();
Expand Down Expand Up @@ -628,6 +649,10 @@ fn new_map(
// Tests
// ======================================================================

#[cfg(test)]
#[path = "map_constructor_tests.rs"]
mod constructor_tests;

#[cfg(test)]
#[allow(unused_must_use)]
mod tests {
Expand Down
Loading
Loading