206 lines
7.9 KiB
Swift
206 lines
7.9 KiB
Swift
import Foundation
|
|
|
|
public enum LineDiff {
|
|
/// Largest LCS matrix built in one go (4M cells); bigger regions are split on unique anchor lines.
|
|
public static let maxCells = 4_000_000
|
|
|
|
/// "" is zero lines, and one trailing "\n" is dropped.
|
|
public static func lines(_ text: String) -> [String] {
|
|
if text.isEmpty { return [] }
|
|
return droppingTrailingNewline(text).components(separatedBy: "\n")
|
|
}
|
|
|
|
/// Drops one final "\n". `hasSuffix("\n")` misses it after a "\r", where "\r\n" is one Character.
|
|
static func droppingTrailingNewline(_ text: String) -> String {
|
|
text.utf8.last == 10 ? String(decoding: text.utf8.dropLast(), as: UTF8.self) : text
|
|
}
|
|
|
|
/// Line-based LCS diff of two texts into rows, both sides and aligned split rows.
|
|
///
|
|
/// On a tie the DP takes the deletion before the addition; flipping that reorders
|
|
/// removed and added lines in every view.
|
|
public static func build(original: String, updated: String, status: GitStatus? = nil) -> Diff {
|
|
let a = lines(original)
|
|
let b = lines(updated)
|
|
let (ia, ib) = intern(a, b)
|
|
var ops: [Op] = []
|
|
ops.reserveCapacity(max(a.count, b.count))
|
|
region(ia, ib, 0, ia.count, 0, ib.count, &ops)
|
|
|
|
var rows: [DiffRow] = []
|
|
rows.reserveCapacity(ops.count)
|
|
var removedLines = Set<Int>(), addedLines = Set<Int>()
|
|
for op in ops {
|
|
switch op {
|
|
case let .same(i, j): rows.append(DiffRow(sign: .same, oldNo: i + 1, newNo: j + 1, text: a[i]))
|
|
case let .del(i):
|
|
rows.append(DiffRow(sign: .removed, oldNo: i + 1, newNo: nil, text: a[i]))
|
|
removedLines.insert(i)
|
|
case let .add(j):
|
|
rows.append(DiffRow(sign: .added, oldNo: nil, newNo: j + 1, text: b[j]))
|
|
addedLines.insert(j)
|
|
}
|
|
}
|
|
let left = a.enumerated().map { SideLine(no: $0.offset + 1, text: $0.element, mark: removedLines.contains($0.offset) ? .removed : nil) }
|
|
let right = b.enumerated().map { SideLine(no: $0.offset + 1, text: $0.element, mark: addedLines.contains($0.offset) ? .added : nil) }
|
|
|
|
return Diff(
|
|
rows: rows, left: left, right: right, split: splitRows(ops, a, b),
|
|
added: addedLines.count, removed: removedLines.count,
|
|
isDeletedFile: status == .deleted, isAddedFile: status == .added,
|
|
original: original, updated: updated
|
|
)
|
|
}
|
|
|
|
private enum Op {
|
|
case same(Int, Int)
|
|
case del(Int)
|
|
case add(Int)
|
|
}
|
|
|
|
/// Maps every distinct line to an integer so the DP compares ints, not strings.
|
|
private static func intern(_ a: [String], _ b: [String]) -> ([Int], [Int]) {
|
|
var ids: [String: Int] = [:]
|
|
func id(_ line: String) -> Int {
|
|
if let known = ids[line] { return known }
|
|
let next = ids.count
|
|
ids[line] = next
|
|
return next
|
|
}
|
|
return (a.map(id), b.map(id))
|
|
}
|
|
|
|
/// Removed and added runs between two unchanged lines pair up side by side.
|
|
private static func splitRows(_ ops: [Op], _ a: [String], _ b: [String]) -> [SplitRow] {
|
|
var split: [SplitRow] = []
|
|
var removed: [SideLine] = [], added: [SideLine] = []
|
|
func flush() {
|
|
for k in 0..<max(removed.count, added.count) {
|
|
split.append(SplitRow(left: k < removed.count ? removed[k] : nil, right: k < added.count ? added[k] : nil))
|
|
}
|
|
removed.removeAll(keepingCapacity: true)
|
|
added.removeAll(keepingCapacity: true)
|
|
}
|
|
for op in ops {
|
|
switch op {
|
|
case let .same(i, j):
|
|
flush()
|
|
split.append(SplitRow(left: SideLine(no: i + 1, text: a[i]), right: SideLine(no: j + 1, text: b[j])))
|
|
case let .del(i): removed.append(SideLine(no: i + 1, text: a[i], mark: .removed))
|
|
case let .add(j): added.append(SideLine(no: j + 1, text: b[j], mark: .added))
|
|
}
|
|
}
|
|
flush()
|
|
return split
|
|
}
|
|
|
|
private static func region(_ a: [Int], _ b: [Int], _ a0In: Int, _ a1In: Int, _ b0In: Int, _ b1In: Int, _ ops: inout [Op]) {
|
|
var a0 = a0In, a1 = a1In, b0 = b0In, b1 = b1In
|
|
while a0 < a1 && b0 < b1 && a[a0] == b[b0] {
|
|
ops.append(.same(a0, b0))
|
|
a0 += 1
|
|
b0 += 1
|
|
}
|
|
var tail: [Op] = []
|
|
while a1 > a0 && b1 > b0 && a[a1 - 1] == b[b1 - 1] {
|
|
a1 -= 1
|
|
b1 -= 1
|
|
tail.append(.same(a1, b1))
|
|
}
|
|
|
|
let n = a1 - a0, m = b1 - b0
|
|
func replaceAll() {
|
|
for i in a0..<a1 { ops.append(.del(i)) }
|
|
for j in b0..<b1 { ops.append(.add(j)) }
|
|
}
|
|
|
|
if n == 0 || m == 0 {
|
|
replaceAll()
|
|
} else if n * m <= maxCells {
|
|
dynamicProgram(a, b, a0, a1, b0, b1, &ops)
|
|
} else {
|
|
let pins = anchors(a, b, a0, a1, b0, b1)
|
|
if pins.isEmpty {
|
|
replaceAll()
|
|
} else {
|
|
var ai = a0, bi = b0
|
|
for (ax, bx) in pins {
|
|
region(a, b, ai, ax, bi, bx, &ops)
|
|
ops.append(.same(ax, bx))
|
|
ai = ax + 1
|
|
bi = bx + 1
|
|
}
|
|
region(a, b, ai, a1, bi, b1, &ops)
|
|
}
|
|
}
|
|
ops.append(contentsOf: tail.reversed())
|
|
}
|
|
|
|
private static func dynamicProgram(_ a: [Int], _ b: [Int], _ a0: Int, _ a1: Int, _ b0: Int, _ b1: Int, _ ops: inout [Op]) {
|
|
let n = a1 - a0, m = b1 - b0
|
|
let width = m + 1
|
|
var dp = [Int32](repeating: 0, count: (n + 1) * width)
|
|
for i in stride(from: n - 1, through: 0, by: -1) {
|
|
for j in stride(from: m - 1, through: 0, by: -1) {
|
|
dp[i * width + j] = a[a0 + i] == b[b0 + j]
|
|
? dp[(i + 1) * width + j + 1] + 1
|
|
: max(dp[(i + 1) * width + j], dp[i * width + j + 1])
|
|
}
|
|
}
|
|
var i = 0, j = 0
|
|
while i < n && j < m {
|
|
if a[a0 + i] == b[b0 + j] {
|
|
ops.append(.same(a0 + i, b0 + j))
|
|
i += 1
|
|
j += 1
|
|
} else if dp[(i + 1) * width + j] >= dp[i * width + j + 1] {
|
|
ops.append(.del(a0 + i))
|
|
i += 1
|
|
} else {
|
|
ops.append(.add(b0 + j))
|
|
j += 1
|
|
}
|
|
}
|
|
while i < n { ops.append(.del(a0 + i)); i += 1 }
|
|
while j < m { ops.append(.add(b0 + j)); j += 1 }
|
|
}
|
|
|
|
/// Lines that appear exactly once on each side, in an order both sides share.
|
|
private static func anchors(_ a: [Int], _ b: [Int], _ a0: Int, _ a1: Int, _ b0: Int, _ b1: Int) -> [(Int, Int)] {
|
|
var countA: [Int: Int] = [:], countB: [Int: Int] = [:], atB: [Int: Int] = [:]
|
|
for i in a0..<a1 { countA[a[i], default: 0] += 1 }
|
|
for j in b0..<b1 {
|
|
countB[b[j], default: 0] += 1
|
|
atB[b[j]] = j
|
|
}
|
|
var pairs: [(Int, Int)] = []
|
|
for i in a0..<a1 where countA[a[i]] == 1 && countB[a[i]] == 1 {
|
|
if let j = atB[a[i]] { pairs.append((i, j)) }
|
|
}
|
|
return longestRun(pairs)
|
|
}
|
|
|
|
/// Longest strictly increasing subsequence over the b-index of each pair.
|
|
private static func longestRun(_ pairs: [(Int, Int)]) -> [(Int, Int)] {
|
|
var tails: [Int] = []
|
|
var prev = [Int](repeating: -1, count: pairs.count)
|
|
for k in pairs.indices {
|
|
let v = pairs[k].1
|
|
var lo = 0, hi = tails.count
|
|
while lo < hi {
|
|
let mid = (lo + hi) / 2
|
|
if pairs[tails[mid]].1 < v { lo = mid + 1 } else { hi = mid }
|
|
}
|
|
prev[k] = lo > 0 ? tails[lo - 1] : -1
|
|
if lo == tails.count { tails.append(k) } else { tails[lo] = k }
|
|
}
|
|
var out: [(Int, Int)] = []
|
|
var k = tails.last ?? -1
|
|
while k >= 0 {
|
|
out.append(pairs[k])
|
|
k = prev[k]
|
|
}
|
|
return out.reversed()
|
|
}
|
|
}
|