Skip to content

Commit

Permalink
Fix InlineDictionary Behavior for Single Item Reassignment (#17370)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
lindexi authored and maxkatz6 committed Nov 14, 2024
1 parent 1d757a6 commit 1b33329
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/Avalonia.Base/Utilities/SmallDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,17 @@ void SetCore(TKey key, TValue value, bool overwrite)
}
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;
Expand Down
11 changes: 11 additions & 0 deletions tests/Avalonia.Base.UnitTests/Utilities/InlineDictionaryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down

0 comments on commit 1b33329

Please sign in to comment.