1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2015 - 2019 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection of insertions and removals that describe the difference
/// between two ordered collection states.
@available(SwiftStdlib 5.1, *)
public struct CollectionDifference<ChangeElement> {
/// A single change to a collection.
@frozen
public enum Change {
/// An insertion.
///
/// The `offset` value is the offset of the inserted element in the final
/// state of the collection after the difference is fully applied.
/// A non-`nil` `associatedWith` value is the offset of the complementary
/// change.
case insert(offset: Int, element: ChangeElement, associatedWith: Int?)
/// A removal.
///
/// The `offset` value is the offset of the element to be removed in the
/// original state of the collection. A non-`nil` `associatedWith` value is
/// the offset of the complementary change.
case remove(offset: Int, element: ChangeElement, associatedWith: Int?)
// Internal common field accessors
internal var _offset: Int {
get {
switch self {
case .insert(offset: let o, element: _, associatedWith: _):
return o
case .remove(offset: let o, element: _, associatedWith: _):
return o
}
}
}
internal var _element: ChangeElement {
get {
switch self {
case .insert(offset: _, element: let e, associatedWith: _):
return e
case .remove(offset: _, element: let e, associatedWith: _):
return e
}
}
}
internal var _associatedOffset: Int? {
get {
switch self {
case .insert(offset: _, element: _, associatedWith: let o):
return o
case .remove(offset: _, element: _, associatedWith: let o):
return o
}
}
}
}
/// The insertions contained by this difference, from lowest offset to
/// highest.
public let insertions: [Change]
/// The removals contained by this difference, from lowest offset to highest.
public let removals: [Change]
/// Creates a new collection difference from a collection of changes.
///
/// To find the difference between two collections, use the
/// `difference(from:)` method declared on the `BidirectionalCollection`
/// protocol.
///
/// The collection of changes passed as `changes` must meet these
/// requirements:
///
/// - All insertion offsets are unique
/// - All removal offsets are unique
/// - All associations between insertions and removals are symmetric
///
/// - Parameter changes: A collection of changes that represent a transition
/// between two states.
///
/// - Complexity: O(*n* * log(*n*)), where *n* is the length of the
/// parameter.
public init?<Changes: Collection>(
_ changes: Changes
) where Changes.Element == Change {
guard CollectionDifference<ChangeElement>._validateChanges(changes) else {
return nil
}
self.init(_validatedChanges: changes)
}
/// Internal initializer for use by algorithms that cannot produce invalid
/// collections of changes. These include the Myers' diff algorithm,
/// self.inverse(), and the move inferencer.
///
/// If parameter validity cannot be guaranteed by the caller then
/// `CollectionDifference.init?(_:)` should be used instead.
///
/// - Parameter c: A valid collection of changes that represent a transition
/// between two states.
///
/// - Complexity: O(*n* * log(*n*)), where *n* is the length of the
/// parameter.
internal init<Changes: Collection>(
_validatedChanges changes: Changes
) where Changes.Element == Change {
let sortedChanges = changes.sorted { (a, b) -> Bool in
switch (a, b) {
case (.remove(_, _, _), .insert(_, _, _)):
return true
case (.insert(_, _, _), .remove(_, _, _)):
return false
default:
return a._offset < b._offset
}
}
// Find first insertion via binary search
let firstInsertIndex: Int
if sortedChanges.isEmpty {
firstInsertIndex = 0
} else {
var range = 0...sortedChanges.count
while range.lowerBound != range.upperBound {
let i = (range.lowerBound + range.upperBound) / 2
switch sortedChanges[i] {
case .insert(_, _, _):
range = range.lowerBound...i
case .remove(_, _, _):
range = (i + 1)...range.upperBound
}
}
firstInsertIndex = range.lowerBound
}
removals = Array(sortedChanges[0..<firstInsertIndex])
insertions = Array(sortedChanges[firstInsertIndex..<sortedChanges.count])
}
/// The public initializer calls this function to ensure that its parameter
/// meets the conditions set in its documentation.
///
/// - Parameter changes: a collection of `CollectionDifference.Change`
/// instances intended to represent a valid state transition for
/// `CollectionDifference`.
///
/// - Returns: whether the parameter meets the following criteria:
///
/// 1. All insertion offsets are unique
/// 2. All removal offsets are unique
/// 3. All associations between insertions and removals are symmetric
///
/// Complexity: O(`changes.count`)
private static func _validateChanges<Changes: Collection>(
_ changes : Changes
) -> Bool where Changes.Element == Change {
if changes.isEmpty { return true }
var insertAssocToOffset = Dictionary<Int,Int>()
var removeOffsetToAssoc = Dictionary<Int,Int>()
var insertOffset = Set<Int>()
var removeOffset = Set<Int>()
for change in changes {
let offset = change._offset
if offset < 0 { return false }
switch change {
case .remove(_, _, _):
if removeOffset.contains(offset) { return false }
removeOffset.insert(offset)
case .insert(_, _, _):
if insertOffset.contains(offset) { return false }
insertOffset.insert(offset)
}
if let assoc = change._associatedOffset {
if assoc < 0 { return false }
switch change {
case .remove(_, _, _):
if removeOffsetToAssoc[offset] != nil { return false }
removeOffsetToAssoc[offset] = assoc
case .insert(_, _, _):
if insertAssocToOffset[assoc] != nil { return false }
insertAssocToOffset[assoc] = offset
}
}
}
return removeOffsetToAssoc == insertAssocToOffset
}
public func inverse() -> Self {
return CollectionDifference(_validatedChanges: self.map { c in
switch c {
case .remove(let o, let e, let a):
return .insert(offset: o, element: e, associatedWith: a)
case .insert(let o, let e, let a):
return .remove(offset: o, element: e, associatedWith: a)
}
})
}
}
/// A CollectionDifference is itself a Collection.
///
/// The enumeration order of `Change` elements is:
///
/// 1. `.remove`s, from highest `offset` to lowest
/// 2. `.insert`s, from lowest `offset` to highest
///
/// This guarantees that applicators on compatible base states are safe when
/// written in the form:
///
/// ```
/// for c in diff {
/// switch c {
/// case .remove(offset: let o, element: _, associatedWith: _):
/// arr.remove(at: o)
/// case .insert(offset: let o, element: let e, associatedWith: _):
/// arr.insert(e, at: o)
/// }
/// }
/// ```
@available(SwiftStdlib 5.1, *)
extension CollectionDifference: Collection {
public typealias Element = Change
/// The position of a collection difference.
@frozen
public struct Index {
// Opaque index type is isomorphic to Int
@usableFromInline
internal let _offset: Int
internal init(_offset offset: Int) {
_offset = offset
}
}
public var startIndex: Index {
return Index(_offset: 0)
}
public var endIndex: Index {
return Index(_offset: removals.count + insertions.count)
}
public func index(after index: Index) -> Index {
return Index(_offset: index._offset + 1)
}
public subscript(position: Index) -> Element {
if position._offset < removals.count {
return removals[removals.count - (position._offset + 1)]
}
return insertions[position._offset - removals.count]
}
public func index(before index: Index) -> Index {
return Index(_offset: index._offset - 1)
}
public func formIndex(_ index: inout Index, offsetBy distance: Int) {
index = Index(_offset: index._offset + distance)
}
public func distance(from start: Index, to end: Index) -> Int {
return end._offset - start._offset
}
}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference.Index: Equatable {
@inlinable
public static func == (
lhs: CollectionDifference.Index,
rhs: CollectionDifference.Index
) -> Bool {
return lhs._offset == rhs._offset
}
}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference.Index: Comparable {
@inlinable
public static func < (
lhs: CollectionDifference.Index,
rhs: CollectionDifference.Index
) -> Bool {
return lhs._offset < rhs._offset
}
}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference.Index: Hashable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(_offset)
}
}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference.Change: Equatable where ChangeElement: Equatable {}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference: Equatable where ChangeElement: Equatable {}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference.Change: Hashable where ChangeElement: Hashable {}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference: Hashable where ChangeElement: Hashable {}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference where ChangeElement: Hashable {
/// Returns a new collection difference with associations between individual
/// elements that have been removed and inserted only once.
///
/// - Returns: A collection difference with all possible moves inferred.
///
/// - Complexity: O(*n*) where *n* is the number of collection differences.
public func inferringMoves() -> CollectionDifference<ChangeElement> {
let uniqueRemovals: [ChangeElement:Int?] = {
var result = [ChangeElement:Int?](minimumCapacity: Swift.min(removals.count, insertions.count))
for removal in removals {
let element = removal._element
if result[element] != .none {
result[element] = .some(.none)
} else {
result[element] = .some(removal._offset)
}
}
return result.filter { (_, v) -> Bool in v != .none }
}()
let uniqueInsertions: [ChangeElement:Int?] = {
var result = [ChangeElement:Int?](minimumCapacity: Swift.min(removals.count, insertions.count))
for insertion in insertions {
let element = insertion._element
if result[element] != .none {
result[element] = .some(.none)
} else {
result[element] = .some(insertion._offset)
}
}
return result.filter { (_, v) -> Bool in v != .none }
}()
return CollectionDifference(_validatedChanges: map({ (change: Change) -> Change in
switch change {
case .remove(offset: let offset, element: let element, associatedWith: _):
if uniqueRemovals[element] == nil {
return change
}
if let assoc = uniqueInsertions[element] {
return .remove(offset: offset, element: element, associatedWith: assoc)
}
case .insert(offset: let offset, element: let element, associatedWith: _):
if uniqueInsertions[element] == nil {
return change
}
if let assoc = uniqueRemovals[element] {
return .insert(offset: offset, element: element, associatedWith: assoc)
}
}
return change
}))
}
}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference.Change: Codable where ChangeElement: Codable {
private enum _CodingKeys: String, CodingKey {
case offset
case element
case associatedOffset
case isRemove
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: _CodingKeys.self)
let offset = try values.decode(Int.self, forKey: .offset)
let element = try values.decode(ChangeElement.self, forKey: .element)
let associatedOffset = try values.decode(Int?.self, forKey: .associatedOffset)
let isRemove = try values.decode(Bool.self, forKey: .isRemove)
if isRemove {
self = .remove(offset: offset, element: element, associatedWith: associatedOffset)
} else {
self = .insert(offset: offset, element: element, associatedWith: associatedOffset)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: _CodingKeys.self)
switch self {
case .remove(_, _, _):
try container.encode(true, forKey: .isRemove)
case .insert(_, _, _):
try container.encode(false, forKey: .isRemove)
}
try container.encode(_offset, forKey: .offset)
try container.encode(_element, forKey: .element)
try container.encode(_associatedOffset, forKey: .associatedOffset)
}
}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference: Codable where ChangeElement: Codable {}
@available(SwiftStdlib 5.1, *)
extension CollectionDifference: Sendable where ChangeElement: Sendable { }
@available(SwiftStdlib 5.1, *)
extension CollectionDifference.Change: Sendable where ChangeElement: Sendable { }
@available(SwiftStdlib 5.1, *)
extension CollectionDifference.Index: Sendable where ChangeElement: Sendable { }
|