Skip to content

Commit

Permalink
Fix BitArray.CopyTo (dotnet#98846)
Browse files Browse the repository at this point in the history
* Fix BitArray.CopyTo

* Revert refactors in fix BitArray.CopyTo

* Post merge fix
  • Loading branch information
lilinus authored Feb 28, 2024
1 parent 3dc3d85 commit d7d3c6b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -761,21 +761,14 @@ public unsafe void CopyTo(Array array, int index)
throw new ArgumentException(SR.Argument_InvalidOffLen);
}

Div32Rem(m_length, out int extraBits);
int quotient = Div32Rem(m_length, out int extraBits);

if (extraBits == 0)
{
// we have perfect bit alignment, no need to sanitize, just copy
Array.Copy(m_array, 0, intArray, index, m_array.Length);
}
else
{
int last = (m_length - 1) >> BitShiftPerInt32;
// do not copy the last int, as it is not completely used
Array.Copy(m_array, 0, intArray, index, last);
Array.Copy(m_array, 0, intArray, index, quotient);

if (extraBits > 0)
{
// the last int needs to be masked
intArray[index + last] = m_array[last] & unchecked((1 << extraBits) - 1);
intArray[index + quotient] = m_array[quotient] & unchecked((1 << extraBits) - 1);
}
}
else if (array is byte[] byteArray)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,18 @@ public static void CopyToIntArray()
}
}

// https://github.com/dotnet/runtime/issues/98813
[Fact]
public static void CopyToIntArray_Regression98813()
{
BitArray bitArray = new BitArray(256);
bitArray.Length = 32;
int[] expectedOutput = new int[] { 0 };
int[] actualOutput = new int[1];
bitArray.CopyTo(actualOutput, 0);
Assert.Equal(expectedOutput, actualOutput);
}

// https://github.com/dotnet/runtime/issues/30440
[Fact]
public static void CopyToByteArray_Regression39929()
Expand Down

0 comments on commit d7d3c6b

Please sign in to comment.