Refactoring

This commit is contained in:
Justin Mazzocchi 2020-09-26 15:56:24 -07:00
parent 3f0f19a75b
commit 718dfccf7d
No known key found for this signature in database
GPG key ID: E223E6937AAFB01C

View file

@ -17,18 +17,18 @@ extension BitArray {
subscript(index: Int) -> Bool { subscript(index: Int) -> Bool {
get { get {
let (byteIndex, bitIndex) = index.quotientAndRemainder(dividingBy: UInt8.bitWidth) let (byteIndex, mask) = Self.byteIndexAndMask(index: index)
return bytes[byteIndex] & Self.mask(bitIndex: bitIndex) > 0 return bytes[byteIndex] & mask > 0
} }
set { set {
let (byteIndex, bitIndex) = index.quotientAndRemainder(dividingBy: UInt8.bitWidth) let (byteIndex, mask) = Self.byteIndexAndMask(index: index)
if newValue { if newValue {
bytes[byteIndex] |= Self.mask(bitIndex: bitIndex) bytes[byteIndex] |= mask
} else { } else {
bytes[byteIndex] &= ~Self.mask(bitIndex: bitIndex) bytes[byteIndex] &= ~mask
} }
} }
} }
@ -47,7 +47,10 @@ extension BitArray: Codable {
} }
private extension BitArray { private extension BitArray {
static func mask(bitIndex: Int) -> UInt8 { static func byteIndexAndMask(index: Int) -> (Int, UInt8) {
UInt8(2 << (bitIndex - 1)) let (byteIndex, bitIndex) = index.quotientAndRemainder(dividingBy: UInt8.bitWidth)
let mask = UInt8(2 << (bitIndex - 1))
return (byteIndex, mask)
} }
} }