Skip to content

[stdlib] Conditionally conform EnumeratedSequence to Collection(s) #78092

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 7 commits into from
Mar 18, 2025
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions Runtimes/Core/core/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ add_library(swiftCore
DropWhile.swift
Dump.swift
EmptyCollection.swift
EnumeratedSequence.swift
Equatable.swift
ErrorType.swift
ExistentialCollection.swift
Expand Down
161 changes: 161 additions & 0 deletions stdlib/private/StdlibCollectionUnittest/MinimalCollections.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1615,6 +1615,167 @@ public struct MinimalBidirectionalCollection<T> : BidirectionalCollection {
internal let _collectionState: _CollectionState
}

/// A minimal implementation of `Collection` with extra checks.
public struct MinimalBidirectionalRandomAccessCollection<T> : BidirectionalCollection, RandomAccessCollection {
/// Creates a collection with given contents, but a unique modification
/// history. No other instance has the same modification history.
public init<S : Sequence>(
elements: S,
underestimatedCount: UnderestimatedCountBehavior = .value(0)
) where S.Element == T {
self._elements = Array(elements)

self._collectionState = _CollectionState(
newRootStateForElementCount: self._elements.count)

switch underestimatedCount {
case .precise:
self.underestimatedCount = _elements.count

case .half:
self.underestimatedCount = _elements.count / 2

case .overestimate:
self.underestimatedCount = _elements.count * 3 + 5

case .value(let count):
self.underestimatedCount = count
}
}


public let timesMakeIteratorCalled = ResettableValue(0)

public func makeIterator() -> MinimalIterator<T> {
timesMakeIteratorCalled.value += 1
return MinimalIterator(_elements)
}

public typealias Index = MinimalIndex

internal func _index(forPosition i: Int) -> MinimalIndex {
return MinimalIndex(
collectionState: _collectionState,
position: i,
startIndex: _elements.startIndex,
endIndex: _elements.endIndex)
}

internal func _uncheckedIndex(forPosition i: Int) -> MinimalIndex {
return MinimalIndex(
_collectionState: _collectionState,
uncheckedPosition: i)
}

public let timesStartIndexCalled = ResettableValue(0)

public var startIndex: MinimalIndex {
timesStartIndexCalled.value += 1
return _uncheckedIndex(forPosition: _elements.startIndex)
}

public let timesEndIndexCalled = ResettableValue(0)

public var endIndex: MinimalIndex {
timesEndIndexCalled.value += 1
return _uncheckedIndex(forPosition: _elements.endIndex)
}


public func _failEarlyRangeCheck(
_ index: MinimalIndex,
bounds: Range<MinimalIndex>
) {
_expectCompatibleIndices(
_uncheckedIndex(forPosition: index.position),
index)

_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.lowerBound.position),
bounds.lowerBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.upperBound.position),
bounds.upperBound)

expectTrapping(
index.position,
in: bounds.lowerBound.position..<bounds.upperBound.position)
}

public func _failEarlyRangeCheck(
_ range: Range<MinimalIndex>,
bounds: Range<MinimalIndex>
) {
_expectCompatibleIndices(
_uncheckedIndex(forPosition: range.lowerBound.position),
range.lowerBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: range.upperBound.position),
range.upperBound)

_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.lowerBound.position),
bounds.lowerBound)
_expectCompatibleIndices(
_uncheckedIndex(forPosition: bounds.upperBound.position),
bounds.upperBound)

expectTrapping(
range.lowerBound.position..<range.upperBound.position,
in: bounds.lowerBound.position..<bounds.upperBound.position)
}

public func index(after i: MinimalIndex) -> MinimalIndex {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
return _uncheckedIndex(forPosition: i.position + 1)
}

public func index(before i: MinimalIndex) -> MinimalIndex {
// FIXME: swift-3-indexing-model: perform a range check and use
// return _uncheckedIndex(forPosition: i.position - 1)
return _index(forPosition: i.position - 1)
}

public func distance(from start: MinimalIndex, to end: MinimalIndex)
-> Int {
// FIXME: swift-3-indexing-model: perform a range check properly.
if start != endIndex {
_failEarlyRangeCheck(start, bounds: startIndex..<endIndex)
}
if end != endIndex {
_failEarlyRangeCheck(end, bounds: startIndex..<endIndex)
}
return end.position - start.position
}

public func index(_ i: Index, offsetBy n: Int) -> Index {
// FIXME: swift-3-indexing-model: perform a range check properly.
if i != endIndex {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
}
return _index(forPosition: i.position + n)
}

public subscript(i: MinimalIndex) -> T {
get {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
return _elements[i.position]
}
}

public subscript(bounds: Range<MinimalIndex>) -> Slice<MinimalBidirectionalRandomAccessCollection<T>> {
get {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
}


public var underestimatedCount: Int

internal var _elements: [T]
internal let _collectionState: _CollectionState
}

/// A minimal implementation of `Collection` with extra checks.
public struct MinimalRangeReplaceableBidirectionalCollection<T> : BidirectionalCollection, RangeReplaceableCollection {
Expand Down
88 changes: 0 additions & 88 deletions stdlib/public/core/Algorithm.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,91 +74,3 @@ public func max<T: Comparable>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T {
}
return maxValue
}

/// An enumeration of the elements of a sequence or collection.
///
/// `EnumeratedSequence` is a sequence of pairs (*n*, *x*), where *n*s are
/// consecutive `Int` values starting at zero, and *x*s are the elements of a
/// base sequence.
///
/// To create an instance of `EnumeratedSequence`, call `enumerated()` on a
/// sequence or collection. The following example enumerates the elements of
/// an array.
///
/// var s = ["foo", "bar"].enumerated()
/// for (n, x) in s {
/// print("\(n): \(x)")
/// }
/// // Prints "0: foo"
/// // Prints "1: bar"
@frozen
public struct EnumeratedSequence<Base: Sequence> {
@usableFromInline
internal var _base: Base

/// Construct from a `Base` sequence.
@inlinable
internal init(_base: Base) {
self._base = _base
}
}

extension EnumeratedSequence: Sendable where Base: Sendable {}

extension EnumeratedSequence {
/// The iterator for `EnumeratedSequence`.
///
/// An instance of this iterator wraps a base iterator and yields
/// successive `Int` values, starting at zero, along with the elements of the
/// underlying base iterator. The following example enumerates the elements of
/// an array:
///
/// var iterator = ["foo", "bar"].enumerated().makeIterator()
/// iterator.next() // (0, "foo")
/// iterator.next() // (1, "bar")
/// iterator.next() // nil
///
/// To create an instance, call
/// `enumerated().makeIterator()` on a sequence or collection.
@frozen
public struct Iterator {
@usableFromInline
internal var _base: Base.Iterator
@usableFromInline
internal var _count: Int

/// Construct from a `Base` iterator.
@inlinable
internal init(_base: Base.Iterator) {
self._base = _base
self._count = 0
}
}
}

extension EnumeratedSequence.Iterator: Sendable where Base.Iterator: Sendable {}

extension EnumeratedSequence.Iterator: IteratorProtocol, Sequence {
/// The type of element returned by `next()`.
public typealias Element = (offset: Int, element: Base.Element)

/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
public mutating func next() -> Element? {
guard let b = _base.next() else { return nil }
let result = (offset: _count, element: b)
_count += 1
return result
}
}

extension EnumeratedSequence: Sequence {
/// Returns an iterator over the elements of this sequence.
@inlinable
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator())
}
}
1 change: 1 addition & 0 deletions stdlib/public/core/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ split_embedded_sources(
EMBEDDED DropWhile.swift
NORMAL Dump.swift
EMBEDDED EmptyCollection.swift
EMBEDDED EnumeratedSequence.swift
EMBEDDED Equatable.swift
EMBEDDED ErrorType.swift
EMBEDDED ExistentialCollection.swift
Expand Down
Loading