Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,54 @@ public struct FuzzyMatch: Equatable, Sendable {
public let matchedIndices: [Int]
}

/// A query split into characters and folded once, so ranking a catalog against it does not redo
/// that work for every candidate.
public struct FuzzyQuery: Sendable {
public let text: String
fileprivate let characters: [Character]
fileprivate let foldedCharacters: [String]
/// Nil when a byte of the query is not one `Character` on its own: anything at or above 0x80,
/// and a carriage return, which joins a following line feed.
fileprivate let bytes: [UInt8]?
fileprivate let foldedBytes: [UInt8]?

public init(_ text: String) {
self.text = text
characters = Array(text)
foldedCharacters = characters.map { $0.lowercased() }
let utf8 = Array(text.utf8)
if utf8.allSatisfy(FuzzyMatcher.isSingleCharacterByte) {
bytes = utf8
foldedBytes = utf8.map(FuzzyMatcher.foldedByte)
} else {
bytes = nil
foldedBytes = nil
}
}
}

/// Rows the scorer reuses from one candidate to the next, so a ranking pass allocates them once.
public struct FuzzyScratch {
fileprivate var previousMatch: [Int] = []
fileprivate var previousBest: [Int] = []
fileprivate var currentMatch: [Int] = []
fileprivate var currentBest: [Int] = []
fileprivate var bonuses: [Int] = []

public init() {}

fileprivate mutating func reserve(_ count: Int) {
guard bonuses.count < count else { return }
// Every cell a candidate reads is written first, so the starting value does not matter.
let row = [Int](repeating: 0, count: count)
previousMatch = row
previousBest = row
currentMatch = row
currentBest = row
bonuses = row
}
}

public enum FuzzyMatcher {
private enum Weight {
static let match = 16
Expand Down Expand Up @@ -32,20 +80,69 @@ public enum FuzzyMatcher {

public static func match(query: String, candidate: String) -> FuzzyMatch? {
let queryChars = Array(query)
let candidateChars = Array(candidate)
return characterMatch(
queryChars: queryChars,
foldedQuery: queryChars.map { $0.lowercased() },
candidateChars: Array(candidate),
withIndices: true
)
}

/// The score `match(query:candidate:)` gives, without the matched indices. An ASCII query and
/// candidate are scored over their bytes with two reused rows, which is what ranking a whole
/// catalog per keystroke needs; anything else takes the `Character` path.
public static func score(_ query: FuzzyQuery, _ candidate: String, scratch: inout FuzzyScratch) -> Int? {
if let queryBytes = query.bytes, let foldedQuery = query.foldedBytes {
let outcome = candidate.utf8.withContiguousStorageIfAvailable { candidateBytes in
asciiScore(queryBytes: queryBytes, foldedQuery: foldedQuery, candidate: candidateBytes, scratch: &scratch)
}
switch outcome {
case .scored(let score)?:
return score
case .needsCharacters?:
break
case nil:
var contiguous = candidate
contiguous.makeContiguousUTF8()
return score(query, contiguous, scratch: &scratch)
}
}
return characterMatch(
queryChars: query.characters,
foldedQuery: query.foldedCharacters,
candidateChars: Array(candidate),
withIndices: false
)?.score
}

private static func characterMatch(
queryChars: [Character],
foldedQuery: [String],
candidateChars: [Character],
withIndices: Bool
) -> FuzzyMatch? {
guard !queryChars.isEmpty, !candidateChars.isEmpty, queryChars.count <= candidateChars.count else {
return nil
}
if candidateChars.count > maxScoredCandidateLength || queryChars.count > maxScoredQueryLength {
return greedyMatch(queryChars: queryChars, candidateChars: candidateChars)
return greedyMatch(queryChars: queryChars, foldedQuery: foldedQuery, candidateChars: candidateChars)
}
return optimalMatch(queryChars: queryChars, candidateChars: candidateChars)
return optimalMatch(
queryChars: queryChars,
foldedQuery: foldedQuery,
candidateChars: candidateChars,
withIndices: withIndices
)
}

private static func optimalMatch(queryChars: [Character], candidateChars: [Character]) -> FuzzyMatch? {
private static func optimalMatch(
queryChars: [Character],
foldedQuery: [String],
candidateChars: [Character],
withIndices: Bool
) -> FuzzyMatch? {
let queryLength = queryChars.count
let candidateLength = candidateChars.count
let foldedQuery = queryChars.map { $0.lowercased() }
let foldedCandidate = candidateChars.map { $0.lowercased() }
let bonuses = boundaryBonuses(for: candidateChars)

Expand Down Expand Up @@ -95,6 +192,7 @@ public enum FuzzyMatcher {

let finalScore = bestScores[queryLength * candidateLength - 1]
guard isValid(finalScore) else { return nil }
guard withIndices else { return FuzzyMatch(score: finalScore, matchedIndices: []) }

let indices = traceback(
queryChars: queryChars,
Expand Down Expand Up @@ -138,8 +236,11 @@ public enum FuzzyMatcher {
return indices
}

private static func greedyMatch(queryChars: [Character], candidateChars: [Character]) -> FuzzyMatch? {
let foldedQuery = queryChars.map { $0.lowercased() }
private static func greedyMatch(
queryChars: [Character],
foldedQuery: [String],
candidateChars: [Character]
) -> FuzzyMatch? {
var score = 0
var indices: [Int] = []
indices.reserveCapacity(queryChars.count)
Expand Down Expand Up @@ -175,6 +276,113 @@ public enum FuzzyMatcher {
return FuzzyMatch(score: score, matchedIndices: indices)
}

private enum ASCIIOutcome {
case scored(Int?)
case needsCharacters
}

// Same recurrence as `optimalMatch`, one byte per `Character`, keeping only the previous row.
private static func asciiScore(
queryBytes: [UInt8],
foldedQuery: [UInt8],
candidate: UnsafeBufferPointer<UInt8>,
scratch: inout FuzzyScratch
) -> ASCIIOutcome {
let queryLength = queryBytes.count
let candidateLength = candidate.count
var matchedPrefix = 0
for byte in candidate {
guard isSingleCharacterByte(byte) else { return .needsCharacters }
if matchedPrefix < queryLength, foldedByte(byte) == foldedQuery[matchedPrefix] {
matchedPrefix += 1
}
}
guard queryLength > 0, candidateLength > 0, queryLength <= candidateLength else { return .scored(nil) }
if candidateLength > maxScoredCandidateLength || queryLength > maxScoredQueryLength {
return .needsCharacters
}
guard matchedPrefix == queryLength else { return .scored(nil) }

scratch.reserve(candidateLength)
for index in 0..<candidateLength {
scratch.bonuses[index] = asciiBoundaryBonus(at: index, in: candidate)
}

for queryIndex in 0..<queryLength {
let foldedQueryByte = foldedQuery[queryIndex]
let queryByte = queryBytes[queryIndex]
var runningGapScore = invalid
for candidateIndex in 0..<candidateLength {
var matchScore = invalid
let candidateByte = candidate[candidateIndex]
if foldedQueryByte == foldedByte(candidateByte) {
let base: Int
if queryIndex == 0 {
base = leadingGapPenalty(for: candidateIndex) + scratch.bonuses[candidateIndex]
} else if candidateIndex > 0 {
let viaBoundary = scratch.previousBest[candidateIndex - 1] + scratch.bonuses[candidateIndex]
let viaConsecutive = scratch.previousMatch[candidateIndex - 1] + Weight.consecutive
base = max(viaBoundary, viaConsecutive)
} else {
base = invalid
}
if isValid(base) {
matchScore = base + Weight.match + (queryByte == candidateByte ? Weight.exactCase : 0)
}
}

scratch.currentMatch[candidateIndex] = matchScore

if candidateIndex > 0 {
let previousMatch = scratch.currentMatch[candidateIndex - 1]
let opened = isValid(previousMatch) ? previousMatch + Weight.gapOpen : invalid
let extended = isValid(runningGapScore) ? runningGapScore + Weight.gapExtension : invalid
runningGapScore = max(opened, extended)
} else {
runningGapScore = invalid
}

scratch.currentBest[candidateIndex] = max(matchScore, runningGapScore)
}
swap(&scratch.previousMatch, &scratch.currentMatch)
swap(&scratch.previousBest, &scratch.currentBest)
}

let finalScore = scratch.previousBest[candidateLength - 1]
return .scored(isValid(finalScore) ? finalScore : nil)
}

private static func asciiBoundaryBonus(at index: Int, in candidate: UnsafeBufferPointer<UInt8>) -> Int {
guard index > 0 else { return Weight.firstCharacter }
let previous = candidate[index - 1]
if separatorBytes.contains(previous) {
return Weight.separatorBoundary
}
if isLowercaseASCII(previous), isUppercaseASCII(candidate[index]) {
return Weight.camelBoundary
}
return 0
}

// The bytes of `separators`, in the order a table name holds them most.
private static let separatorBytes: [UInt8] = [0x5F, 0x2E, 0x20, 0x2D, 0x2F, 0x24]

fileprivate static func isSingleCharacterByte(_ byte: UInt8) -> Bool {
byte < 0x80 && byte != 0x0D
}

fileprivate static func foldedByte(_ byte: UInt8) -> UInt8 {
isUppercaseASCII(byte) ? byte | 0x20 : byte
}

private static func isUppercaseASCII(_ byte: UInt8) -> Bool {
byte >= 0x41 && byte <= 0x5A
}

private static func isLowercaseASCII(_ byte: UInt8) -> Bool {
byte >= 0x61 && byte <= 0x7A
}

private static func boundaryBonuses(for candidateChars: [Character]) -> [Int] {
candidateChars.indices.map { boundaryBonus(at: $0, in: candidateChars) }
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import Foundation

/// The first `capacity` elements of a sequence in `areInIncreasingOrder`, kept without sorting the
/// rest. Equal elements keep the order they were inserted in, so the result is the same as a stable
/// `sorted(by:).prefix(capacity)`.
public struct TopRanked<Element> {
private struct Entry {
let element: Element
let sequence: Int
}

public let capacity: Int
private let areInIncreasingOrder: (Element, Element) -> Bool
// A heap with the last kept entry at the root, so a better one replaces it in log time.
private var heap: [Entry] = []
private var inserted = 0

public init(capacity: Int, by areInIncreasingOrder: @escaping (Element, Element) -> Bool) {
self.capacity = max(0, capacity)
self.areInIncreasingOrder = areInIncreasingOrder
heap.reserveCapacity(min(self.capacity, 4_096))
}

public var count: Int { heap.count }

public var isEmpty: Bool { heap.isEmpty }

public mutating func insert(_ element: Element) {
let entry = Entry(element: element, sequence: inserted)
inserted += 1
guard capacity > 0 else { return }
if heap.count < capacity {
heap.append(entry)
siftUp(from: heap.count - 1)
} else if precedes(entry, heap[0]) {
heap[0] = entry
siftDown(from: 0)
}
}

public func sorted() -> [Element] {
heap.sorted(by: precedes).map(\.element)
}

private func precedes(_ lhs: Entry, _ rhs: Entry) -> Bool {
if areInIncreasingOrder(lhs.element, rhs.element) { return true }
if areInIncreasingOrder(rhs.element, lhs.element) { return false }
return lhs.sequence < rhs.sequence
}

private mutating func siftUp(from start: Int) {
var child = start
while child > 0 {
let parent = (child - 1) / 2
guard precedes(heap[parent], heap[child]) else { return }
heap.swapAt(parent, child)
child = parent
}
}

private mutating func siftDown(from start: Int) {
var parent = start
while true {
let left = 2 * parent + 1
guard left < heap.count else { return }
var last = left
let right = left + 1
if right < heap.count, precedes(heap[left], heap[right]) { last = right }
guard precedes(heap[parent], heap[last]) else { return }
heap.swapAt(parent, last)
parent = last
}
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Foundation
@testable import TableProUtilities
import Testing

Expand Down Expand Up @@ -151,3 +152,52 @@ struct FuzzyMatcherTests {
#expect(match?.matchedIndices.count == 80)
}
}

struct FuzzyMatcherScoreTests {
private static let longCandidate = String(repeating: "ab_", count: 341) + "cd"
private static let longQuery = String(repeating: "a", count: 65)

private static let queries: [String] = [
"u", "us", "USR", "ut", "uT", "a_b", "user", "users", "o", "ord", "ab", "cd", "b.c", "a b", "-", "$", "/",
"é", "e\u{301}", "caf", "café", "🙂", "\r\n", "\r", "\n", "K", "\u{212A}", "i", "İ", "ß", "SS",
longQuery, "xyz", " ",
]

private static let candidates: [String] = [
"users", "user_table", "UserTable", "all_users", "butter", "u_s_e_r", "orders", "order_items",
"a b-c.d/e$f_g", "camelCaseName", "ABC", "aBc", "x", "",
"caf\u{E9}", "cafe\u{301}", "emoji🙂name", "line\r\nbreak", "line\nbreak", "cr\ronly",
"Kelvin", "\u{212A}elvin", "İstanbul", "straße", "STRASSE",
longCandidate, String(repeating: "a", count: 70), String(repeating: "a", count: 1_024),
]

@Test("score equals match's score over a corpus of ASCII and Unicode text")
func scoreEqualsMatchScore() {
var scratch = FuzzyScratch()
for query in Self.queries {
let folded = FuzzyQuery(query)
for candidate in Self.candidates {
let expected = FuzzyMatcher.match(query: query, candidate: candidate)?.score
let actual = FuzzyMatcher.score(folded, candidate, scratch: &scratch)
#expect(actual == expected, "query \(query.debugDescription) candidate \(candidate.debugDescription)")
}
}
}

@Test("A bridged string scores the same as a native one")
func bridgedCandidateScoresTheSame() {
var scratch = FuzzyScratch()
let bridged = NSString(string: "order_items") as String
let query = FuzzyQuery("oi")
#expect(FuzzyMatcher.score(query, bridged, scratch: &scratch) == FuzzyMatcher.match(query: "oi", candidate: "order_items")?.score)
}

@Test("A long candidate scored after a short one does not read the short one's rows")
func scratchGrowsAndShrinksSafely() {
var scratch = FuzzyScratch()
let query = FuzzyQuery("ab")
for candidate in ["ab", String(repeating: "xab", count: 200), "b_a_b", "ab"] {
#expect(FuzzyMatcher.score(query, candidate, scratch: &scratch) == FuzzyMatcher.match(query: "ab", candidate: candidate)?.score)
}
}
}
Loading
Loading