Implement ICollection.CopyTo (using Array) for MapField views.

This commit is contained in:
Jon Skeet 2015-08-10 08:47:07 +01:00
parent 3f45d7c11e
commit 5be01ee65b
2 changed files with 26 additions and 1 deletions

View file

@ -523,6 +523,20 @@ namespace Google.Protobuf.Collections
keys.CopyTo(array, 1);
CollectionAssert.AreEqual(new[] { null, "foo", "x", null }, array);
}
// Just test keys - we know the implementation is the same for values
[Test]
public void NonGenericViewCopyTo()
{
IDictionary map = new MapField<string, string> { { "foo", "bar" }, { "x", "y" } };
ICollection keys = map.Keys;
// Note the use of the Array type here rather than string[]
Array array = new string[4];
Assert.Throws<ArgumentException>(() => keys.CopyTo(array, 3));
Assert.Throws<ArgumentOutOfRangeException>(() => keys.CopyTo(array, -1));
keys.CopyTo(array, 1);
CollectionAssert.AreEqual(new[] { null, "foo", "x", null }, array);
}
[Test]
public void KeysContains()

View file

@ -735,7 +735,18 @@ namespace Google.Protobuf.Collections
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
if (index < 0)
{
throw new ArgumentOutOfRangeException("arrayIndex");
}
if (index + Count >= array.Length)
{
throw new ArgumentException("Not enough space in the array", "array");
}
foreach (var item in this)
{
array.SetValue(item, index++);
}
}
}
}