mirror of
https://github.com/metabolist/metatext.git
synced 2024-11-25 09:41:00 +00:00
Simplify bit array
This commit is contained in:
parent
1b49ec2515
commit
59b5f64720
1 changed files with 3 additions and 20 deletions
|
@ -1,7 +1,5 @@
|
||||||
// Copyright © 2020 Metabolist. All rights reserved.
|
// Copyright © 2020 Metabolist. All rights reserved.
|
||||||
|
|
||||||
// Adapted from https://github.com/dduan/BitArray
|
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
struct BitArray {
|
struct BitArray {
|
||||||
|
@ -19,13 +17,13 @@ extension BitArray {
|
||||||
|
|
||||||
subscript(index: Int) -> Bool {
|
subscript(index: Int) -> Bool {
|
||||||
get {
|
get {
|
||||||
let (byteIndex, bitIndex) = Self.byteAndBitIndices(index: index)
|
let (byteIndex, bitIndex) = index.quotientAndRemainder(dividingBy: Self.bitsInByte)
|
||||||
|
|
||||||
return bytes[byteIndex] & Self.mask(bitIndex: bitIndex) > 0
|
return bytes[byteIndex] & Self.mask(bitIndex: bitIndex) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
set {
|
set {
|
||||||
let (byteIndex, bitIndex) = Self.byteAndBitIndices(index: index)
|
let (byteIndex, bitIndex) = index.quotientAndRemainder(dividingBy: Self.bitsInByte)
|
||||||
|
|
||||||
if newValue {
|
if newValue {
|
||||||
bytes[byteIndex] |= Self.mask(bitIndex: bitIndex)
|
bytes[byteIndex] |= Self.mask(bitIndex: bitIndex)
|
||||||
|
@ -51,22 +49,7 @@ extension BitArray: Codable {
|
||||||
private extension BitArray {
|
private extension BitArray {
|
||||||
static let bitsInByte = 8
|
static let bitsInByte = 8
|
||||||
|
|
||||||
static func byteAndBitIndices(index: Int) -> (Int, Int) {
|
|
||||||
index.quotientAndRemainder(dividingBy: bitsInByte)
|
|
||||||
}
|
|
||||||
|
|
||||||
static func mask(bitIndex: Int) -> UInt8 {
|
static func mask(bitIndex: Int) -> UInt8 {
|
||||||
switch bitIndex {
|
UInt8(2 << (bitIndex - 1))
|
||||||
case 0: return 0b00000001
|
|
||||||
case 1: return 0b00000010
|
|
||||||
case 2: return 0b00000100
|
|
||||||
case 3: return 0b00001000
|
|
||||||
case 4: return 0b00010000
|
|
||||||
case 5: return 0b00100000
|
|
||||||
case 6: return 0b01000000
|
|
||||||
case 7: return 0b10000000
|
|
||||||
default:
|
|
||||||
fatalError("Invalid bit index: \(bitIndex)")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue