Skip to content

Commit

Permalink
Fix missing hashcode set in OrderedDictionary.SetAt
Browse files Browse the repository at this point in the history
  • Loading branch information
stephentoub committed Jun 18, 2024
1 parent a0b8890 commit b07b5b8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
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;
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()
{
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

0 comments on commit b07b5b8

Please sign in to comment.