Skip to content

Commit c248326

Browse files
committed
[stdlib] add U[M]RBP.assumingMemoryBound
1 parent 5403129 commit c248326

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

stdlib/public/core/UnsafeRawBufferPointer.swift.gyb

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -784,6 +784,37 @@ extension Unsafe${Mutable}RawBufferPointer {
784784
defer { Builtin.rebindMemory(s._rawValue, binding) }
785785
return try body(.init(start: .init(s._rawValue), count: n))
786786
}
787+
788+
/// Returns a typed buffer to the memory referenced by this buffer,
789+
/// assuming that the memory is already bound to the specified type.
790+
///
791+
/// Use this method when you have a raw buffer to memory that has *already*
792+
/// been bound to the specified type. The memory starting at this pointer
793+
/// must be bound to the type `T`. Accessing memory through the returned
794+
/// pointer is undefined if the memory has not been bound to `T`. To bind
795+
/// memory to `T`, use `bindMemory(to:capacity:)` instead of this method.
796+
///
797+
/// - Note: The buffer's base address must match the
798+
/// alignment of `T` (as reported by `MemoryLayout<T>.alignment`).
799+
/// That is, `Int(bitPattern: self.baseAddress) % MemoryLayout<T>.alignment`
800+
/// must equal zero.
801+
///
802+
/// - Parameter to: The type `T` that the memory has already been bound to.
803+
/// - Returns: A typed pointer to the same memory as this raw pointer.
804+
@inlinable
805+
@_alwaysEmitIntoClient
806+
public func assumingMemoryBound<T>(
807+
to: T.Type
808+
) -> Unsafe${Mutable}BufferPointer<T> {
809+
guard let s = _position else {
810+
return .init(start: nil, count: 0)
811+
}
812+
// initializer ensures _end is nil only when _position is nil.
813+
_internalInvariant(_end != nil)
814+
let c = _assumeNonNegative(s.distance(to: _end._unsafelyUnwrappedUnchecked))
815+
let n = c / MemoryLayout<T>.stride
816+
return .init(start: .init(s._rawValue), count: n)
817+
}
787818
}
788819

789820
extension Unsafe${Mutable}RawBufferPointer: CustomDebugStringConvertible {

0 commit comments

Comments
 (0)