未验证 提交 c0df4cd8 编写于 作者: N Nathan Moreau 提交者: GitHub

ImmutableDictionary.AddRange: throw if any item has a null Key. (#51438)

The behavior of AddRange(items) should be the same as
foreach(var item in items) Add(item); Add(item) throws if item.Key == null,
so AddRange should it as well.

Fix #50865.
上级 ab4e593f
......@@ -963,6 +963,7 @@ private static MutationResult AddRange(IEnumerable<KeyValuePair<TKey, TValue>> i
var newRoot = origin.Root;
foreach (var pair in items)
{
Requires.NotNullAllowStructs(pair.Key, nameof(pair.Key));
int hashCode = origin.KeyComparer.GetHashCode(pair.Key);
HashBucket bucket = newRoot.GetValueOrDefault(hashCode);
OperationResult result;
......
......@@ -47,6 +47,15 @@ public void ToBuilder()
Assert.False(set.ContainsKey(8));
}
[Fact]
public void BuilderAddRangeThrowsWhenAddingNullKey()
{
var set = ImmutableDictionary<string, int>.Empty.Add("1", 1);
var builder = set.ToBuilder();
var items = new[] { new KeyValuePair<string, int>(null, 0) };
Assert.Throws<ArgumentNullException>(() => builder.AddRange(items));
}
[Fact]
public void BuilderFromMap()
{
......
......@@ -24,6 +24,18 @@ public void AddExistingKeyDifferentValueTest()
AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void AddRangeShouldThrowOnNullKeyTest()
{
var items = new[] { new KeyValuePair<string, string>(null, "value") };
var map = Empty(StringComparer.Ordinal, StringComparer.Ordinal);
Assert.Throws<ArgumentNullException>(() => map.AddRange(items));
map = map.WithComparers(new BadHasher<string>());
Assert.Throws<ArgumentNullException>(() => map.AddRange(items));
}
[Fact]
public void UnorderedChangeTest()
{
......@@ -59,6 +71,16 @@ public void SetItemUpdateEqualKeyTest()
Assert.Equal("a", map.Keys.Single());
}
[Fact]
public void SetItemsThrowOnNullKey()
{
var map = Empty<string, int>().WithComparers(StringComparer.OrdinalIgnoreCase);
var items = new[] { new KeyValuePair<string, int>(null, 0) };
Assert.Throws<ArgumentNullException>(() => map.SetItems(items));
map = map.WithComparers(new BadHasher<string>());
Assert.Throws<ArgumentNullException>(() => map.SetItems(items));
}
/// <summary>
/// Verifies that the specified value comparer is applied when
/// checking for equality.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册