Skip to content

Commit 0c95f90

Browse files
committed
restore debug-mode bounds checking to *BufferPointer.swapAt
1 parent 116de2b commit 0c95f90

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

stdlib/public/core/UnsafeBufferPointer.swift.gyb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,8 @@ extension Unsafe${Mutable}BufferPointer: ${Mutable}Collection, RandomAccessColle
351351
@_inlineable
352352
public func swapAt(_ i: Int, _ j: Int) {
353353
guard i != j else { return }
354+
_debugPrecondition(i >= 0 && j >= 0)
355+
_debugPrecondition(i < endIndex && j < endIndex)
354356
let pi = (_position! + i)
355357
let pj = (_position! + j)
356358
let tmp = pi.move()

stdlib/public/core/UnsafeRawBufferPointer.swift.gyb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,8 @@ extension Unsafe${Mutable}RawBufferPointer: ${Mutable}Collection {
237237
@_inlineable
238238
public func swapAt(_ i: Int, _ j: Int) {
239239
guard i != j else { return }
240+
_debugPrecondition(i >= 0 && j >= 0)
241+
_debugPrecondition(i < endIndex && j < endIndex)
240242
let pi = (_position! + i)
241243
let pj = (_position! + j)
242244
let tmp = pi.load(fromByteOffset: 0, as: UInt8.self)

validation-test/stdlib/UnsafeBufferPointer.swift.gyb

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -831,11 +831,15 @@ UnsafeMutable${'Raw' if IsRaw else ''}BufferPointerTestSuite.test("subscript/set
831831

832832
UnsafeMutable${'Raw' if IsRaw else ''}BufferPointerTestSuite.test("nonmutating-swapAt") {
833833
% if IsRaw:
834-
let buffer = UnsafeMutableRawBufferPointer.allocate(count: 3)
834+
let allocated = UnsafeMutableRawPointer.allocate(bytes: 4, alignedTo: 8)
835+
let buffer = UnsafeMutableRawBufferPointer(start: allocated, count: 3)
836+
allocated.storeBytes(of: UInt8.max, toByteOffset: 3, as: UInt8.self)
835837
% else:
836-
let buffer = UnsafeMutableBufferPointer<Int>.allocate(capacity: 3)
838+
let allocated = UnsafeMutablePointer<Int>.allocate(capacity: 4)
839+
let buffer = UnsafeMutableBufferPointer(start: allocated, count: 3)
840+
allocated[3] = Int.max
837841
% end
838-
defer { buffer.deallocate() }
842+
defer { allocated.deallocate() }
839843

840844
buffer[0] = 0
841845
buffer[1] = 1
@@ -846,6 +850,11 @@ UnsafeMutable${'Raw' if IsRaw else ''}BufferPointerTestSuite.test("nonmutating-s
846850

847851
buffer.swapAt(0, 2)
848852
expectEqual(Array(buffer), [2, 1, 0])
853+
854+
if _isDebugAssertConfiguration() {
855+
expectCrashLater()
856+
}
857+
buffer.swapAt(2, 3)
849858
}
850859

851860
% if not IsRaw:

0 commit comments

Comments
 (0)