|
| 1 | +/* |
| 2 | + This source file is part of the Swift.org open source project |
| 3 | + |
| 4 | + Copyright (c) 2022 Apple Inc. and the Swift project authors |
| 5 | + Licensed under Apache License v2.0 with Runtime Library Exception |
| 6 | + |
| 7 | + See https://swift.org/LICENSE.txt for license information |
| 8 | + See https://swift.org/CONTRIBUTORS.txt for Swift project authors |
| 9 | +*/ |
| 10 | + |
| 11 | +import Foundation |
| 12 | + |
| 13 | +/// A collection of sparse segments that describe the subsequences that are common or different between two collections. |
| 14 | +struct CollectionChanges { |
| 15 | + /// The segments of common elements, removed elements, and inserted elements. |
| 16 | + let segments: [Segment] |
| 17 | + |
| 18 | + /// A single segment that describe a number of elements that are either common between both collections, or that are removed or inserted in the second collection. |
| 19 | + struct Segment: Equatable { |
| 20 | + var kind: Kind |
| 21 | + var count: Int |
| 22 | + |
| 23 | + enum Kind: Equatable { |
| 24 | + /// These elements are common between both collections. |
| 25 | + case common |
| 26 | + /// These elements are removed from the first collection to produce the second collection. |
| 27 | + case remove |
| 28 | + /// These elements are inserted in the first collection to produce the second collection. |
| 29 | + case insert |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + /// Creates a new collection changes value from the differences between to collections. |
| 34 | + /// |
| 35 | + /// - Parameters: |
| 36 | + /// - from: The collection that the base is compared to. |
| 37 | + /// - to: The base collection. |
| 38 | + /// - areEquivalent: A closure that returns a Boolean value indicating whether two elements are equivalent. |
| 39 | + init<C>(from: C, to: C, by areEquivalent: (C.Element, C.Element) -> Bool = (==)) where C: BidirectionalCollection, C.Element: Hashable { |
| 40 | + guard !from.isEmpty else { |
| 41 | + segments = [.init(kind: .insert, count: to.count)] |
| 42 | + return |
| 43 | + } |
| 44 | + guard !to.isEmpty else { |
| 45 | + segments = [.init(kind: .remove, count: from.count)] |
| 46 | + return |
| 47 | + } |
| 48 | + |
| 49 | + var changes = ChangeSegmentBuilder(originalCount: from.count) |
| 50 | + // The `CollectionDifference` enumeration order is documented; first removals in descending order then insertions in ascending order. |
| 51 | + // https://github.com/apple/swift/blob/main/stdlib/public/core/CollectionDifference.swift#L216-L235 |
| 52 | + for change in to.difference(from: from, by: areEquivalent) { |
| 53 | + switch change { |
| 54 | + case .remove(let offset, _, _): |
| 55 | + changes.remove(at: offset) |
| 56 | + case .insert(let offset, _, _): |
| 57 | + changes.insert(at: offset) |
| 58 | + } |
| 59 | + } |
| 60 | + segments = changes.segments |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +/// A builder that applies collection differences to construct an array of ``Segment`` values. |
| 65 | +/// |
| 66 | +/// - Important: |
| 67 | +/// Removals need to be applied in reverse order. All removals need to be applied before applying any insertions. Insertions need to be applied in order. |
| 68 | +private struct ChangeSegmentBuilder { |
| 69 | + typealias Segment = CollectionChanges.Segment |
| 70 | + |
| 71 | + private(set) var segments: [Segment] |
| 72 | + |
| 73 | + private var insertStartIndex = 0 |
| 74 | + private var insertStartOffset = 0 |
| 75 | + |
| 76 | + init(originalCount: Int) { |
| 77 | + self.segments = [ Segment(kind: .common, count: originalCount) ] |
| 78 | + } |
| 79 | + |
| 80 | + mutating func remove(at removalIndex: Int) { |
| 81 | + // Removals are applied in reverse order. When the first removal is applied, the only segment is the 'common' count. |
| 82 | + // |
| 83 | + // Each removal can be either be at the start of the segment, middle of the segment, or end of the segment. |
| 84 | + // - After removing from the start of the segment there can be no more removals (since those indices would be in ascending order). |
| 85 | + // - After removing from the middle, the 'common' segment is split in two with a 'remove' segment in between. |
| 86 | + // Since the removal has to be at a lower index, it can only be applied to the split 'original' segment. |
| 87 | + // - After removing from the end, the 'common' segment is made shorter and a new 'remove' segment is added after it. |
| 88 | + // Since the removal has to be at a lower index, it can only be applied to the shortened 'common' segment. |
| 89 | + // |
| 90 | + // This process repeats, meaning that every removal is always applied to the first segment. |
| 91 | + let segment = segments[0] |
| 92 | + assert(segment.kind == .common && removalIndex < segment.count, """ |
| 93 | + The first segment should always be a 'common' segment (was \(segment.kind)) and (0 ..< \(segment.count)) should always contain the removal index (\(removalIndex)). |
| 94 | + If it's not, then that's means that the remove operations wasn't performed in reverse order. |
| 95 | + """) |
| 96 | + |
| 97 | + if removalIndex == 0 { |
| 98 | + // Removing at the start of the segment |
| 99 | + if segment.count == 1 { |
| 100 | + segments.remove(at: 0) |
| 101 | + } else { |
| 102 | + segments[0].count -= 1 |
| 103 | + } |
| 104 | + |
| 105 | + if segments.first?.kind == .remove { |
| 106 | + segments[0].count += 1 |
| 107 | + } else { |
| 108 | + segments.insert(Segment(kind: .remove, count: 1), at: 0) |
| 109 | + } |
| 110 | + } |
| 111 | + else if removalIndex == segment.count - 1 { |
| 112 | + // Removing at end of segment |
| 113 | + segments[0].count -= 1 |
| 114 | + |
| 115 | + if segments.count > 1, segments[1].kind == .remove { |
| 116 | + segments[1].count += 1 |
| 117 | + } else { |
| 118 | + // Insert at `endIndex` is equivalent to `append()` |
| 119 | + segments.insert(Segment(kind: .remove, count: 1), at: 1) |
| 120 | + } |
| 121 | + } else { |
| 122 | + // Removal within segment |
| 123 | + let lowerSegmentCount = removalIndex |
| 124 | + let higherSegmentCount = segment.count - lowerSegmentCount - 1 // the 1 is for the removed element |
| 125 | + |
| 126 | + // Split the segment in two with a new removal segment in-between. |
| 127 | + segments[0...0] = [ |
| 128 | + Segment(kind: .common, count: lowerSegmentCount), |
| 129 | + Segment(kind: .remove, count: 1), |
| 130 | + Segment(kind: .common, count: higherSegmentCount), |
| 131 | + ] |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + private func findSegment(toInsertAt index: Int) -> (segment: Segment, startOffset: Int, segmentIndex: Int)? { |
| 136 | + // Insertions are applied in order. This means that we can start with the previous offset and index. |
| 137 | + var offset = insertStartOffset |
| 138 | + for segmentIndex in insertStartIndex ..< segments.count { |
| 139 | + let segment = segments[segmentIndex] |
| 140 | + if segment.kind == .remove { |
| 141 | + continue |
| 142 | + } |
| 143 | + |
| 144 | + if index <= offset + segment.count { |
| 145 | + return (segment, offset, segmentIndex) |
| 146 | + } |
| 147 | + offset += segment.count |
| 148 | + } |
| 149 | + return nil |
| 150 | + } |
| 151 | + |
| 152 | + mutating func insert(at insertIndex: Int) { |
| 153 | + guard let (segment, startOffset, segmentIndex) = findSegment(toInsertAt: insertIndex) else { |
| 154 | + assert(segments.count == 1 && segments[0].kind == .remove, """ |
| 155 | + The only case when a segment can't be found in the loop is if the only segment is a 'remove' segment. |
| 156 | + This happens when all the 'common' elements are removed (meaning that the 'from' and 'to' values have nothing in common. |
| 157 | + """) |
| 158 | + |
| 159 | + segments.append(Segment(kind: .insert, count: 1)) |
| 160 | + return |
| 161 | + } |
| 162 | + assert(segment.kind != .remove) |
| 163 | + |
| 164 | + insertStartOffset = startOffset |
| 165 | + insertStartIndex = segmentIndex |
| 166 | + |
| 167 | + guard segment.kind != .insert else { |
| 168 | + segments[segmentIndex].count += 1 |
| 169 | + return |
| 170 | + } |
| 171 | + assert(segment.kind == .common) |
| 172 | + |
| 173 | + if insertIndex == startOffset { |
| 174 | + // Insert at start of segment |
| 175 | + segments.insert(Segment(kind: .insert, count: 1), at: segmentIndex) |
| 176 | + } else if insertIndex == startOffset + segment.count { |
| 177 | + // Insert at end of segment |
| 178 | + let insertSegmentIndex = segmentIndex + 1 |
| 179 | + |
| 180 | + // If this is the last segment, append a new 'insert' segment |
| 181 | + guard insertSegmentIndex < segments.count else { |
| 182 | + segments.append(Segment(kind: .insert, count: 1)) |
| 183 | + return |
| 184 | + } |
| 185 | + |
| 186 | + switch segments[insertSegmentIndex].kind { |
| 187 | + case .insert: |
| 188 | + assertionFailure("Inserts are processed from low to high. There shouldn't be another 'insert' segment after 'segmentIndex'.") |
| 189 | + |
| 190 | + case .common: |
| 191 | + // If the next segment is a 'common' segment, insert a new 'insert' segment before it |
| 192 | + segments.insert(Segment(kind: .insert, count: 1), at: insertSegmentIndex) |
| 193 | + |
| 194 | + case .remove: |
| 195 | + // If the next segment is a 'remove' segment, skip over it so that insertions are always after removals. |
| 196 | + segments.insert(Segment(kind: .insert, count: 1), at: insertSegmentIndex + 1) |
| 197 | + |
| 198 | + assert(insertSegmentIndex + 2 == segments.count || segments[insertSegmentIndex + 2].kind == .common, |
| 199 | + "If there's a segment after the remove segment, that is a segment of 'common' characters.") |
| 200 | + } |
| 201 | + } else { |
| 202 | + // Insert within segment |
| 203 | + let lowerSegmentCount = insertIndex - startOffset |
| 204 | + let higherSegmentCount = segment.count - lowerSegmentCount // nothing to add |
| 205 | + |
| 206 | + // Split the segment in two with a new insertion segment in-between. |
| 207 | + segments[segmentIndex...segmentIndex] = [ |
| 208 | + Segment(kind: .common, count: lowerSegmentCount), |
| 209 | + Segment(kind: .insert, count: 1), |
| 210 | + Segment(kind: .common, count: higherSegmentCount), |
| 211 | + ] |
| 212 | + } |
| 213 | + } |
| 214 | +} |
0 commit comments