BitArray.CopyTo throws IndexOutOfRangeException under certain conditions
Description
If BitArray.CopyTo is invoked with:
- destination array being an
int[](does not reproduce withbool[]norbyte[]) - the destination array is too small
- bit count in
BitArrayis not divisible by 32.
Throwing of ArgumentException is delegated to calling of Array.Copy.
Although if the BitArray contains "extra bits", this check is not done for the last extra bits, so IndexOutOfRangeException can be thrown. The check is essentially of-by one under these circumstances.
Reproduction Steps
new BitArray(33).CopyTo(new int[1], 0);
Expected behavior
It should throw ArgumentException according to documentation
Actual behavior
It throws IndexOutOfRangeException
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
It's a bit of an edge case I think this is probably an oversight and not by design (ie. not incorrect documentation)
Tagging subscribers to this area: @dotnet/area-system-collections See info in area-owners.md if you want to be subscribed.
Issue Details
Description
If BitArray.CopyTo is invoked with:
- destination array being an
int[](does not reproduce withbool[]norbyte[]) - the destination array is too small
- bit count in
BitArrayis not divisible by 32.
Throwing of ArgumentException is delegated to calling of Array.Copy.
Although if the BitArray contains "extra bits", this check is not done for the last extra bits, so IndexOutOfRangeException can be thrown. The check is essentially of-by one under these circumstances.
Reproduction Steps
new BitArray(33).CopyTo(new int[1], 0);
Expected behavior
It should throw ArgumentException according to documentation
Actual behavior
It throws IndexOutOfRangeException
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
It's a bit of an edge case I think this is probably an oversight and not by design (ie. not incorrect documentation)
| Author: | lilinus |
|---|---|
| Assignees: | - |
| Labels: |
|
| Milestone: | - |
What do the CopyTo implementations in other collection types do in this case? I think this should inform whether we update the implementation or correct the documentation.
EDIT most common ICollection<T> implementations that I checked throw ArgumentException in this case so it's clear that this is a bug. I would support fixing this in the implementation.