Skip to content

Commit 3ddfff9

Browse files
committed
add CollectionDifference.inverse() and test coverage
1 parent 88d3677 commit 3ddfff9

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

stdlib/public/core/CollectionDifference.swift

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,8 @@ public struct CollectionDifference<ChangeElement> {
154154
}
155155

156156
/// Internal initializer for use by algorithms that cannot produce invalid
157-
/// collections of changes. These include the Myers' diff algorithm and
158-
/// the move inferencer.
157+
/// collections of changes. These include the Myers' diff algorithm,
158+
/// self.inverse(), and the move inferencer.
159159
///
160160
/// If parameter validity cannot be guaranteed by the caller then
161161
/// `CollectionDifference.init?(_:)` should be used instead.
@@ -200,6 +200,17 @@ public struct CollectionDifference<ChangeElement> {
200200
removals = Array(sortedChanges[0..<firstInsertIndex])
201201
insertions = Array(sortedChanges[firstInsertIndex..<sortedChanges.count])
202202
}
203+
204+
public func inverse() -> Self {
205+
return CollectionDifference(_validatedChanges: self.map { c in
206+
switch c {
207+
case .remove(let o, let e, let a):
208+
return .insert(offset: o, element: e, associatedWith: a)
209+
case .insert(let o, let e, let a):
210+
return .remove(offset: o, element: e, associatedWith: a)
211+
}
212+
})
213+
}
203214
}
204215

205216
/// A CollectionDifference is itself a Collection.

test/stdlib/Diffing.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,7 @@ if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, * ) {
626626

627627
// Validate application
628628
expectEqual(b, a.applying(diff)!)
629+
expectEqual(a, b.applying(diff.inverse())!)
629630
}}}}}}
630631
}
631632

@@ -645,13 +646,15 @@ if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, * ) {
645646
expectNotNil(applied)
646647
if let applied = applied {
647648
expectEqual(b, applied)
649+
expectEqual(a, applied.applying(d.inverse()))
648650
if (b != applied) {
649651
print("""
650652
// repro:
651653
let a = \(a)
652654
let b = \(b)
653655
let d = b.difference(from: a)
654656
expectEqual(b, a.applying(d))
657+
expectEqual(a, applied.applying(d.inverse()))
655658
""")
656659
break
657660
}

0 commit comments

Comments
 (0)