swift-mmio
swift-mmio copied to clipboard
Dynamic arrays are used in FixedWidthInteger.bitRangesCoalesced
Dynamic arrays are used in FixedWidthInteger.bitRangesCoalesced. Swift MMIO should really be allocations free. This was identified while investigating https://forums.swift.org/t/building-swift-mmio-for-stm32c011-with-no-allocations-results-in-compilation-error/75124.
extension FixedWidthInteger {
@inlinable @inline(__always)
static func bitRangesCoalesced(bits bitRanges: [Range<Int>]) -> Bool { // << receives an arrays
let bitRanges = bitRanges.sorted { $0.lowerBound < $1.lowerBound } // << sorting is not constant-foldable
var lowerBound = -1
for bitRange in bitRanges {
// Specifically ensure that the bit ranges dont overlap, e.g. the
// following ranges are not valid: 0..<1, 0..<2. This is to ensure ranges
// are coalesced before iterating reduce the number of mask and shift
// operations needed.
guard lowerBound <= bitRange.lowerBound else { return false }
lowerBound = bitRange.upperBound
}
return true
}