[swift-evolution] [swift-dev] Rebinding UnsafePointer makes it mutable

Andrew Trick atrick at apple.com
Mon Sep 19 13:42:44 CDT 2016


> On Sep 19, 2016, at 1:24 AM, Martin R via swift-dev <swift-dev at swift.org> wrote:
> 
> I noticed that both UnsafePointer and UnsafeMutablePointer have the identical method
> 
>    public func withMemoryRebound<T, Result>(to: T.Type, capacity count: Int, _ body: (UnsafeMutablePointer<T>) throws -> Result) rethrows -> Result
> 
> so that rebinding an immutable pointer gives you a _mutable_ pointer. That is different from what
> 
>    Unsafe[Mutable]Pointer<Pointee> {
>      func withMemoryRebound<T>(to: T.Type, capacity count: Int,
>        _ body: (Unsafe[Mutable]Pointer<T>) throws -> ()) rethrows
>    }
> 
> in https://github.com/apple/swift-evolution/blob/master/proposals/0107-unsaferawpointer.md indicates. Perhaps I am misunderstanding something. Shouldn't rebinding an UnsafePointer result in an UnsafePointer again?
> 
> Martin

I think you’re right about that. I didn’t notice the discrepancy until source breaking changes were frozen and was concerned that fixing it would be more restrictive.

Some users may migrate their code to:

constPtr.withMemoryRebound(to: T.self, capacity: 1) {
 takesMutablePointer($0)
}

We probably want them to be more explicit:

constPtr.withMemoryRebound(to: T.self, capacity: 1) {
 takesMutablePointer(UnsafeMutablePointer(mutating: $0))
}

We could possibly justify correcting this in Swift 3 though on these grounds:

- It’s effectively a bug considering that the proposal and implementation are inconsistent.
- There is a correct way write the code that will continue to work before and after fixing the bug.
- A simple fixit will tell them to add the “mutating” label.

If not, it’s something I was already planning to roll into Swift 4.

-Andy



More information about the swift-evolution mailing list