From 0a3dcfd3a8be74eb04e6b3ea58dbe163dba7a186 Mon Sep 17 00:00:00 2001 From: Aditya Singh Date: Sun, 24 May 2026 18:22:45 -0700 Subject: [PATCH] [InternalCollectionsUtilities] Fix _trim returning the wrong buffer region The `_trim(first:)` and `_trim(last:)` helpers reassign `self` to the remaining slice and then build the trimmed result from `self`'s now-updated `baseAddress`/`count`, so they hand back a region that points into the wrong place in the buffer. `UnsafeMutableBufferPointer._trim(first:)` had this exact bug fixed earlier (it captures `oldStart` before the reassignment), but three sibling helpers were left untouched: * `UnsafeBufferPointer._trim(first:)` reads `baseAddress` after advancing `self`, so the returned prefix starts at the remainder instead of at the original head. * `UnsafeBufferPointer._trim(last:)` and `UnsafeMutableBufferPointer._trim(last:)` recompute `count &- cut` after shrinking `self`, so the returned suffix starts `cut` elements too early. For a five-element buffer, `_trim(first: 2)` returned the bytes of `[30, 40]` rather than `[10, 20]`, and `_trim(last: 2)` returned `[20, 30]` rather than `[40, 50]`; trimming more than the count walked off the end of the buffer. Capture the original start (and, for the suffix case, the post-trim count) before mutating `self`, matching the already-correct `_trim(first:)` on the mutable buffer. Adds direct tests covering both overloads on both buffer types. --- .../UnsafeBufferPointer+Extras.swift | 8 +- .../UnsafeMutableBufferPointer+Extras.swift | 6 +- Tests/DequeTests/UnsafeBufferTrimTests.swift | 110 ++++++++++++++++++ 3 files changed, 119 insertions(+), 5 deletions(-) create mode 100644 Tests/DequeTests/UnsafeBufferTrimTests.swift diff --git a/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift index 0db4d879..c9c49bb6 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift @@ -146,7 +146,7 @@ extension UnsafeBufferPointer where Element: ~Copyable { guard cut > 0 else { return .init(start: nil, count: 0) } let oldStart = baseAddress.unsafelyUnwrapped self = Self(start: oldStart + cut, count: count - cut) - return Self(start: baseAddress, count: cut) + return Self(start: oldStart, count: cut) } @_alwaysEmitIntoClient @@ -154,7 +154,9 @@ extension UnsafeBufferPointer where Element: ~Copyable { precondition(maxLength >= 0, "Cannot have a suffix of negative length") let cut = Swift.min(maxLength, count) guard cut > 0 else { return .init(start: nil, count: 0) } - self = .init(start: baseAddress, count: count &- cut) - return Self(start: baseAddress.unsafelyUnwrapped + (count &- cut), count: cut) + let oldStart = baseAddress.unsafelyUnwrapped + let newCount = count &- cut + self = .init(start: oldStart, count: newCount) + return Self(start: oldStart + newCount, count: cut) } } diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift index b9d1e0f2..65b6cb44 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift @@ -167,8 +167,10 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { precondition(maxLength >= 0, "Cannot have a suffix of negative length") let cut = Swift.min(maxLength, count) guard cut > 0 else { return .init(start: nil, count: 0) } - self = .init(start: baseAddress, count: count &- cut) - return Self(start: baseAddress.unsafelyUnwrapped + (count &- cut), count: cut) + let oldStart = baseAddress.unsafelyUnwrapped + let newCount = count &- cut + self = .init(start: oldStart, count: newCount) + return Self(start: oldStart + newCount, count: cut) } } diff --git a/Tests/DequeTests/UnsafeBufferTrimTests.swift b/Tests/DequeTests/UnsafeBufferTrimTests.swift new file mode 100644 index 00000000..4a985d46 --- /dev/null +++ b/Tests/DequeTests/UnsafeBufferTrimTests.swift @@ -0,0 +1,110 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +import XCTest +#if COLLECTIONS_SINGLE_MODULE +@_spi(Testing) import Collections +#else +import _CollectionsTestSupport +import InternalCollectionsUtilities +#endif + +/// Tests for the `_trim(first:)` and `_trim(last:)` helpers on the unsafe +/// buffer pointer types in `InternalCollectionsUtilities`. These are used by +/// the deque consumption/segment machinery, so a wrong result here corrupts +/// the spans that get handed out to clients. +final class UnsafeBufferTrimTests: CollectionTestCase { + func test_mutableBuffer_trimFirst() { + let values = [10, 20, 30, 40, 50] + values.withUnsafeBufferPointer { source in + let storage = UnsafeMutableBufferPointer.allocate(capacity: source.count) + defer { storage.deallocate() } + _ = storage.initialize(fromContentsOf: source) + defer { storage.deinitialize() } + + var rest = storage + let head = rest._trim(first: 2) + expectEqual(Array(head), [10, 20]) + expectEqual(Array(rest), [30, 40, 50]) + + // Trimming more than the count yields everything. + var all = storage + let everything = all._trim(first: 99) + expectEqual(Array(everything), [10, 20, 30, 40, 50]) + expectEqual(all.count, 0) + } + } + + func test_mutableBuffer_trimLast() { + let values = [10, 20, 30, 40, 50] + values.withUnsafeBufferPointer { source in + let storage = UnsafeMutableBufferPointer.allocate(capacity: source.count) + defer { storage.deallocate() } + _ = storage.initialize(fromContentsOf: source) + defer { storage.deinitialize() } + + var rest = storage + let tail = rest._trim(last: 2) + expectEqual(Array(tail), [40, 50]) + expectEqual(Array(rest), [10, 20, 30]) + + var all = storage + let everything = all._trim(last: 99) + expectEqual(Array(everything), [10, 20, 30, 40, 50]) + expectEqual(all.count, 0) + } + } + + func test_immutableBuffer_trimFirst() { + let values = [10, 20, 30, 40, 50] + values.withUnsafeBufferPointer { source in + var rest = source + let head = rest._trim(first: 2) + expectEqual(Array(head), [10, 20]) + expectEqual(Array(rest), [30, 40, 50]) + + var all = source + let everything = all._trim(first: 99) + expectEqual(Array(everything), [10, 20, 30, 40, 50]) + expectEqual(all.count, 0) + } + } + + func test_immutableBuffer_trimLast() { + let values = [10, 20, 30, 40, 50] + values.withUnsafeBufferPointer { source in + var rest = source + let tail = rest._trim(last: 2) + expectEqual(Array(tail), [40, 50]) + expectEqual(Array(rest), [10, 20, 30]) + + var all = source + let everything = all._trim(last: 99) + expectEqual(Array(everything), [10, 20, 30, 40, 50]) + expectEqual(all.count, 0) + } + } + + func test_trim_zeroIsNoOp() { + let values = [1, 2, 3] + values.withUnsafeBufferPointer { source in + var a = source + expectEqual(a._trim(first: 0).count, 0) + expectEqual(Array(a), [1, 2, 3]) + + var b = source + expectEqual(b._trim(last: 0).count, 0) + expectEqual(Array(b), [1, 2, 3]) + } + } +}