Skip to content

Commit 441e3ce

Browse files
committed
[stdlib] add withContiguousStorageIfAvailable for raw buffers
1 parent 36076e2 commit 441e3ce

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

stdlib/public/core/UnsafeRawBufferPointer.swift.gyb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -830,6 +830,35 @@ extension Unsafe${Mutable}RawBufferPointer {
830830
let n = c / MemoryLayout<T>.stride
831831
return .init(start: .init(s._rawValue), count: n)
832832
}
833+
834+
% if Mutable:
835+
@inlinable
836+
@_alwaysEmitIntoClient
837+
public func withContiguousMutableStorageIfAvailable<R>(
838+
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
839+
) rethrows -> R? {
840+
try withMemoryRebound(to: Element.self) { b in
841+
var buffer = b
842+
defer {
843+
_debugPrecondition(
844+
(b.baseAddress, b.count) == (buffer.baseAddress, buffer.count),
845+
"UnsafeMutableRawBufferPointer.withContiguousMutableStorageIfAvailable: replacing the buffer is not allowed"
846+
)
847+
}
848+
return try body(&buffer)
849+
}
850+
}
851+
852+
% end
853+
@inlinable
854+
@_alwaysEmitIntoClient
855+
public func withContiguousStorageIfAvailable<R>(
856+
_ body: (UnsafeBufferPointer<Element>) throws -> R
857+
) rethrows -> R? {
858+
try withMemoryRebound(to: Element.self) {
859+
try body(${ 'UnsafeBufferPointer<Element>($0)' if Mutable else '$0' })
860+
}
861+
}
833862
}
834863

835864
extension Unsafe${Mutable}RawBufferPointer: CustomDebugStringConvertible {

0 commit comments

Comments
 (0)