[PersistentCollection] Back out BidirectionalCollection conformance

BidirectionalCollection has the connotation that the ordering
of elements is meaningful, which isn’t the case for PersistentSet
and PersistentDictionary.
This commit is contained in:
Karoy Lorentey committed 2022-10-27 18:08:27 -07:00
1 parent 82b7a53960
commit 84356e58c7
12 files changed
+196 -110

No files matched your search

@@ -77,7 +77,7 @@ extension PersistentDictionary.Index: CustomDebugStringConvertible {
}
}
extension PersistentDictionary: BidirectionalCollection {
extension PersistentDictionary: Collection {
@inlinable
public var isEmpty: Bool {
_root.count == 0
@@ -130,14 +130,6 @@ extension PersistentDictionary: BidirectionalCollection {
}
}
@inlinable
public func formIndex(before i: inout Index) {
precondition(_isValid(i), "Invalid index")
guard i._path.findPredecessorItem(under: _root.raw) else {
preconditionFailure("The start index has no predecessor")
}
}
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
var i = i
@@ -145,13 +137,6 @@ extension PersistentDictionary: BidirectionalCollection {
return i
}
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
precondition(_isValid(start) && _isValid(end), "Invalid index")
@@ -182,3 +167,37 @@ extension PersistentDictionary: BidirectionalCollection {
return nil
}
}
#if false
// Note: Let's not do this. `BidirectionalCollection` would imply that
// the ordering of elements would be meaningful, which isn't true for
// `PersistentDictionary`.
extension PersistentDictionary: BidirectionalCollection {
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable
public func formIndex(before i: inout Index) {
precondition(_isValid(i), "Invalid index")
guard i._path.findPredecessorItem(under: _root.raw) else {
preconditionFailure("The start index has no predecessor")
}
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
}
#endif
@@ -102,7 +102,7 @@ extension PersistentDictionary.Keys.Iterator: Sendable
where Key: Sendable, Value: Sendable {}
#endif
extension PersistentDictionary.Keys: BidirectionalCollection {
extension PersistentDictionary.Keys: Collection {
public typealias Index = PersistentDictionary.Index
@inlinable
@@ -127,21 +127,11 @@ extension PersistentDictionary.Keys: BidirectionalCollection {
_base.formIndex(after: &i)
}
@inlinable
public func formIndex(before i: inout Index) {
_base.formIndex(before: &i)
}
@inlinable
public func index(after i: Index) -> Index {
_base.index(after: i)
}
@inlinable
public func index(before i: Index) -> Index {
_base.index(before: i)
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
_base.index(i, offsetBy: distance)
@@ -159,3 +149,17 @@ extension PersistentDictionary.Keys: BidirectionalCollection {
_base.distance(from: start, to: end)
}
}
#if false
extension PersistentDictionary.Keys: BidirectionalCollection {
@inlinable
public func formIndex(before i: inout Index) {
_base.formIndex(before: &i)
}
@inlinable
public func index(before i: Index) -> Index {
_base.index(before: i)
}
}
#endif
@@ -106,7 +106,7 @@ where Key: Sendable, Value: Sendable {}
// Note: This cannot be a MutableCollection because its subscript setter
// needs to invalidate indices.
extension PersistentDictionary.Values: BidirectionalCollection {
extension PersistentDictionary.Values: Collection {
public typealias Index = PersistentDictionary.Index
@inlinable
@@ -153,21 +153,11 @@ extension PersistentDictionary.Values: BidirectionalCollection {
_base.formIndex(after: &i)
}
@inlinable
public func formIndex(before i: inout Index) {
_base.formIndex(before: &i)
}
@inlinable
public func index(after i: Index) -> Index {
_base.index(after: i)
}
@inlinable
public func index(before i: Index) -> Index {
_base.index(before: i)
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
_base.index(i, offsetBy: distance)
@@ -185,3 +175,17 @@ extension PersistentDictionary.Values: BidirectionalCollection {
_base.distance(from: start, to: end)
}
}
#if false
extension PersistentDictionary.Values: BidirectionalCollection {
@inlinable
public func formIndex(before i: inout Index) {
_base.formIndex(before: &i)
}
@inlinable
public func index(before i: Index) -> Index {
_base.index(before: i)
}
}
#endif
@@ -78,7 +78,7 @@ extension PersistentSet.Index: CustomDebugStringConvertible {
}
}
extension PersistentSet: BidirectionalCollection {
extension PersistentSet: Collection {
@inlinable
public var isEmpty: Bool {
_root.count == 0
@@ -130,14 +130,6 @@ extension PersistentSet: BidirectionalCollection {
}
}
@inlinable
public func formIndex(before i: inout Index) {
precondition(_isValid(i), "Invalid index")
guard i._path.findPredecessorItem(under: _root.raw) else {
preconditionFailure("The start index has no predecessor")
}
}
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
var i = i
@@ -145,13 +137,6 @@ extension PersistentSet: BidirectionalCollection {
return i
}
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
precondition(_isValid(start) && _isValid(end), "Invalid index")
@@ -221,3 +206,37 @@ extension PersistentSet: BidirectionalCollection {
precondition(_isValid(range.lowerBound) && _isValid(range.upperBound))
}
}
#if false
// Note: Let's not do this. `BidirectionalCollection` would imply that
// the ordering of elements would be meaningful, which isn't true for
// `PersistentSet`.
extension PersistentSet: BidirectionalCollection {
/// Replaces the given index with its predecessor.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable
public func formIndex(before i: inout Index) {
precondition(_isValid(i), "Invalid index")
guard i._path.findPredecessorItem(under: _root.raw) else {
preconditionFailure("The start index has no predecessor")
}
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection.
/// `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
}
#endif
@@ -80,6 +80,61 @@ public func checkBidirectionalCollection<C: BidirectionalCollection, S: Sequence
file: file, line: line)
}
public func _checkBidirectionalCollection_indexOffsetBy<
C: Collection
>(
_ collection: C,
expectedContents: [C.Element],
by areEquivalent: (C.Element, C.Element) -> Bool,
maxSamples: Int? = nil,
file: StaticString = #file,
line: UInt = #line
) {
var allIndices = collection._indicesByIndexAfter()
allIndices.append(collection.endIndex)
withSomeRanges(
"range",
in: 0 ..< allIndices.count - (1 as Int),
maxSamples: maxSamples
) { range in
let i = range.lowerBound
let j = range.upperBound
// Check `index(_,offsetBy:)` with negative offsets
let a = collection.index(allIndices[j], offsetBy: i - j)
expectEqual(a, allIndices[i])
if i < expectedContents.count {
expectEquivalent(
collection[a], expectedContents[i],
by: areEquivalent)
}
// Check `distance(from:to:)` with decreasing indices
let d = collection.distance(from: allIndices[j], to: allIndices[i])
expectEqual(d, i - j)
}
// Check `index(_,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 min = -i - (limit <= i ? 2 : 0)
withEvery("delta", in: stride(from: 0, through: min, by: -1)) { delta in
let actual = collection.index(
allIndices[i],
offsetBy: delta,
limitedBy: allIndices[limit])
let j = i + delta
let expected = i < limit || j >= limit ? allIndices[j] : nil
expectEqual(actual, expected)
}
}
}
}
public func _checkBidirectionalCollection<C: BidirectionalCollection, S: Sequence>(
_ collection: C,
expectedContents: S,
@@ -112,6 +167,11 @@ public func _checkBidirectionalCollection<C: BidirectionalCollection, S: Sequenc
by: areEquivalent,
"\(expectedContents)")
// Check `distance(from:to:)`, `index(_:offsetBy)` and
// `index(_:offsetBy:limitedBy:)`.
_checkBidirectionalCollection_indexOffsetBy(
collection, expectedContents: expectedContents, by: areEquivalent)
var allIndices = indicesByIndexAfter
allIndices.append(collection.endIndex)
@@ -123,44 +183,12 @@ public func _checkBidirectionalCollection<C: BidirectionalCollection, S: Sequenc
let i = range.lowerBound
let j = range.upperBound
// Check `index(_,offsetBy:)` with negative offsets
let a = collection.index(allIndices[j], offsetBy: i - j)
expectEqual(a, allIndices[i])
if i < expectedContents.count {
expectEquivalent(
collection[a], expectedContents[i],
by: areEquivalent)
}
// Check `distance(from:to:)` with decreasing indices
let d = collection.distance(from: allIndices[j], to: allIndices[i])
expectEqual(d, i - j)
// Check slicing.
let slice = collection[allIndices[i] ..< allIndices[j]]
expectEqualElements(slice._indicesByIndexBefore(), allIndices[i ..< j])
expectEqualElements(slice._indicesByFormIndexBefore(), allIndices[i ..< j])
}
// Check `index(_,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 min = -i - (limit <= i ? 2 : 0)
withEvery("delta", in: stride(from: 0, through: min, by: -1)) { delta in
let actual = collection.index(
allIndices[i],
offsetBy: delta,
limitedBy: allIndices[limit])
let j = i + delta
let expected = i < limit || j >= limit ? allIndices[j] : nil
expectEqual(actual, expected)
}
}
}
// Check the Indices associated type
if C.self != C.Indices.self && C.self != DefaultIndices<C>.self {
TestContext.current.withTrace("Indices") {
@@ -107,10 +107,10 @@ public protocol DictionaryAPIExtras: DictionaryAPIChecker {
uniqueKeysWithValues keysAndValues: S
) where S.Element == Element
init<Keys: Sequence, Values: Sequence>(
uniqueKeys keys: Keys,
values: Values
) where Keys.Element == Key, Values.Element == Value
// init<Keys: Sequence, Values: Sequence>(
// uniqueKeys keys: Keys,
// values: Values
// ) where Keys.Element == Key, Values.Element == Value
init<S: Sequence>(
_ keysAndValues: S,
@@ -38,9 +38,9 @@ extension LifetimeTracker {
keyTransform: (C.Element) -> Key,
valueTransform: (C.Element) -> Value
) -> PersistentDictionary<LifetimeTracked<Key>, LifetimeTracked<Value>> {
PersistentDictionary(
uniqueKeys: instances(for: items, by: keyTransform),
values: instances(for: items, by: valueTransform))
let keys = instances(for: items, by: keyTransform)
let values = instances(for: items, by: valueTransform)
return PersistentDictionary(uniqueKeysWithValues: zip(keys, values))
}
func persistentDictionary<Value, C: Collection>(
@@ -48,9 +48,9 @@ extension LifetimeTracker {
by valueTransform: (C.Element) -> Value
) -> PersistentDictionary<LifetimeTracked<C.Element>, LifetimeTracked<Value>>
where C.Element: Hashable {
PersistentDictionary(
uniqueKeys: instances(for: keys),
values: instances(for: keys, by: valueTransform))
let k = instances(for: keys)
let v = instances(for: keys, by: valueTransform)
return PersistentDictionary(uniqueKeysWithValues: zip(k, v))
}
func dictionary<Key, Value, C: Collection>(
@@ -254,14 +254,20 @@ class PersistentDictionaryTests: CollectionTestCase {
withEachFixture { fixture in
withLifetimeTracking { tracker in
let (d, ref) = tracker.persistentDictionary(for: fixture)
checkBidirectionalCollection(d, expectedContents: ref, by: ==)
checkCollection(d, expectedContents: ref, by: ==)
_checkBidirectionalCollection_indexOffsetBy(
d, expectedContents: ref, by: ==)
}
}
}
func test_BidirectionalCollection_random100() {
let d = PersistentDictionary<Int, Int>(uniqueKeys: 0 ..< 100, values: 0 ..< 100)
checkBidirectionalCollection(d, expectedContents: Array(d), by: ==)
let d = PersistentDictionary<Int, Int>(
uniqueKeysWithValues: (0 ..< 100).map { ($0, $0) })
let ref = Array(d)
checkCollection(d, expectedContents: ref, by: ==)
_checkBidirectionalCollection_indexOffsetBy(
d, expectedContents: ref, by: ==)
}
#if swift(>=5.6)
@@ -18,10 +18,10 @@ class PersistentDictionaryKeysTests: CollectionTestCase {
withEachFixture { fixture in
withLifetimeTracking { tracker in
let (d, ref) = tracker.persistentDictionary(for: fixture)
checkBidirectionalCollection(
d.keys,
expectedContents: ref.map { $0.key },
by: ==)
let k = ref.map { $0.key }
checkCollection(d.keys, expectedContents: k, by: ==)
_checkBidirectionalCollection_indexOffsetBy(
d.keys, expectedContents: k, by: ==)
}
}
}
@@ -18,10 +18,10 @@ class PersistentDictionaryValuesTests: CollectionTestCase {
withEachFixture { fixture in
withLifetimeTracking { tracker in
let (d, ref) = tracker.persistentDictionary(for: fixture)
checkBidirectionalCollection(
d.values,
expectedContents: ref.map { $0.value },
by: ==)
let v = ref.map { $0.value }
checkCollection(d.values, expectedContents: v, by: ==)
_checkBidirectionalCollection_indexOffsetBy(
d.values, expectedContents: v, by: ==)
}
}
}
@@ -26,14 +26,19 @@ class PersistentSetTests: CollectionTestCase {
withEachFixture { fixture in
withLifetimeTracking { tracker in
let (set, ref) = tracker.persistentSet(for: fixture)
checkBidirectionalCollection(set, expectedContents: ref, by: ==)
checkCollection(set, expectedContents: ref, by: ==)
_checkBidirectionalCollection_indexOffsetBy(
set, expectedContents: ref, by: ==)
}
}
}
func test_BidirectionalCollection_random100() {
let s = PersistentSet<Int>(0 ..< 100)
checkBidirectionalCollection(s, expectedContents: Array(s))
let ref = Array(s)
checkCollection(s, expectedContents: ref)
_checkBidirectionalCollection_indexOffsetBy(
s, expectedContents: ref, by: ==)
}
func test_basics() {
@@ -25,7 +25,8 @@ extension LifetimeTracker {
let k = Array(keys)
let keys = self.instances(for: k)
let values = self.instances(for: k.map { $0 + 100 })
let dictionary = PersistentDictionary(uniqueKeys: keys, values: values)
let dictionary = PersistentDictionary(
uniqueKeysWithValues: zip(keys, values))
return (dictionary, keys, values)
}
}