swift-mmio icon indicating copy to clipboard operation
swift-mmio copied to clipboard

Dynamic arrays are used in FixedWidthInteger.bitRangesCoalesced

Open kubamracek opened this issue 4 months ago • 3 comments

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
  }

kubamracek avatar Oct 03 '24 20:10 kubamracek