Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix missing hashcode set in OrderedDictionary.SetAt #103643

Merged
merged 1 commit into from
Jun 18, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -809,8 +809,8 @@ public void SetAt(int index, TKey key, TValue value)
}

// The key doesn't match that index. If it exists elsewhere in the collection, fail.
uint _ = 0, collisionCount = 0;
if (IndexOf(key, ref _, ref collisionCount) >= 0)
uint hashCode = 0, collisionCount = 0;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just curious why do we use uint for collision count? In general we use signed everywhere unless we need the full range.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This just copies what Dictionary<TKey, TValue> does. I believe it uses uint just to make it very clear there's no possibility of overflow.

if (IndexOf(key, ref hashCode, ref collisionCount) >= 0)
{
ThrowHelper.ThrowDuplicateKey(key);
}
Expand All @@ -820,6 +820,7 @@ public void SetAt(int index, TKey key, TValue value)
// (we could check for this, but in a properly balanced dictionary the chances should
// be low for a match, so it's not worth it).
RemoveEntryFromBucket(index);
e.HashCode = hashCode;
e.Key = key;
e.Value = value;
PushEntryIntoBucket(ref e, index);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,25 @@ public void OrderedDictionary_Generic_SetAt_GetAt_Roundtrip(int count)
}
}

[Fact]
public void OrderedDictionary_SetAt_KeyValuePairSubsequentlyAvailable()
{
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
TKey key0 = CreateTKey(0), key1 = CreateTKey(1);
TValue value0 = CreateTValue(0), value1 = CreateTValue(1);

var dict = new OrderedDictionary<TKey, TValue>
{
[key0] = value0,
};

dict.SetAt(index: 0, key1, value1);

Assert.Equal(1, dict.Count);
Assert.Equal([new(key1, value1)], dict);
Assert.False(dict.ContainsKey(key0));
Assert.True(dict.ContainsKey(key1));
}

#endregion

#region Remove(..., out TValue)
Expand Down
Loading