Skip to content

Commit c6943e1

Browse files
committed
[stdlib] add UMBP.mutableSpan accessor
1 parent 70932ae commit c6943e1

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

stdlib/public/core/UnsafeBufferPointer.swift.gyb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,18 @@ extension Unsafe${Mutable}BufferPointer where Element: ~Copyable {
583583
return unsafe _overrideLifetime(span, borrowing: self)
584584
}
585585
}
586+
%if Mutable:
587+
588+
@unsafe
589+
@available(SwiftStdlib 6.2, *)
590+
public var mutableSpan: MutableSpan<Element> {
591+
@lifetime(borrow self)
592+
@_alwaysEmitIntoClient
593+
get {
594+
unsafe MutableSpan(_unsafeElements: self)
595+
}
596+
}
597+
%end
586598
}
587599

588600
extension Unsafe${Mutable}BufferPointer {

test/stdlib/Span/MutableSpanTests.swift

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -720,3 +720,25 @@ suite.test("extracting suffixes")
720720
expectEqual(span.extracting(droppingFirst: 1).count, b.count)
721721
}
722722
}
723+
724+
suite.test("MutableSpan from UnsafeMutableBufferPointer")
725+
.require(.stdlib_6_2).code {
726+
guard #available(SwiftStdlib 6.2, *) else { return }
727+
728+
let capacity = 4
729+
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: capacity)
730+
defer {
731+
b.deallocate()
732+
}
733+
_ = b.initialize(fromContentsOf: 0..<capacity)
734+
735+
var span = b.mutableSpan
736+
expectEqual(span.count, capacity)
737+
738+
span.swapAt(0, 3)
739+
span.swapAt(1, 2)
740+
741+
_ = consume span
742+
743+
expectTrue(b.elementsEqual((0..<capacity).reversed()))
744+
}

0 commit comments

Comments
 (0)