mirror of
https://github.com/apple/swift-collections
synced 2026-11-26 04:47:48 +00:00
[TestSupport] Add Container validator and StaccatoContainer
These are precursors for container protocols, referenced by the new array tests
This commit is contained in:
3 files changed
+353
No files matched your search
@@ -0,0 +1,231 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
|
||||
import XCTest
|
||||
import ContainersPreview
|
||||
|
||||
@available(SwiftStdlib 6.2, *)
|
||||
extension Container where Self: ~Copyable & ~Escapable {
|
||||
@inlinable
|
||||
internal func _indicesByIndexAfter() -> [Index] {
|
||||
var result: [Index] = []
|
||||
var i = startIndex
|
||||
while i != endIndex {
|
||||
result.append(i)
|
||||
i = index(after: i)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _indicesByFormIndexAfter() -> [Index] {
|
||||
var result: [Index] = []
|
||||
var i = startIndex
|
||||
while i != endIndex {
|
||||
result.append(i)
|
||||
formIndex(after: &i)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 6.2, *)
|
||||
@inlinable
|
||||
public func checkContainer<
|
||||
C: Container & ~Copyable & ~Escapable,
|
||||
Expected: Sequence<C.Element>
|
||||
>(
|
||||
_ container: borrowing C,
|
||||
expectedContents: Expected,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) where C.Element: Equatable {
|
||||
checkContainer(
|
||||
container,
|
||||
expectedContents: expectedContents,
|
||||
by: ==,
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 6.2, *)
|
||||
@inlinable
|
||||
public func checkContainer<
|
||||
C: Container & ~Copyable & ~Escapable,
|
||||
Expected: Sequence<C.Element>
|
||||
>(
|
||||
_ container: borrowing C,
|
||||
expectedContents: Expected,
|
||||
by areEquivalent: (C.Element, C.Element) -> Bool,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) where C.Element: Equatable {
|
||||
let entry = TestContext.current.push("checkContainer", file: file, line: line)
|
||||
defer { TestContext.current.pop(entry) }
|
||||
|
||||
let expectedContents = Array(expectedContents)
|
||||
expectEqual(container.isEmpty, expectedContents.isEmpty)
|
||||
let actualCount = container.count
|
||||
expectEqual(actualCount, expectedContents.count)
|
||||
|
||||
let validIndices = container._indicesByIndexAfter()
|
||||
|
||||
expectEqual(
|
||||
container._indicesByIndexAfter(), validIndices,
|
||||
"Container does not have stable indices")
|
||||
|
||||
// Check that `index(after:)` produces the same results as `formIndex(after:)`
|
||||
do {
|
||||
let indicesByFormIndexAfter = container._indicesByFormIndexAfter()
|
||||
expectEqual(indicesByFormIndexAfter, validIndices)
|
||||
}
|
||||
|
||||
expectEqual(container.index(container.startIndex, offsetBy: container.count), container.endIndex)
|
||||
|
||||
// Check contents using indexing.
|
||||
let actualContents = validIndices.map { container[$0] }
|
||||
expectEquivalentElements(actualContents, expectedContents, by: areEquivalent)
|
||||
|
||||
let allIndices = validIndices + [container.endIndex]
|
||||
do {
|
||||
var last: C.Index? = nil
|
||||
for index in allIndices {
|
||||
if let last {
|
||||
// The indices must be monotonically increasing.
|
||||
expectGreaterThan(
|
||||
index, last,
|
||||
"Index \(index) is not greater than immediately preceding index \(last)")
|
||||
|
||||
// Aligning a valid index must not change it.
|
||||
let nearestDown = container.index(alignedDown: index)
|
||||
expectEqual(nearestDown, index, "Aligning a valid index down must not change its position")
|
||||
let nearestUp = container.index(alignedUp: index)
|
||||
expectEqual(nearestUp, index, "Aligning a valid index up must not change its position")
|
||||
}
|
||||
last = index
|
||||
}
|
||||
}
|
||||
|
||||
// Check the `Comparable` conformance of the Index type.
|
||||
if C.Index.self != Int.self {
|
||||
checkComparable(allIndices, oracle: { .comparing($0, $1) })
|
||||
}
|
||||
|
||||
withEveryRange("range", in: 0 ..< expectedContents.count) { range in
|
||||
let i = range.lowerBound
|
||||
let j = range.upperBound
|
||||
|
||||
// Check `index(_,offsetBy:)`
|
||||
let e = container.index(allIndices[i], offsetBy: j - i)
|
||||
expectEqual(e, allIndices[j])
|
||||
if j < expectedContents.count {
|
||||
expectEquivalent(container[e], expectedContents[j], by: areEquivalent)
|
||||
}
|
||||
|
||||
// Check `distance(from:to:)`
|
||||
let d = container.distance(from: allIndices[i], to: allIndices[j])
|
||||
expectEqual(d, j - i)
|
||||
}
|
||||
|
||||
// Check `formIndex(_,offsetBy:limitedBy:)`
|
||||
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)
|
||||
withEvery("delta", in: 0 ..< max) { delta in
|
||||
let target = i + delta
|
||||
var index = allIndices[i]
|
||||
var d = delta
|
||||
container.formIndex(&index, offsetBy: &d, limitedBy: allIndices[limit])
|
||||
if i > limit {
|
||||
expectEqual(d, 0, "Nonzero remainder after jump opposite limit")
|
||||
expectEqual(index, allIndices[target], "Jump opposite limit landed in wrong position")
|
||||
} else if target <= limit {
|
||||
expectEqual(d, 0, "Nonzero remainder after jump within limit")
|
||||
expectEqual(index, allIndices[target], "Jump within limit landed in wrong position")
|
||||
} else {
|
||||
expectEqual(d, target - limit, "Unexpected remainder after jump beyond limit")
|
||||
expectEqual(index, allIndices[limit], "Jump beyond limit landed in unexpected position")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check that the spans seem plausibly sized and that the indices are monotonic.
|
||||
let spanShapes: [(offsetRange: Range<Int>, indexRange: Range<C.Index>)] = {
|
||||
var r: [(offsetRange: Range<Int>, indexRange: Range<C.Index>)] = []
|
||||
var pos = 0
|
||||
var index = container.startIndex
|
||||
while true {
|
||||
let origIndex = index
|
||||
let origPos = pos
|
||||
let span = container.span(after: &index)
|
||||
pos += span.count
|
||||
if span.isEmpty {
|
||||
expectEqual(origIndex, container.endIndex)
|
||||
expectEqual(index, origIndex, "span(after:) is not expected to move the end index")
|
||||
break
|
||||
}
|
||||
expectGreaterThan(
|
||||
index, origIndex, "span(after:) does not monotonically increase the index")
|
||||
expectEqual(
|
||||
index, allIndices[pos], "span(after:) does not advance the index by the size of the returned span")
|
||||
r.append((origPos ..< pos, origIndex ..< index))
|
||||
}
|
||||
return r
|
||||
}()
|
||||
expectEqual(
|
||||
spanShapes.reduce(into: 0, { $0 += $1.offsetRange.count }), actualCount,
|
||||
"Container's count does not match the sum of its spans")
|
||||
|
||||
|
||||
// Check that the spans have stable sizes and the expected contents.
|
||||
do {
|
||||
var pos = 0
|
||||
var index = container.startIndex
|
||||
var spanIndex = 0
|
||||
while true {
|
||||
let span = container.span(after: &index)
|
||||
if span.isEmpty { break }
|
||||
expectEqual(
|
||||
span.count, spanShapes[spanIndex].offsetRange.count,
|
||||
"Container has nondeterministic span sizes")
|
||||
expectEqual(
|
||||
index, spanShapes[spanIndex].indexRange.upperBound,
|
||||
"Container has nondeterministic span boundaries")
|
||||
for i in 0 ..< span.count {
|
||||
expectEqual(span[i], expectedContents[pos])
|
||||
pos += 1
|
||||
}
|
||||
spanIndex += 1
|
||||
}
|
||||
expectEqual(spanIndex, spanShapes.endIndex)
|
||||
expectEqual(pos, expectedContents.count)
|
||||
}
|
||||
|
||||
// Check that we can get a span beginning at every index, and that it extends as much as possible.
|
||||
do {
|
||||
for spanIndex in spanShapes.indices {
|
||||
let (offsetRange, indexRange) = spanShapes[spanIndex]
|
||||
for pos in offsetRange {
|
||||
let start = validIndices[pos]
|
||||
var i = start
|
||||
let span = container.span(after: &i)
|
||||
|
||||
expectEqual(span.count, offsetRange.upperBound - pos,
|
||||
"Unexpected span size at offset \(pos), index \(start)")
|
||||
expectEqual(i, indexRange.upperBound,
|
||||
"Unexpected span upper bound at offset \(pos), index \(start)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,114 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if COLLECTIONS_SINGLE_MODULE
|
||||
import Collections
|
||||
#else
|
||||
import ContainersPreview
|
||||
#endif
|
||||
|
||||
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
|
||||
/// 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]) {
|
||||
// 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 })
|
||||
}
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
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)
|
||||
var remainder = offset % _modulus
|
||||
var i = 0
|
||||
while i < _spanCounts.count {
|
||||
let c = _spanCounts[i]
|
||||
if remainder < c { break }
|
||||
remainder -= c
|
||||
i += 1
|
||||
}
|
||||
return (i, remainder)
|
||||
}
|
||||
}
|
||||
|
||||
extension StaccatoContainer where Element: ~Copyable {
|
||||
public var isEmpty: Bool { _contents.isEmpty }
|
||||
public var count: Int { _contents.count }
|
||||
public var startIndex: Index { Index(_offset: 0) }
|
||||
public var endIndex: Index { Index(_offset: _contents.count) }
|
||||
public func index(after index: Index) -> Index {
|
||||
precondition(index >= startIndex && index < endIndex)
|
||||
return Index(_offset: index._offset + 1)
|
||||
}
|
||||
public func formIndex(after i: inout Index) {
|
||||
i = index(after: i)
|
||||
}
|
||||
public func index(_ index: Index, offsetBy n: Int) -> Index {
|
||||
precondition(index._offset >= 0 && index._offset <= _contents.count)
|
||||
let offset = index._offset + n
|
||||
precondition(offset >= 0 && offset <= _contents.count)
|
||||
return Index(_offset: offset)
|
||||
}
|
||||
|
||||
public func distance(from start: Index, to end: Index) -> Int {
|
||||
precondition(start >= startIndex && start <= endIndex)
|
||||
precondition(end >= startIndex && end <= endIndex)
|
||||
return end._offset - start._offset
|
||||
}
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 6.2, *)
|
||||
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)
|
||||
}
|
||||
|
||||
@lifetime(borrow self)
|
||||
public func borrowElement(at index: Index) -> Future.Borrow<Element> {
|
||||
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 span = _contents.span
|
||||
let (spanIndex, spanOffset) = _spanCoordinates(atOffset: index._offset)
|
||||
let c = _spanCounts[spanIndex] - spanOffset
|
||||
let startOffset = index._offset
|
||||
let endOffset = Swift.min(startOffset + c, span.count)
|
||||
index._offset = endOffset
|
||||
return span._extracting(startOffset ..< endOffset)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -25,6 +25,8 @@
|
||||
7D48BCED2E5158A100D7F6F7 /* BorrowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCE52E5158A100D7F6F7 /* BorrowTests.swift */; };
|
||||
7D48BCEE2E5158A100D7F6F7 /* BoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCE62E5158A100D7F6F7 /* BoxTests.swift */; };
|
||||
7D48BCF02E51597200D7F6F7 /* Assertions+Containers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCEF2E51597200D7F6F7 /* Assertions+Containers.swift */; };
|
||||
7D48BCF22E51599200D7F6F7 /* CheckContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCF12E51599200D7F6F7 /* CheckContainer.swift */; };
|
||||
7D48BCF42E5159A300D7F6F7 /* StaccatoContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCF32E5159A300D7F6F7 /* StaccatoContainer.swift */; };
|
||||
7D48BCFE2E5182CE00D7F6F7 /* UnsafeRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCFD2E5182CE00D7F6F7 /* UnsafeRawBufferPointer+Extras.swift */; };
|
||||
7D48BCFF2E5182CE00D7F6F7 /* UnsafeMutableRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCFC2E5182CE00D7F6F7 /* UnsafeMutableRawBufferPointer+Extras.swift */; };
|
||||
7D48BD002E5182CE00D7F6F7 /* LifetimeOverride.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCFA2E5182CE00D7F6F7 /* LifetimeOverride.swift */; };
|
||||
@@ -466,6 +468,8 @@
|
||||
7D48BCE62E5158A100D7F6F7 /* BoxTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BoxTests.swift; sourceTree = "<group>"; };
|
||||
7D48BCE72E5158A100D7F6F7 /* InoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InoutTests.swift; sourceTree = "<group>"; };
|
||||
7D48BCEF2E51597200D7F6F7 /* Assertions+Containers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Assertions+Containers.swift"; sourceTree = "<group>"; };
|
||||
7D48BCF12E51599200D7F6F7 /* CheckContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CheckContainer.swift; sourceTree = "<group>"; };
|
||||
7D48BCF32E5159A300D7F6F7 /* StaccatoContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StaccatoContainer.swift; sourceTree = "<group>"; };
|
||||
7D48BCF52E51651900D7F6F7 /* Package@swift-6.0.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = "Package@swift-6.0.swift"; path = "../Package@swift-6.0.swift"; sourceTree = SOURCE_ROOT; };
|
||||
7D48BCF62E5172CF00D7F6F7 /* LifetimeOverride.swift.gyb */ = {isa = PBXFileReference; lastKnownFileType = text; path = LifetimeOverride.swift.gyb; sourceTree = "<group>"; };
|
||||
7D48BCF82E5172CF00D7F6F7 /* UnsafeMutableRawBufferPointer+Extras.swift.gyb */ = {isa = PBXFileReference; lastKnownFileType = text; path = "UnsafeMutableRawBufferPointer+Extras.swift.gyb"; sourceTree = "<group>"; };
|
||||
@@ -1834,6 +1838,7 @@
|
||||
7DEBDB3929CCE43600ADC226 /* CheckBidirectionalCollection.swift */,
|
||||
7DEBDB3429CCE43600ADC226 /* CheckCollection.swift */,
|
||||
7DEBDB3629CCE43600ADC226 /* CheckComparable.swift */,
|
||||
7D48BCF12E51599200D7F6F7 /* CheckContainer.swift */,
|
||||
7DEBDB3729CCE43600ADC226 /* CheckEquatable.swift */,
|
||||
7DEBDB3529CCE43600ADC226 /* CheckHashable.swift */,
|
||||
7DEBDB3829CCE43600ADC226 /* CheckSequence.swift */,
|
||||
@@ -1858,6 +1863,7 @@
|
||||
7DEBDB4329CCE43600ADC226 /* MinimalRangeReplaceableRandomAccessCollection.swift */,
|
||||
7DEBDB3E29CCE43600ADC226 /* MinimalSequence.swift */,
|
||||
7DEBDB4229CCE43600ADC226 /* ResettableValue.swift */,
|
||||
7D48BCF32E5159A300D7F6F7 /* StaccatoContainer.swift */,
|
||||
);
|
||||
path = MinimalTypes;
|
||||
sourceTree = "<group>";
|
||||
@@ -2325,6 +2331,7 @@
|
||||
7DE9220C29CA8576004483EB /* Availability.swift in Sources */,
|
||||
7DE9220029CA8576004483EB /* TreeDictionary Smoke Tests.swift in Sources */,
|
||||
7DEBDB9029CCE44A00ADC226 /* TestContext.swift in Sources */,
|
||||
7D48BCF22E51599200D7F6F7 /* CheckContainer.swift in Sources */,
|
||||
7DE9221429CA8576004483EB /* OrderedSet Diffing Tests.swift in Sources */,
|
||||
7DEBDB1D29CBF6B200ADC226 /* RandomAccessCollection+Offsets.swift in Sources */,
|
||||
7DEBDB8529CCE44A00ADC226 /* AllOnesRandomNumberGenerator.swift in Sources */,
|
||||
@@ -2405,6 +2412,7 @@
|
||||
7DE9220829CA8576004483EB /* BitSetTests.swift in Sources */,
|
||||
7DEBDB7329CCE44A00ADC226 /* _MinimalCollectionCore.swift in Sources */,
|
||||
7DE921C829CA81DC004483EB /* _UniqueCollection.swift in Sources */,
|
||||
7D48BCF42E5159A300D7F6F7 /* StaccatoContainer.swift in Sources */,
|
||||
7DE9220629CA8576004483EB /* TreeSet Tests.swift in Sources */,
|
||||
7DEBDB9229CCE44A00ADC226 /* StringConvertibleValue.swift in Sources */,
|
||||
7DEBDB6F29CCE44A00ADC226 /* MinimalMutableRangeReplaceableRandomAccessCollection.swift in Sources */,
|
||||
|
||||
Reference in new issue
Block a user