Created
March 24, 2018 18:50
-
-
Save dabrahams/f05e1eda6a2939577e609fd3a21387e4 to your computer and use it in GitHub Desktop.
A mutable collection adapter that projects out each bit of the underlying integers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct BitArray<Base : RandomAccessCollection & MutableCollection> | |
: RandomAccessCollection & MutableCollection | |
where Base.Element : FixedWidthInteger | |
{ | |
fileprivate var base: Base | |
private var bitWidth: Int { return Base.Element.bitWidth } | |
var startIndex: Int { return 0 } | |
var endIndex: Int { return Base.Element.bitWidth * base.count } | |
subscript(i: Int) -> Bool { | |
get { | |
let j = base.index(base.startIndex, offsetBy: i / bitWidth) | |
let k: Base.Element = 0x1 &<< (i % bitWidth) | |
return base[j] & k != 0 | |
} | |
set { | |
let j = base.index(base.startIndex, offsetBy: i / bitWidth) | |
let k: Base.Element = 0x1 &<< (i % bitWidth) | |
base[j] = newValue ? base[j] | k : base[j] & ~k | |
} | |
} | |
} | |
extension RandomAccessCollection | |
where Self : MutableCollection, Element : FixedWidthInteger { | |
var bits: BitArray<Self> { | |
get { | |
return BitArray(base: self) | |
} | |
set { | |
self = newValue.base | |
} | |
} | |
} | |
func testMe(_ a: inout [Int]) { | |
a[0..<1].bits[3] = true | |
} | |
var a = [0, 0] | |
// Test the identity of the underlying buffer | |
print(unsafeBitCast(a, to: Int.self)) | |
testMe(&a) | |
print(a) | |
// Prove that we didn't have to copy a to a whole new collection | |
print(unsafeBitCast(a, to: Int.self)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment