Flesh out RigidArray even more; add complete test coverage

This commit is contained in:
Karoy Lorentey committed 2025-04-28 21:55:28 -07:00
1 parent 75837a7717
commit 3fffe2ad20
11 files changed
+584 -143

No files matched your search

+2
View File
@@ -9,7 +9,9 @@
//
//===----------------------------------------------------------------------===//
#if !COLLECTIONS_SINGLE_MODULE
import Future
#endif
/// A collection implementing a double-ended queue. `Deque` (pronounced "deck")
/// implements an ordered random-access collection that supports efficient
+4 -4
View File
@@ -95,7 +95,7 @@ extension NewArray {
if _storage.isUnique() {
_storage.value.reserveCapacity(n)
} else {
_storage.replace { $0._copy(capacity: Swift.max($0.capacity, n)) }
_storage.replace { $0.copy(capacity: Swift.max($0.capacity, n)) }
}
}
@@ -113,7 +113,7 @@ extension NewArray {
@inlinable
internal mutating func _ensureUnique() {
_storage.ensureUnique { $0._copy() }
_storage.ensureUnique { $0.copy() }
}
@inlinable
@@ -127,8 +127,8 @@ extension NewArray {
}
let c = Swift.max(minimumCapacity, Self._grow(capacity))
_storage.edit(
shared: { $0._copy(capacity: c) },
unique: { $0 = $0._move(capacity: c) }
shared: { $0.copy(capacity: c) },
unique: { $0.reserveCapacity(c) }
)
}
+199 -76
View File
@@ -9,6 +9,10 @@
//
//===----------------------------------------------------------------------===//
#if !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
/// A manually resizable, heap allocated, noncopyable array of
/// potentially noncopyable elements.
@safe
@@ -35,7 +39,12 @@ public struct RigidArray<Element: ~Copyable>: ~Copyable {
}
_count = 0
}
}
extension RigidArray: @unchecked Sendable where Element: Sendable & ~Copyable {}
//MARK: - Initializers
extension RigidArray where Element: ~Copyable {
@inlinable
public init(count: Int, initializedWith generator: (Int) -> Element) {
unsafe _storage = .allocate(capacity: count)
@@ -46,8 +55,6 @@ public struct RigidArray<Element: ~Copyable>: ~Copyable {
}
}
extension RigidArray: @unchecked Sendable where Element: Sendable & ~Copyable {}
extension RigidArray /*where Element: Copyable*/ {
/// Creates a new array containing the specified number of a single,
/// repeated value.
@@ -63,6 +70,39 @@ extension RigidArray /*where Element: Copyable*/ {
}
}
extension RigidArray /*where Element: Copyable*/ {
@_alwaysEmitIntoClient
@inline(__always)
public init(capacity: Int? = nil, copying contents: some Collection<Element>) {
self.init(capacity: capacity ?? contents.count)
self.append(contentsOf: contents)
}
@available(SwiftCompatibilitySpan 5.0, *)
@_alwaysEmitIntoClient
@inline(__always)
public init<C: Container<Element> & ~Copyable & ~Escapable>(
capacity: Int? = nil,
copying contents: borrowing C
) {
self.init(capacity: capacity ?? contents.count)
self.append(copying: contents)
}
@available(SwiftCompatibilitySpan 5.0, *)
@_alwaysEmitIntoClient
@inline(__always)
public init<C: Container<Element> & Collection<Element>>(
capacity: Int? = nil,
copying contents: C
) {
self.init(capacity: capacity ?? contents.count)
self.append(copying: contents)
}
}
//MARK: - Basics
extension RigidArray where Element: ~Copyable {
@inlinable
@inline(__always)
@@ -235,8 +275,8 @@ extension RigidArray where Element: ~Copyable {
extension RigidArray where Element: ~Copyable {
@inlinable
public mutating func resize(to newCapacity: Int) {
precondition(newCapacity >= count)
public mutating func setCapacity(_ newCapacity: Int) {
precondition(newCapacity >= count, "RigidArray capacity overflow")
guard newCapacity != capacity else { return }
let newStorage: UnsafeMutableBufferPointer<Element> = .allocate(capacity: newCapacity)
let i = unsafe newStorage.moveInitialize(fromContentsOf: self._items)
@@ -248,10 +288,30 @@ extension RigidArray where Element: ~Copyable {
@inlinable
public mutating func reserveCapacity(_ n: Int) {
guard capacity < n else { return }
resize(to: n)
setCapacity(n)
}
}
//MARK: - Copying helpers
extension RigidArray {
@inlinable
public func copy() -> Self {
copy(capacity: capacity)
}
@inlinable
public func copy(capacity: Int) -> Self {
precondition(capacity >= count, "RigidArray capacity overflow")
var result = RigidArray<Element>(capacity: capacity)
let initialized = unsafe result._storage.initialize(fromContentsOf: _items)
precondition(initialized == count)
result._count = count
return result
}
}
//MARK: - Opening and closing gaps
extension RigidArray where Element: ~Copyable {
@@ -423,9 +483,9 @@ extension RigidArray where Element: ~Copyable {
/// - Complexity: O(1)
@inlinable
public mutating func append(_ item: consuming Element) {
precondition(!isFull)
precondition(!isFull, "RigidArray capacity overflow")
unsafe _storage.initializeElement(at: _count, to: item)
_count += 1
_count &+= 1
}
}
@@ -454,19 +514,9 @@ extension RigidArray {
public mutating func append<C: Container<Element> & ~Copyable & ~Escapable>(
copying items: borrowing C
) {
var i = items.startIndex
var target = unsafe _freeSpace
while true {
let span = items.nextSpan(after: &i)
if span.isEmpty { break }
unsafe span.withUnsafeBufferPointer { source in
precondition(source.count <= target.count, "RigidArray capacity overflow")
unsafe target.baseAddress.unsafelyUnwrapped.initialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
_count += source.count
unsafe target = target.extracting(source.count...)
}
}
let (copied, end) = unsafe _freeSpace._initializePrefix(copying: items)
precondition(end == items.endIndex, "RigidArray capacity overflow")
_count += copied
}
}
@@ -543,26 +593,42 @@ extension RigidArray {
precondition(index >= 0 && index <= _count, "Index out of bounds")
let c = items.count
precondition(c <= freeCapacity, "RigidArray capacity overflow")
var i = items.startIndex
var target = unsafe _openGap(at: index, count: c)
while true {
let span = items.nextSpan(after: &i)
if span.isEmpty { break }
unsafe span.withUnsafeBufferPointer { source in
precondition(source.count <= target.count, "Broken Container: count doesn't match contents")
unsafe target.baseAddress.unsafelyUnwrapped.initialize(
from: source.baseAddress.unsafelyUnwrapped, count: source.count)
_count += source.count
unsafe target = target.extracting(source.count...)
}
}
precondition(target.count == 0, "Broken Container: count doesn't match contents")
let target = unsafe _openGap(at: index, count: c)
let (copied, end) = unsafe target._initializePrefix(copying: items)
precondition(
copied == c && end == items.endIndex,
"Broken Container: count doesn't match contents")
_count += c
}
}
//MARK: - Range replacement
extension RigidArray {
/// Perform a range replacement up to populating the newly opened gap. This deinitializes removed content, rearranges trailing
/// elements to be at their final size, and sets the container's new count.
///
/// - Returns: A buffer pointer addressing the newly opened gap, to be initialized by the caller.
@inlinable
internal mutating func _gapForReplacement(
of subrange: Range<Int>, withNewCount newCount: Int
) -> UnsafeMutableBufferPointer<Element> {
precondition(
subrange.lowerBound >= 0 && subrange.upperBound <= _count,
"Index range out of bounds")
precondition(newCount - subrange.count <= freeCapacity, "RigidArray capacity overflow")
unsafe _items.extracting(subrange).deinitialize()
if newCount > subrange.count {
_ = unsafe _openGap(at: subrange.upperBound, count: newCount - subrange.count)
} else if newCount < subrange.count {
_closeGap(at: subrange.lowerBound + newCount, count: subrange.count - newCount)
}
_count += newCount - subrange.count
let gapRange = unsafe Range(
uncheckedBounds: (subrange.lowerBound, subrange.lowerBound + newCount))
return unsafe _storage.extracting(gapRange)
}
/// Replaces the specified subrange of elements by copying the elements of the given collection.
///
/// This method has the effect of removing the specified range of elements
@@ -591,56 +657,113 @@ extension RigidArray {
_ subrange: Range<Int>,
with newElements: __owned some Collection<Element>
) {
precondition(
subrange.lowerBound >= 0 && subrange.upperBound <= _count,
"Index range out of bounds")
let c = newElements.count
precondition(c - subrange.count <= freeCapacity, "RigidArray capacity overflow")
unsafe _items.extracting(subrange).deinitialize()
if c > subrange.count {
_ = unsafe _openGap(at: subrange.upperBound, count: c - subrange.count)
} else if c < subrange.count {
_closeGap(at: subrange.lowerBound + c, count: subrange.count - c)
}
let gap = unsafe _storage.extracting(subrange.lowerBound ..< subrange.lowerBound + c)
let gap = unsafe _gapForReplacement(of: subrange, withNewCount: c)
var (it, copied) = unsafe newElements._copyContents(initializing: gap)
precondition(it.next() == nil && copied == c, "Broken Collection: count doesn't match contents")
_count += c - subrange.count
}
// FIXME: Add replaceSubrange(_:copying:) variants taking Span & Container
}
//MARK: - Copying and moving helpers
extension RigidArray {
// FIXME: Make these public, perhaps as initializers.
/// Replaces the specified subrange of elements by copying the elements of
/// the given buffer pointer, which must be fully initialized.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length buffer as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@inlinable
internal func _copy() -> Self {
_copy(capacity: capacity)
public mutating func replaceSubrange(
_ subrange: Range<Int>,
with newElements: UnsafeBufferPointer<Element>
) {
let gap = unsafe _gapForReplacement(of: subrange, withNewCount: newElements.count)
unsafe gap.initializeAll(fromContentsOf: newElements)
}
/// Replaces the specified subrange of elements by copying the elements of the given span.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@available(SwiftCompatibilitySpan 5.0, *)
@inlinable
internal func _copy(capacity: Int) -> Self {
precondition(capacity >= count)
var result = RigidArray<Element>(capacity: capacity)
let initialized = unsafe result._storage.initialize(fromContentsOf: _storage)
precondition(initialized == count)
result._count = count
return result
}
}
extension RigidArray where Element: ~Copyable {
@inlinable
internal mutating func _move(capacity: Int) -> Self {
precondition(capacity >= count)
var result = RigidArray<Element>(capacity: capacity)
let initialized = unsafe result._storage.moveInitialize(fromContentsOf: _storage)
precondition(initialized == count)
result._count = count
self._count = 0
return result
public mutating func replaceSubrange(
_ subrange: Range<Int>,
copying newElements: Span<Element>
) {
unsafe newElements.withUnsafeBufferPointer { buffer in
unsafe self.replaceSubrange(subrange, with: buffer)
}
}
/// Replaces the specified subrange of elements by copying the elements of the given container.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(contentsOf:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@available(SwiftCompatibilitySpan 5.0, *)
@inlinable
public mutating func replaceSubrange<C: Container<Element> & ~Copyable & ~Escapable>(
_ subrange: Range<Int>,
copying newElements: borrowing C
) {
let c = newElements.count
let gap = unsafe _gapForReplacement(of: subrange, withNewCount: c)
let (copied, end) = unsafe gap._initializePrefix(copying: newElements)
precondition(
copied == c && end == newElements.endIndex,
"Broken Container: count doesn't match contents")
}
}
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
#if false // FIXME: Disabled until I have time to track down a flaky compiler crash
#if false // FIXME: This is what we'd want
import Builtin
@@ -109,3 +111,5 @@ extension RepeatingContainer: RandomAccessContainer where Element: ~Copyable {
}
}
#endif
#endif
@@ -46,3 +46,72 @@ extension UnsafeMutableRawBufferPointer {
unsafe (self.baseAddress == other.baseAddress) && (self.count == other.count)
}
}
extension UnsafeMutableBufferPointer {
/// Initialize slots at the start of this buffer by copying data from `buffer`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized, while `buffer` must be fully initialized.
///
/// The count of `buffer` must not be greater than `self.count`.
@inlinable
internal mutating func _initializeAndDropPrefix(copying buffer: UnsafeBufferPointer<Element>) {
if buffer.isEmpty { return }
precondition(buffer.count <= self.count)
unsafe self.baseAddress.unsafelyUnwrapped.initialize(
from: buffer.baseAddress.unsafelyUnwrapped, count: buffer.count)
unsafe self = self.extracting(buffer.count...)
}
/// Initialize slots at the start of this buffer by copying data from `span`, then
/// shrink `self` to drop all initialized items from its front, leaving it addressing the
/// uninitialized remainder.
///
/// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be
/// entirely uninitialized.
///
/// The count of `span` must not be greater than `self.count`.
@available(SwiftCompatibilitySpan 5.0, *)
@inlinable
internal mutating func _initializeAndDropPrefix(copying span: Span<Element>) {
unsafe span.withUnsafeBufferPointer { buffer in
unsafe self._initializeAndDropPrefix(copying: buffer)
}
}
/// Initialize all slots in this buffer by copying data from `items`, which must fit entirely
/// in this buffer.
///
/// If `items` contains more elements than can fit into this buffer, then this function
/// will return an index other than `items.endIndex`. In that case, `self` may not be fully
/// populated.
///
/// If `Element` is not bitwise copyable, then this function must be called on an
/// entirely uninitialized buffer.
///
/// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were
/// successfully initialized, and `end` is the index into `items` after the last copied item.
@available(SwiftCompatibilitySpan 5.0, *)
@inlinable
internal func _initializePrefix<
C: Container<Element> & ~Copyable & ~Escapable
>(
copying items: borrowing C
) -> (copied: Int, end: C.Index) {
var target = unsafe self
var i = items.startIndex
while true {
let start = i
let span = items.nextSpan(after: &i)
if span.isEmpty { break }
guard span.count <= target.count else {
return (self.count - target.count, start)
}
unsafe target._initializeAndDropPrefix(copying: span)
}
return (self.count - target.count, i)
}
}
@@ -0,0 +1,110 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//
import XCTest
import _CollectionsTestSupport
import Future
class StaccatoContainerTests: CollectionTestCase {
func checkStriding<C: Container & ~Copyable & ~Escapable>(
_ container: borrowing C,
spanCounts: [Int],
file: StaticString = #file,
line: UInt = #line
) {
let entry = context.push("checkStriding", file: file, line: line)
defer { context.pop(entry) }
var i = container.startIndex
var j = 0
var seen = 0
while true {
let span = container.nextSpan(after: &i)
if i == container.endIndex {
expectLessThanOrEqual(span.count, spanCounts[j])
expectEqual(span.count, container.count - seen)
break
}
expectEqual(span.count, spanCounts[j])
seen += span.count
j += 1
if j == spanCounts.count { j = 0 }
}
}
func test_Basic1() {
let items = StaccatoContainer(
contents: RigidArray(copying: 0 ..< 10),
spanCounts: [1])
checkContainer(items, expectedContents: 0 ..< 10)
}
func test_Basic2() {
let items = StaccatoContainer(
contents: RigidArray(copying: 0 ..< 10),
spanCounts: [3])
checkContainer(items, expectedContents: 0 ..< 10)
}
func test_Basic3() {
let items = StaccatoContainer(
contents: RigidArray(copying: 0 ..< 13),
spanCounts: [1, 2])
checkContainer(items, expectedContents: 0 ..< 13)
}
func test_SingleSpec() {
withEvery("c", in: [0, 10, 20]) { c in
withEvery("spanCount", in: 1 ... 20) { spanCount in
let items = StaccatoContainer(
contents: RigidArray(copying: 0 ..< c),
spanCounts: [spanCount])
checkStriding(items, spanCounts: [spanCount])
checkContainer(items, expectedContents: 0 ..< c)
}
}
}
func test_DoubleSpec() {
withEvery("c", in: [0, 10, 20]) { c in
withEvery("spanCount1", in: 1 ... 10) { spanCount1 in
withEvery("spanCount2", in: 1 ... 10) { spanCount2 in
let spanCounts = [spanCount1, spanCount2]
let items = StaccatoContainer(
contents: RigidArray(copying: 0 ..< c),
spanCounts: spanCounts)
checkStriding(items, spanCounts: spanCounts)
checkContainer(items, expectedContents: 0 ..< c)
}
}
}
}
func test_TripleSpec() {
withEvery("c", in: [0, 10, 20]) { c in
withEvery("spanCount1", in: 1 ... 5) { spanCount1 in
withEvery("spanCount2", in: 1 ... 5) { spanCount2 in
withEvery("spanCount3", in: 1 ... 5) { spanCount3 in
let spanCounts = [spanCount1, spanCount2, spanCount3]
let items = StaccatoContainer(
contents: RigidArray(copying: 0 ..< c),
spanCounts: spanCounts)
checkStriding(items, spanCounts: spanCounts)
checkContainer(items, expectedContents: 0 ..< c)
}
}
}
}
}
}
@@ -9,6 +9,7 @@ import XCTest
import _CollectionsTestSupport
import Future
#if false
@available(SwiftStdlib 6.0, *)
class RepeatingContainerTests: CollectionTestCase {
func test_10() {
@@ -21,3 +22,4 @@ class RepeatingContainerTests: CollectionTestCase {
}
}
}
#endif
+153 -27
View File
@@ -144,6 +144,47 @@ class RigidArrayTests: CollectionTestCase {
}
}
func test_init_copying_Collection() {
withEvery("c", in: [0, 10, 100]) { c in
withLifetimeTracking { tracker in
let a = RigidArray(copying: (0 ..< c).map { tracker.instance(for: $0) })
expectEqual(tracker.instances, c)
expectEqual(a.capacity, c)
expectEqual(a.count, c)
expectEqual(a.freeCapacity, 0)
expectEqual(a.isEmpty, c == 0)
expectTrue(a.isFull)
for i in 0 ..< c {
expectEqual(a[i].payload, i)
}
}
}
}
func test_init_copying_Container() {
withEvery("c", in: [0, 10, 100]) { c in
withEvery("spanCounts", in: [
[1],
[3, 5, 7],
[10, 3],
] as [[Int]]) { spanCounts in
withLifetimeTracking { tracker in
let additions = StaccatoContainer(
contents: RigidArray(copying: (0 ..< c).map { tracker.instance(for: $0) }),
spanCounts: spanCounts)
let array = RigidArray(copying: additions)
expectEqual(tracker.instances, c)
expectEqual(array.capacity, c)
expectEqual(array.count, c)
for i in 0 ..< c {
expectEqual(array[i].payload, i)
}
}
}
}
}
func test_span() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
@@ -325,7 +366,7 @@ class RigidArrayTests: CollectionTestCase {
}
}
func test_resize_to() {
func test_setCapacity() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery(
"newCapacity",
@@ -333,7 +374,7 @@ class RigidArrayTests: CollectionTestCase {
) { newCapacity in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
a.resize(to: newCapacity)
a.setCapacity(newCapacity)
expectEqual(a.count, layout.count)
expectEqual(a.capacity, newCapacity)
expectEqual(tracker.instances, layout.count)
@@ -347,7 +388,9 @@ class RigidArrayTests: CollectionTestCase {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery(
"newCapacity",
in: [layout.capacity, layout.count, layout.count + 1, layout.capacity + 1] as Set
in: [
0, layout.count - 1, layout.count, layout.count + 1, layout.capacity, layout.capacity + 1
] as Set
) { newCapacity in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
@@ -361,6 +404,39 @@ class RigidArrayTests: CollectionTestCase {
}
}
func test_copy() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
let a = tracker.rigidArray(layout: layout)
let b = a.copy()
expectEqual(b.count, layout.count)
expectEqual(b.capacity, layout.capacity)
expectEqual(tracker.instances, layout.count)
expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
expectContainerContents(b, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
}
}
}
func test_copy_capacity() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery(
"newCapacity",
in: [layout.count, layout.count + 1, layout.capacity, layout.capacity + 1] as Set
) { newCapacity in
withLifetimeTracking { tracker in
let a = tracker.rigidArray(layout: layout)
let b = a.copy(capacity: newCapacity)
expectEqual(b.count, layout.count)
expectEqual(b.capacity, newCapacity)
expectEqual(tracker.instances, layout.count)
expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
expectContainerContents(b, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 })
}
}
}
}
func test_removeAll() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
@@ -510,17 +586,19 @@ class RigidArrayTests: CollectionTestCase {
func test_append_copying_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
let b = tracker.rigidArray( // FIXME: Use TestContainer with various span counts
layout: ArrayLayout(
capacity: layout.capacity - layout.count,
count: layout.capacity - layout.count),
using: { layout.count + $0 })
a.append(copying: b)
expectTrue(a.isFull)
expectContainerContents(a, equivalentTo: 0 ..< layout.capacity, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.capacity)
withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in
withLifetimeTracking { tracker in
var a = tracker.rigidArray(layout: layout)
let addition = (layout.count ..< layout.capacity).map { tracker.instance(for: $0) }
let b = StaccatoContainer(
contents: RigidArray(copying: addition),
spanCounts: [spanCount])
a.append(copying: b)
expectTrue(a.isFull)
expectContainerContents(a, equivalentTo: 0 ..< layout.capacity, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.capacity)
}
}
}
}
@@ -587,21 +665,24 @@ class RigidArrayTests: CollectionTestCase {
func test_insert_copying_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in
withEvery("i", in: 0 ... layout.count) { i in
withLifetimeTracking { tracker in
withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = Array(layout.count ..< layout.capacity)
expected.insert(contentsOf: addition, at: i)
var expected = Array(0 ..< layout.count)
let addition = Array(layout.count ..< layout.capacity)
expected.insert(contentsOf: addition, at: i)
var a = tracker.rigidArray(layout: layout)
let rigidAddition = RigidArray(count: addition.count) {
tracker.instance(for: addition[$0])
var a = tracker.rigidArray(layout: layout)
let rigidAddition = StaccatoContainer(
contents: RigidArray(count: addition.count) {
tracker.instance(for: addition[$0])
},
spanCounts: [Swift.max(spanCount, 1)])
a.insert(copying: rigidAddition, at: i)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.capacity)
}
// FIXME: Use TestContainer with various span counts
a.insert(copying: rigidAddition, at: i)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.capacity)
}
}
}
@@ -618,7 +699,6 @@ class RigidArrayTests: CollectionTestCase {
var a = tracker.rigidArray(layout: layout)
let trackedAddition = addition.map { tracker.instance(for: $0) }
// FIXME: Use TestContainer with various span counts
a.replaceSubrange(range, with: trackedAddition)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
@@ -628,4 +708,50 @@ class RigidArrayTests: CollectionTestCase {
}
}
}
func test_replaceSubrange_Span() {
withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in
withEveryRange("range", in: 0 ..< layout.count) { range in
withEvery("c", in: 0 ..< layout.capacity - layout.count + range.count) { c in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = (0 ..< c).map { -100 - $0 }
expected.replaceSubrange(range, with: addition)
var a = tracker.rigidArray(layout: layout)
let trackedAddition = RigidArray(copying: addition.map { tracker.instance(for: $0) })
a.replaceSubrange(range, copying: trackedAddition.span)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count - range.count + c)
}
}
}
}
}
func test_replaceSubrange_Container() {
withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in
withEveryRange("range", in: 0 ..< layout.count) { range in
withEvery("c", in: 0 ..< layout.capacity - layout.count + range.count) { c in
withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in
withLifetimeTracking { tracker in
var expected = Array(0 ..< layout.count)
let addition = (0 ..< c).map { -100 - $0 }
expected.replaceSubrange(range, with: addition)
var a = tracker.rigidArray(layout: layout)
let trackedAddition = StaccatoContainer(
contents: RigidArray(copying: addition.map { tracker.instance(for: $0) }),
spanCounts: [spanCount])
a.replaceSubrange(range, copying: trackedAddition)
expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 })
expectEqual(tracker.instances, layout.count - range.count + c)
}
}
}
}
}
}
}
@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===//
import XCTest
@testable import Future
import Future
@available(macOS 9999, *)
final class RawSpanTests: XCTestCase {
@@ -38,6 +38,7 @@ extension Container where Self: ~Copyable & ~Escapable {
}
@available(SwiftCompatibilitySpan 5.0, *)
@inlinable
public func checkContainer<
C: Container & ~Copyable & ~Escapable,
Expected: Sequence<C.Element>
@@ -55,6 +56,7 @@ public func checkContainer<
}
@available(SwiftCompatibilitySpan 5.0, *)
@inlinable
public func checkContainer<
C: Container & ~Copyable & ~Escapable,
Expected: Sequence<C.Element>
@@ -116,7 +118,7 @@ public func checkContainer<
checkComparable(allIndices, oracle: { .comparing($0, $1) })
}
withEveryRange("range", in: 0 ..< allIndices.count - 1) { range in
withEveryRange("range", in: 0 ..< expectedContents.count) { range in
let i = range.lowerBound
let j = range.upperBound
@@ -133,9 +135,7 @@ public func checkContainer<
}
// Check `formIndex(_,offsetBy:limitedBy:)`
let limits =
Set([0, allIndices.count - 1, allIndices.count / 2])
.sorted()
let limits = Set([0, allIndices.count - 1, allIndices.count / 2]).sorted()
withEvery("limit", in: limits) { limit in
withEvery("i", in: 0 ..< allIndices.count) { i in
let max = allIndices.count - i + (limit >= i ? 2 : 0)
@@ -170,13 +170,13 @@ public func checkContainer<
pos += span.count
if span.isEmpty {
expectEqual(origIndex, container.endIndex)
expectEqual(index, origIndex, "nextCount is not expected to move the end index")
expectEqual(index, origIndex, "nextSpan is not expected to move the end index")
break
}
expectGreaterThan(
index, origIndex, "nextCount does not monotonically increase the index")
index, origIndex, "nextSpan does not monotonically increase the index")
expectEqual(
index, allIndices[pos], "nextCount does not increase the index by the size of the span")
index, allIndices[pos], "nextSpan does not advance the index by the size of the returned span")
r.append((origPos ..< pos, origIndex ..< index))
}
return r
@@ -1,56 +1,60 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors
// Copyright (c) 2025 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Future
public struct TestContainer<Element: ~Copyable>: ~Copyable {
/// A container type with user-defined contents and storage chunks. Useful for testing.
public struct StaccatoContainer<Element: ~Copyable>: ~Copyable {
internal let _contents: RigidArray<Element>
internal let _spanCounts: [Int]
internal let _modulus: Int
public init(contents: consuming RigidArray<Element>, spanCounts: [Int]) {
precondition(spanCounts.allSatisfy { $0 > 0 })
// FIXME: Make this take an arbitrary consumable container
precondition(!spanCounts.isEmpty && spanCounts.allSatisfy { $0 > 0 })
self._contents = contents
self._spanCounts = spanCounts
self._modulus = spanCounts.reduce(into: 0, { $0 += $1 })
}
}
extension TestContainer where Element: ~Copyable {
public struct Index: Comparable {
internal var _offset: Int
public struct _StaccatoContainerIndex: Comparable {
internal var _offset: Int
internal init(_offset: Int) {
self._offset = _offset
}
public static func == (left: Self, right: Self) -> Bool { left._offset == right._offset }
public static func < (left: Self, right: Self) -> Bool { left._offset < right._offset }
internal init(_offset: Int) {
self._offset = _offset
}
public static func == (left: Self, right: Self) -> Bool { left._offset == right._offset }
public static func < (left: Self, right: Self) -> Bool { left._offset < right._offset }
}
extension StaccatoContainer where Element: ~Copyable {
public typealias Index = _StaccatoContainerIndex // rdar://150240032
func _spanCoordinates(atOffset offset: Int) -> (spanIndex: Int, spanOffset: Int) {
precondition(offset >= 0 && offset <= _contents.count)
let modulus = _spanCounts.reduce(into: 0, { $0 += $1 })
var remainder = offset % modulus
for i in 0 ..< _spanCounts.count {
var remainder = offset % _modulus
var i = 0
while i < _spanCounts.count {
let c = _spanCounts[i]
if remainder < c {
return (i, remainder)
}
if remainder < c { break }
remainder -= c
i += 1
}
return (_spanCounts.count, 0)
return (i, remainder)
}
}
extension TestContainer where Element: ~Copyable {
extension StaccatoContainer where Element: ~Copyable {
public var isEmpty: Bool { _contents.isEmpty }
public var count: Int { _contents.count }
public var startIndex: Index { Index(_offset: 0) }
@@ -77,7 +81,7 @@ extension TestContainer where Element: ~Copyable {
}
@available(SwiftCompatibilitySpan 5.0, *)
extension TestContainer: Container where Element: ~Copyable {
extension StaccatoContainer: Container where Element: ~Copyable {
public func formIndex(_ i: inout Index, offsetBy distance: inout Int, limitedBy limit: Index) {
precondition(i >= startIndex && i <= endIndex)
_contents.formIndex(&i._offset, offsetBy: &distance, limitedBy: limit._offset)
@@ -85,18 +89,19 @@ extension TestContainer: Container where Element: ~Copyable {
@lifetime(borrow self)
public func borrowElement(at index: Index) -> Future.Borrow<Element> {
precondition(index >= startIndex && index < endIndex)
precondition(index >= startIndex && index < endIndex, "Index out of bounds")
return _contents.borrowElement(at: index._offset)
}
@lifetime(borrow self)
public func nextSpan(after index: inout Index) -> Span<Element> {
precondition(index >= startIndex && index <= endIndex)
let (spanIndex, spanOffset) = _spanCoordinates(atOffset: index._offset)
let span = _contents.span
guard spanIndex < _spanCounts.count else { return span._extracting(last: 0) }
let (spanIndex, spanOffset) = _spanCoordinates(atOffset: index._offset)
let c = _spanCounts[spanIndex] - spanOffset
index._offset += c
return span._extracting(index._offset ..< index._offset + c)
let startOffset = index._offset
let endOffset = Swift.min(startOffset + c, span.count)
index._offset = endOffset
return span._extracting(startOffset ..< endOffset)
}
}