Created
July 11, 2017 15:50
-
-
Save sharplet/d95d665cfd5e1105262e3cae1d0aeb70 to your computer and use it in GitHub Desktop.
Playing around with a high-level API for working with bit masks
This file contains hidden or 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 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