Skip to content

[stdlib] Stop swapping self in Array.withUnsafeMutableBufferPointer #38867

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 16, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 1 addition & 16 deletions stdlib/public/core/Array.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1604,31 +1604,16 @@ extension Array {
_makeMutableAndUnique()
let count = _buffer.mutableCount

// Ensure that body can't invalidate the storage or its bounds by
// moving self into a temporary working array.
// NOTE: The stack promotion optimization that keys of the
// "array.withUnsafeMutableBufferPointer" semantics annotation relies on the
// array buffer not being able to escape in the closure. It can do this
// because we swap the array buffer in self with an empty buffer here. Any
// escape via the address of self in the closure will therefore escape the
// empty array.

var work = Array()
(work, self) = (self, work)

// Create an UnsafeBufferPointer over work that we can pass to body
let pointer = work._buffer.mutableFirstElementAddress
let pointer = _buffer.mutableFirstElementAddress
var inoutBufferPointer = UnsafeMutableBufferPointer(
start: pointer, count: count)

// Put the working array back before returning.
defer {
_precondition(
inoutBufferPointer.baseAddress == pointer &&
inoutBufferPointer.count == count,
"Array withUnsafeMutableBufferPointer: replacing the buffer is not allowed")

(work, self) = (self, work)
_endMutation()
}

Expand Down