Browse Source

Fix InlineDictionary Behavior for Single Item Reassignment (#17370)

* Fix InlineDictionary Behavior for Single Item Reassignment

Previous Behavior:

- When the `Set` method was called, it ignored the `overwrite` parameter if the dictionary contained only one item.
- This caused the `Set` method to behave like the `Add` method, leading to unexpected behavior in composition animations.
- Specifically, the second composition animation would not play because it could not replace the first animation. Instead, it was added after the first animation, preventing it from being executed.

Updated Behavior:

- The `InlineDictionary` now respects the `overwrite` parameter even when it contains only one item.
- This ensures that the second composition animation can overwrite the first one, allowing it to play correctly.

* Append unit test for InlineDictionary

* keep the `(TKey)_data` in a variable and reuse it below line 90 so we avoid a double cast

* Rename the test method

* Remove the unnecessary assignment code.
release/11.2.1
lindexi 1 year ago
committed by Max Katz
parent
commit
1b33329384
  1. 12
      src/Avalonia.Base/Utilities/SmallDictionary.cs
  2. 11
      tests/Avalonia.Base.UnitTests/Utilities/InlineDictionaryTests.cs

12
src/Avalonia.Base/Utilities/SmallDictionary.cs

@ -77,9 +77,17 @@ internal struct InlineDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey,
}
else
{
// We have a single element, upgrade to array
// We have a single element, check if we should update the value.
var data = (TKey)_data;
if (data == key && overwrite)
{
_value = value;
return;
}
// If we do not replace it, upgrade to array.
arr = new KeyValuePair[6];
arr[0] = new KeyValuePair((TKey)_data, _value);
arr[0] = new KeyValuePair(data, _value);
arr[1] = new KeyValuePair(key, value);
_data = arr;
_value = default;

11
tests/Avalonia.Base.UnitTests/Utilities/InlineDictionaryTests.cs

@ -8,6 +8,17 @@ namespace Avalonia.Base.UnitTests.Utilities;
public class InlineDictionaryTests
{
[Fact]
public void Set_Twice_With_Single_Item_Works()
{
var dic = new InlineDictionary<string, int>();
dic["foo"] = 1;
Assert.Equal(1, dic["foo"]);
dic["foo"] = 2;
Assert.Equal(2, dic["foo"]);
}
[Fact]
public void Enumeration_After_Add_With_Internal_Array_Works()
{

Loading…
Cancel
Save