File: PrefixTrie.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (412 lines) | stat: -rw-r--r-- 13,161 bytes parent folder | download
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
//==------------------ PrefixTrie.swift - Prefix Trie ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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 prefix trie is a data structure for quickly matching prefixes of strings.
/// It's a tree structure where each node in the tree corresponds to another
/// element in the prefix of whatever you're looking for.
///
/// For example, if you entered these strings:
///
/// "Help", "Helper", "Helping", "Helicopters", "Helicoptering"
///
/// The resulting trie would look like this:
///
/// ```
///                      ┌───┐
///              ┌──────▶│ s │
///              │       └───┘
///         ┌─────────┐
///    ┌───▶│ icopter │
///    │    └─────────┘
///    │         │       ┌───┐
///    │         └──────▶│ing│
/// ┌─────┐              └───┘
/// │ Hel │
/// └─────┘              ┌────┐
///    │      ┌─────────▶│ er │
///    │      │          └────┘
///    │    ┌───┐
///    └───▶│ p │
///         └───┘
///           │          ┌─────┐
///           └─────────▶│ ing │
///                      └─────┘
/// ```
///
/// Traversing this trie is O(min(n, m)) with `n` representing the length of the
/// key being searched and `m` representing the longest matching prefix in the
/// tree.
///
/// Inserting into the trie is also O(n) with the length of the key being
/// inserted.
public struct PrefixTrie<Payload> {
  final class Node {
    /// The result of querying the trie for a given string. This represents the
    /// kind and length of the match.
    enum QueryResult: Equatable {
      /// The exact string queried was found in the trie.
      case same

      /// The query string is a prefix of the nodes in the trie; there are still
      /// unconsumed characters in the matching node's label.
      case stringIsPrefix

      /// The label of the queried node is a prefix of the string; there are
      /// still characters left in the query string that have yet to be
      /// matched.
      case labelIsPrefix

      /// The strings do not match at all.
      case dontMatch

      /// There's a common part of the string, but neither the label nor the
      /// query string were matched entirely.
      case haveCommonPart(Int)
    }

    /// The string corresponding to this hop in the trie.
    var label: Substring

    /// The data associated with this node, if any. If this is `nil`, the node
    /// is an intermediate node (or its data has been explicitly erased).
    var data: Payload?

    /// The children of this node. This array is always in sorted order by
    /// the node's `id`.
    var children = [Node]()

    /// Each node is identified in the child list by the first character in its
    /// label.
    var id: Character {
      label.first!
    }

    /// Creates a new `Node` with the given label and data.
    init(label: Substring, data: Payload?) {
      self.label = label
      self.data = data
    }

    /// Adds the provided child to the children list, maintaining the list's
    /// sort.
    func addChild(_ node: Node) {
      if children.isEmpty {
        children.append(node)
      } else {
        let index = children.lowerBound(of: node) {
          $0.id < $1.id
        }
        children.insert(node, at: index)
      }
    }

    /// Replaces the existing child for that `id` with the provided child.
    func updateChild(_ node: Node) {
      let index = children.lowerBound(of: node) {
        $0.id < $1.id
      }
      children[index] = node
    }

    /// Searches through the trie for the given string, returning the kind of
    /// match made.
    func query<S: StringProtocol>(_ s: S) -> QueryResult {
      let stringCount = s.count
      let labelCount = label.count

      // Find the length of common part.
      let leastCount = min(stringCount, labelCount)

      var index = s.startIndex
      var otherIndex = label.startIndex
      var length = 0
      while length < leastCount && s[index] == label[otherIndex] {
        s.formIndex(after: &index)
        label.formIndex(after: &otherIndex)
        length += 1
      }

      // One is prefix of another, find who is who
      if length == leastCount {
        if stringCount == labelCount {
          return .same
        } else if length == stringCount {
          return .stringIsPrefix
        } else {
          return .labelIsPrefix
        }
      } else if length == 0 {
          return .dontMatch
      } else {
        // The query string and the label have a common part, return its length.
        return .haveCommonPart(length)
      }
    }

    /// Splits the receiver into two nodes at the provided index. Doing this
    /// will turn the receiver into an intermediate node, and transfer its
    /// children to the new node.
    ///
    /// For example, if the current branch is:
    ///
    /// ```
    /// "Hel" -> "per" -> "s"
    /// ```
    ///
    /// then calling `"per".split(at: 1)` will turn the branch into:
    ///
    /// ```
    /// "Hel" -> "p" -> "er" -> "s"
    /// ```
    func split(at rawIndex: Int) {
      assert((1..<label.count).contains(rawIndex),
             "Trying to split outside the bounds of the label")

      let index = label.index(label.startIndex, offsetBy: rawIndex)
      let firstPart = label[..<index]
      let secondPart = label[index...]

      let new = Node(label: secondPart, data: data)
      new.children = children
      label = firstPart
      data = nil
      children = []
      addChild(new)
    }

    /// Searches the array for the given `id` and returns the node with that
    /// `id`, if present.
    func findChild(for id: Character) -> Node? {
      if children.isEmpty { return nil }

      let index = children.lowerBound(of: id) { $0.id < $1 }
      guard index < children.endIndex else { return nil }
      let node = children[index]
      guard node.id == id else { return nil }
      return node
    }
  }

  /// The root of the hierarchy, intentionally empty. This label is never
  /// queried.
  var root = Node(label: "", data: nil)

  /// Creates a new, empty prefix trie.
  public init() {}

  /// Searches the trie for the given query string and either returns the best
  /// matching entry or stores the provided payload into the trie.
  public subscript(_ query: String) -> Payload? {
    get {
      var current = root
      var bestMatch: Payload?
      var string = query[...]

      while true {
        let id = string.first!
        guard let existing = current.findChild(for: id) else {
          return bestMatch
        }

        switch existing.query(string) {
        case .same:
          // If we've found an exact match, return it directly.
          return existing.data
        case .labelIsPrefix:
          // If we have more of our query to consume, keep going down this path.
          string = string.dropFirst(existing.label.count)
          current = existing
          if let data = existing.data {
            // If there's data associated with this node, though, keep track of
            // it. We may end up with a later match that doesn't have associated
            // data.
            bestMatch = data
          }
        case .dontMatch:
          fatalError("Impossible because we found a child with id \(id)")
        default:
          // If we've consumed the whole query string, return the best match
          // now.
          return bestMatch
        }
      }
    }

    set {
      var current = root
      var string = query[...]

      while true {
        let id = string.first!

        guard let existing = current.findChild(for: id) else {
          current.addChild(Node(label: string, data: newValue))
          return
        }

        switch existing.query(string) {
        case .same:
          // If we've matched an entry exactly, just update its value in place.
          existing.data = newValue
          return
        case .stringIsPrefix:
          // In this case, the string we're matching is a prefix of an existing
          // string in the trie. e.g. we're trying to add "-debug-constraints"
          // when we already have "-debug-constraints-on-line" and
          // "-debug-constraints-attempt"

          // So far we have:
          //   "debug-" : <A>
          //     -> "constraints-" : <B>
          //       -> "on-line" : <C>
          //       -> "attempt" : <D>
          //
          // We need to end up with:
          //   "debug-" : <A>
          //     -> "constraints" : <B>
          //       -> "-"         : <E>
          //         -> "on-line" : <C>
          //         -> "attempt" : <D>
          //
          // In this example, we need to take the '-' from the end of B and
          // split it into its own node, and then add the existing children as a child
          // of that node.
          //

          // First, strip off the leading text of "constraints"
          let remaining = existing.label.dropFirst(string.count)

          // Create a new node for this, and give it the existing node's
          // children.
          let new = Node(label: remaining, data: existing.data)
          new.children = existing.children

          // Reset 'existing' to the common prefix, and set its data
          // accordingly.
          existing.label = string
          existing.data = newValue

          // Now remove all of 'existing's children, and replace it with this
          // hop.
          existing.children = [new]
          return
        case .dontMatch:
          fatalError("Impossible because we found a child with id \(id)")
        case .labelIsPrefix:
          // If we've matched an entry along the way, remove it from the
          // beginning of our query and continue down this path.
          string = string.dropFirst(existing.label.count)
          current = existing
        case .haveCommonPart(let length):
          // If the existing node has some in common with our node, we need
          // to split the existing node at the common point, then add the
          // remaining characters as a child of that node.
          existing.split(at: length)
          let new = Node(label: string.dropFirst(length), data: newValue)
          existing.addChild(new)
          return
        }
      }
    }
  }

  public var nodeCount: Int {
    var count = 1
    var queue = [root]
    while !queue.isEmpty {
      let node = queue.popLast()!
      queue += node.children
      count += node.children.count
    }
    return count
  }

  public func printDOT() {
    let writer = Node.DOTWriter(node: root)
    writer.writeDOT()
  }
}

// MARK: - DOT generation for nodes (for debugging)

extension PrefixTrie.Node {
  class DOTWriter {
    let node: PrefixTrie.Node
    init(node: PrefixTrie.Node) {
      self.node = node
    }
    var labelCounter = [Substring: Int]()
    var nodeIDs = [ObjectIdentifier: String]()

    func id(for node: PrefixTrie.Node) -> String {
      if let id = nodeIDs[ObjectIdentifier(node)] {
        return id
      }

      let count = labelCounter[node.label, default: 0]
      labelCounter[node.label] = count + 1

      let id: String
      if count == 0 {
        id = String(node.label)
      } else {
        id = "\(node.label)_\(count)"
      }
      nodeIDs[ObjectIdentifier(node)] = id
      return id
    }

    func writeDOT() {
      print("digraph Trie {")
      var queue = [node]
      while !queue.isEmpty {
        let node = queue.popLast()!
        var str = #"  "\#(id(for: node))" [label="\#(node.label)""#
        if node.data != nil {
          str += ", style=bold"
        }
        str += "]"
        print(str)
        for child in node.children {
          print(#"  "\#(id(for: node))" -> "\#(id(for: child))""#)
          queue.insert(child, at: 0)
        }
      }
      print("}")
    }
  }
}

extension Array {
  /// A naïve implementation of `std::lower_bound` for Array.
  /// Returns the index before the first element in the list that is ordered
  /// after the given `value`, as determined by the provided predicate.
  func lowerBound<T>(of value: T, isOrderedBefore: (Element, T) -> Bool) -> Int {
    var count = self.count
    var index = startIndex
    var first = startIndex
    var step = 0
    while count > 0 {
      index = first
      step = count / 2
      index += step
      if isOrderedBefore(self[index], value) {
        index += 1
        first = index
        count -= step + 1
      } else {
        count = step
      }
    }
    return first
  }
}