Skip to content

Commit 4ea4db0

Browse files
committed
Add preconditions for bitsCount in bit writers to be within int bit width
1 parent 2896287 commit 4ea4db0

3 files changed

Lines changed: 5 additions & 2 deletions

File tree

Sources/BitWriter.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ extension BitWriter {
5252
}
5353

5454
public func write(number: Int, bitsCount: Int) {
55+
precondition(0...Int.bitWidth ~= bitsCount)
5556
self.write(unsignedNumber: UInt(bitPattern: number), bitsCount: bitsCount)
5657
}
5758

Sources/LsbBitWriter.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ public final class LsbBitWriter: BitWriter {
5050
thus, crashes when converting to an `Int` if `write(number:bitsCount:)` method is used.
5151
*/
5252
public func write(unsignedNumber: UInt, bitsCount: Int) {
53-
var mask: UInt = 1
53+
precondition(0...UInt.bitWidth ~= bitsCount)
54+
var mask = 1 as UInt
5455
for _ in 0..<bitsCount {
5556
self.write(bit: unsignedNumber & mask > 0 ? 1 : 0)
5657
mask <<= 1

Sources/MsbBitWriter.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ public final class MsbBitWriter: BitWriter {
5050
thus, crashes when converting to an `Int` if `write(number:bitsCount:)` method is used.
5151
*/
5252
public func write(unsignedNumber: UInt, bitsCount: Int) {
53-
var mask: UInt = 1 << (UInt(truncatingIfNeeded: bitsCount) - 1)
53+
precondition(0...UInt.bitWidth ~= bitsCount)
54+
var mask = (1 as UInt) << (bitsCount - 1)
5455
for _ in 0..<bitsCount {
5556
self.write(bit: unsignedNumber & mask > 0 ? 1 : 0)
5657
mask >>= 1

0 commit comments

Comments
 (0)