Swift 6.1 compiler error using UnsafeRawPointer and binary minus operator

I have a strange problem compiling Swift code related to pointer operations and UnsafeRawPointer.

Swift version:

swift-driver version: 1.120.5 Apple Swift version 6.1 (swiftlang-6.1.0.110.21 clang-1700.0.13.3)

Compiling the following demo code fails with the error

Binary operator '-' cannot be applied to operands of type '_' and 'UnsafeRawPointer'`

Ignore the semantics of the following demo code, it's all about the syntax:

struct SomeData {
    let magic: UInt32 = 1
    let totalLength: UInt32 = 2
    let indexEntriesCount: UInt32 = 3
}

var someData = SomeData()

withUnsafePointer(to: &someData) { pointer in
    processRawData(pointer)
}

func processRawData(_ pointer: UnsafePointer<SomeData>) {
    let magicRawPointer = UnsafeRawPointer(pointer)
    let magicValuePointer = magicRawPointer.assumingMemoryBound(to: UInt32.self)
    let totalLengthPointer = UnsafeRawPointer(magicValuePointer.advanced(by: 1))

    let dataLength: UInt32 = 12
    // the following line causes a compiler error
    let distance = Int(dataLength) - (totalLengthPointer - magicRawPointer)
}

The failing line is
let distance = Int(dataLength) - (totalLengthPointer - magicRawPointer)

If you change the code a little, the compilation does succeed:

    let dataLength: Int = 12
    let distance = dataLength - (totalLengthPointer - magicRawPointer)

However, this code will fail as well:

    let dataLength: Int = 12
    let distance = Int(dataLength) - (totalLengthPointer - magicRawPointer)

I'm a little confused. Does anyone have any idea what's going on?
Is this a compiler bug?

Must be a bug. Changing the order of operands also fixes it:

let distance = -(totalLengthPointer - magicRawPointer) + Int(dataLength)
1 Like