Instantly share code, notes, and snippets.

Embed
What would you like to do?
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