Skip to content

Commit 1c1a845

Browse files
committed
[stdlib] fix withUnsafe[BufferPointer,Bytes] impls
1 parent 10a0ee2 commit 1c1a845

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
@@ -635,9 +635,10 @@ extension Span where Element: ~Copyable {
635635
public func withUnsafeBufferPointer<E: Error, Result: ~Copyable>(
636636
_ body: (_ buffer: UnsafeBufferPointer<Element>) throws(E) -> Result
637637
) throws(E) -> Result {
638-
guard let pointer = _pointer else {
638+
guard let pointer = _pointer, _count > 0 else {
639639
return try unsafe body(.init(start: nil, count: 0))
640640
}
641+
// manual memory rebinding to avoid recalculating the alignment checks
641642
let binding = Builtin.bindMemory(
642643
pointer._rawValue, count._builtinWordValue, Element.self
643644
)
@@ -667,8 +668,11 @@ extension Span where Element: BitwiseCopyable {
667668
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
668669
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
669670
) throws(E) -> Result {
670-
try unsafe body(
671-
.init(start: _pointer, count: _count * MemoryLayout<Element>.stride)
671+
guard let _pointer, _count > 0 else {
672+
return try unsafe body(.init(start: nil, count: 0))
673+
}
674+
return try unsafe body(
675+
.init(start: _pointer, count: _count &* MemoryLayout<Element>.stride)
672676
)
673677
}
674678
}

0 commit comments

Comments
 (0)