withMemoryRebound(to:_:)
Executes the given closure while temporarily binding the memory referenced by this buffer to the given type.
func withMemoryRebound<T, Result>(to type: T.Type, _ body: (UnsafeBufferPointer<T>) throws -> Result) rethrows -> Result
Parameters
- type
The type to temporarily bind the memory referenced by this buffer. The type
T
must be layout compatible with the pointer’sElement
type.- body
A closure that takes a typed buffer to the same memory as this buffer, only bound to type
T
. The buffer parameter contains a number of complete instances ofT
based on the capacity of the original buffer and the stride ofElement
. The closure’s buffer argument is valid only for the duration of the closure’s execution. Ifbody
has a return value, that value is also used as the return value for thewithMemoryRebound(to:_:)
method.- buffer
The buffer temporarily bound to
T
.
Returns
The return value, if any, of the body
closure parameter.
Overview
Use this method when you have a buffer of memory bound to one type and you need to access that memory as a buffer of another type. Accessing memory as type T
requires that the memory be bound to that type. A memory location may only be bound to one type at a time, so accessing the same memory as an unrelated type without first rebinding the memory is undefined.
The number of instances of T
referenced by the rebound buffer may be different than the number of instances of Element
referenced by the original buffer. The number of instances of T
will be calculated at runtime.
Any instance of T
within the re-bound region may be initialized or uninitialized. Every instance of Pointee
overlapping with a given instance of T
should have the same initialization state (i.e. initialized or uninitialized.) Accessing a T
whose underlying Pointee
storage is in a mixed initialization state shall be undefined behaviour.
Because this buffer’s memory is no longer bound to its Element
type while the body
closure executes, do not access memory using the original buffer from within body
. Instead, use the body
closure’s buffer argument to access the values in memory as instances of type T
.
After executing body
, this method rebinds memory back to the original Element
type.