Skip to content

Commit d7d3c6b

Browse files
authored
Fix BitArray.CopyTo (#98846)
* Fix BitArray.CopyTo * Revert refactors in fix BitArray.CopyTo * Post merge fix
1 parent 3dc3d85 commit d7d3c6b

File tree

2 files changed

+17
-12
lines changed

2 files changed

+17
-12
lines changed

src/libraries/System.Collections/src/System/Collections/BitArray.cs

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -761,21 +761,14 @@ public unsafe void CopyTo(Array array, int index)
761761
throw new ArgumentException(SR.Argument_InvalidOffLen);
762762
}
763763

764-
Div32Rem(m_length, out int extraBits);
764+
int quotient = Div32Rem(m_length, out int extraBits);
765765

766-
if (extraBits == 0)
767-
{
768-
// we have perfect bit alignment, no need to sanitize, just copy
769-
Array.Copy(m_array, 0, intArray, index, m_array.Length);
770-
}
771-
else
772-
{
773-
int last = (m_length - 1) >> BitShiftPerInt32;
774-
// do not copy the last int, as it is not completely used
775-
Array.Copy(m_array, 0, intArray, index, last);
766+
Array.Copy(m_array, 0, intArray, index, quotient);
776767

768+
if (extraBits > 0)
769+
{
777770
// the last int needs to be masked
778-
intArray[index + last] = m_array[last] & unchecked((1 << extraBits) - 1);
771+
intArray[index + quotient] = m_array[quotient] & unchecked((1 << extraBits) - 1);
779772
}
780773
}
781774
else if (array is byte[] byteArray)

src/libraries/System.Collections/tests/BitArray/BitArray_GetSetTests.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,18 @@ public static void CopyToIntArray()
396396
}
397397
}
398398

399+
// https://github.com/dotnet/runtime/issues/98813
400+
[Fact]
401+
public static void CopyToIntArray_Regression98813()
402+
{
403+
BitArray bitArray = new BitArray(256);
404+
bitArray.Length = 32;
405+
int[] expectedOutput = new int[] { 0 };
406+
int[] actualOutput = new int[1];
407+
bitArray.CopyTo(actualOutput, 0);
408+
Assert.Equal(expectedOutput, actualOutput);
409+
}
410+
399411
// https://github.com/dotnet/runtime/issues/30440
400412
[Fact]
401413
public static void CopyToByteArray_Regression39929()

0 commit comments

Comments
 (0)