Skip to content

Commit 3935f00

Browse files
committed
[stdlib] fix withUnsafe[BufferPointer,Bytes] impls
1 parent bd84291 commit 3935f00

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

stdlib/public/core/Span/RawSpan.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,10 @@ extension RawSpan {
469469
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
470470
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
471471
) throws(E) -> Result {
472-
try unsafe body(.init(start: _pointer, count: byteCount))
472+
guard let _pointer, byteCount > 0 else {
473+
return try unsafe body(.init(start: nil, count: 0))
474+
}
475+
return try unsafe body(.init(start: _pointer, count: byteCount))
473476
}
474477
}
475478

stdlib/public/core/Span/Span.swift

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -622,9 +622,10 @@ extension Span where Element: ~Copyable {
622622
public func withUnsafeBufferPointer<E: Error, Result: ~Copyable>(
623623
_ body: (_ buffer: UnsafeBufferPointer<Element>) throws(E) -> Result
624624
) throws(E) -> Result {
625-
guard let pointer = _pointer else {
625+
guard let pointer = _pointer, _count > 0 else {
626626
return try unsafe body(.init(start: nil, count: 0))
627627
}
628+
// manual memory rebinding to avoid recalculating the alignment checks
628629
let binding = Builtin.bindMemory(
629630
pointer._rawValue, count._builtinWordValue, Element.self
630631
)
@@ -654,8 +655,11 @@ extension Span where Element: BitwiseCopyable {
654655
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
655656
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
656657
) throws(E) -> Result {
657-
try unsafe body(
658-
.init(start: _pointer, count: _count * MemoryLayout<Element>.stride)
658+
guard let _pointer, _count > 0 else {
659+
return try unsafe body(.init(start: nil, count: 0))
660+
}
661+
return try unsafe body(
662+
.init(start: _pointer, count: _count &* MemoryLayout<Element>.stride)
659663
)
660664
}
661665
}

0 commit comments

Comments
 (0)