Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created September 18, 2018 18:06
Show Gist options
  • Save natecook1000/552dc3d23d2fc4a54d2e9fcd309e59e9 to your computer and use it in GitHub Desktop.
Save natecook1000/552dc3d23d2fc4a54d2e9fcd309e59e9 to your computer and use it in GitHub Desktop.
struct BitArray: RandomAccessCollection, MutableCollection {
typealias Data = (UInt, UInt)
var data: Data = (0, 0)
var startIndex: Int {
return 0
}
var endIndex: Int {
return MemoryLayout<Data>.size * 8
}
subscript(_ i: Int) -> Bool {
get {
return withUnsafeBytes(of: data) { buffer in
return (buffer[i / 8] >> (i % 8)) & 1 == 1
}
}
set {
withUnsafeMutableBytes(of: &data) { buffer in
let v = (1 as UInt8) << (i % 8)
if newValue {
buffer[i / 8] |= v
} else {
buffer[i / 8] &= ~v
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment