[swift-users] How much memory does withMemoryRebound bind

Andrew Trick atrick at apple.com
Wed Jan 4 16:48:06 CST 2017


> On Dec 29, 2016, at 2:03 PM, Guillaume Lessard via swift-users <swift-users at swift.org> wrote:
> 
> Hi Etan,
> 
> `withMemoryRebound` does not copy memory.
> The proposal for UnsafeRawPointer contains information about the memory model (as related to pointers):
> https://github.com/apple/swift-evolution/blob/master/proposals/0107-unsaferawpointer.md
> 
> (also, the method is defined in the following file:
> https://github.com/apple/swift/blob/master/stdlib/public/core/UnsafePointer.swift.gyb)
> 
> The capacity parameter of withMemoryRebound allows rebinding a contiguous buffer at once; it might be nice if it had a default value of 1.
> 
> Cheers,
> Guillaume Lessard

Yep. To further reassure you, `withMemoryRebound` could not be implemented as a copy without breaking various semantics.

Specifically, `forwardPointer` below is semantically equivalent to calling `f` directly.

func forwardPointer(_ p: UnsafePointer<Int64>, to f: (UnsafePointer<Int64>) -> ()) {
  p.withMemoryRebound(to: Int32.self, capacity: 1) {
    $0.withMemoryRebound(to: Int64.self, capacity: 1) {
      f($0)
    }
  }
}

[For an instant, the high bytes are initialized to untyped raw bits. The documentation skirts around this case, but the model is consistent and verifiable.]

The `capacity` label serves to distinguish this cast from the familiar C pointer cast where it’s customary to dereference multiple elements from the resulting typed pointer without specifying the array size. A default capacity=1 would be convenient but misleading.

-Andy


More information about the swift-users mailing list