[BitCollections] sign extend BitArray conversions to integers wider than a word

converting a negative bit array to `Int128` lost the sign above the first
64 bits , so `Int128(truncatingIfNeeded: "1" as BitArray)` gave
18446744073709551615 , not -1 , `Int128(exactly:)` gave nil , and
`Int128(_:)` trapped . a negative value now starts out as all ones , so the
words shifted in keep the sign .

the trap message also named `BitArray` as the type it could not convert
to , it names the integer type now .
This commit is contained in:
HuzaifaChaudary committed 2026-10-30 20:22:20 +05:00
1 parent f96b909e1a
commit ed61a95cc8
2 files changed
+52 -2

No files matched your search

@@ -23,7 +23,9 @@ extension BitArray {
value: T,
isNegative: Bool
) {
var value: T = .zero
// Negative values start out with all bits set, so that they remain sign
// extended in types that are wider than the words we shift in.
var value: T = T.isSigned && self.last == true ? ~.zero : .zero
let isNegative = self._foreachTwosComplementWordDownward(
isSigned: T.isSigned
) { _, word in
@@ -62,7 +64,7 @@ extension BitArray {
package func _convertForced<T: BinaryInteger>(to type: T.Type) -> T {
guard let value = _convertExactly(to: T.self) else {
fatalError("""
BitArray value cannot be converted to \(Self.self) because it is \
BitArray value cannot be converted to \(T.self) because it is \
outside the representable range
""")
}