Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created September 18, 2018 18:06
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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