Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Playing around with a high-level API for working with bit masks
struct BitMask<T: FixedWidthInteger>: RandomAccessCollection {
typealias SubSequence = BitMask<T>
var rawValue: T {
var rawValue: T = 0
for bit in self {
rawValue |= bit
}
return rawValue
}
private(set) var startIndex = 0
private(set) var endIndex = T().bitWidth
subscript(i: Int) -> T {
return 1 << i
}
subscript<R: RangeExpression>(range: R) -> BitMask<T> where R.Bound == Int {
let range = range.relative(to: self)
var mask = self
mask.startIndex = range.lowerBound
mask.endIndex = range.upperBound
return mask
}
}
extension FixedWidthInteger {
static var bitMask: BitMask<Self> {
return BitMask()
}
subscript<R: RangeExpression>(bitMask range: R) -> Self where R.Bound == BitMask<Self>.Index {
let mask = Self.bitMask[range]
return self[bitMask: mask]
}
subscript(bitMask mask: BitMask<Self>) -> Self {
return self & mask.rawValue >> mask.startIndex
}
}
UInt8.max[bitMask: ..<6] // 0b0011_1111 = 63
UInt8.max[bitMask: 6...] // 0b1100_0000 = 192
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.