File: TreeDictionary.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 (552 lines) | stat: -rw-r--r-- 22,709 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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2019 - 2024 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
//
//===----------------------------------------------------------------------===//

/// An unordered collection of unique keys and associated values, optimized for
/// mutating shared copies and comparing different snapshots of the same
/// collection.
///
/// `TreeDictionary` has the same functionality as a standard
/// `Dictionary`, and it largely implements the same APIs: both are hashed
/// collection types with convenient and efficient ways to look up the value
/// associated with a particular key, and both types are unordered, meaning that
/// neither type provides any guarantees about the ordering of their items.
///
/// However, `TreeDictionary` is optimizing specifically for use cases
/// that need to mutate shared copies or to compare a dictionary value to one of
/// its older snapshots. To use a term from functional programming,
/// `TreeDictionary` implements a _persistent data structure_.
///
/// The standard `Dictionary` stores its members in a single, flat hash table,
/// and it implements value semantics with all-or-nothing copy-on-write
/// behavior: every time a shared copy of a dictionary is mutated, the mutation
/// needs to make a full copy of the dictionary's storage.
/// `TreeDictionary` takes a different approach: it organizes its members
/// into a tree structure, the nodes of which can be freely shared across
/// collection values. When mutating a shared copy of a dictionary value,
/// `TreeDictionary` is able to simply link the unchanged parts of the
/// tree directly into the result, saving both time and memory.
///
/// This structural sharing also makes it more efficient to compare mutated
/// dictionaries values to earlier versions of themselves. When comparing or
/// combining dictionaries, parts that are shared across both inputs can
/// typically be handled in constant time, leading to a dramatic performance
/// boost when the two inputs are still largely unchanged:
///
///     var d = TreeDictionary(
///         uniqueKeysWithValues: (0 ..< 10_000).map { ($0, 2 * $0) })
///     let copy = d
///     d[20_000] = 42 // Expected to be an O(log(n)) operation
///     let diff = d.keys.subtracting(copy.keys) // Also O(log(n))!
///     // `diff` now holds the single item 20_000.
///
/// The tree structure also eliminates the need to reserve capacity in advance:
/// `TreeDictionary` creates, destroys and resizes individual nodes as
/// needed, always consuming just enough memory to store its contents. As of
/// Swift 5.9, the standard collection types never shrink their storage, so
/// temporary storage spikes can linger as unused but still allocated memory
/// long after the collection has shrunk back to its usual size.
///
/// Of course, switching to a tree structure comes with some trade offs. In
/// particular, inserting new items, removing existing ones, and iterating over
/// a `TreeDictionary` is expected to be a constant factor slower than a
/// standard `Dictionary` -- allocating/deallocating nodes isn't free, and
/// navigating the tree structure requires more pointer dereferences than
/// accessing a flat hash table. However the algorithmic improvements above
/// usually more than make up for this, as long as the use case can make use of
/// them.
@frozen // Not really -- this package is not at all ABI stable
public struct TreeDictionary<Key: Hashable, Value> {
  @usableFromInline
  internal typealias _Node = _HashNode<Key, Value>

  @usableFromInline
  internal typealias _UnsafeHandle = _Node.UnsafeHandle

  @usableFromInline
  var _root: _Node

  /// The version number of this instance, used for quick index validation.
  /// This is initialized to a (very weakly) random value and it gets
  /// incremented on every mutation that needs to invalidate indices.
  @usableFromInline
  var _version: UInt

  @inlinable
  internal init(_root: _Node, version: UInt) {
    self._root = _root
    self._version = version
  }

  @inlinable
  internal init(_new: _Node) {
    self.init(_root: _new, version: _new.initialVersionNumber)
  }
}

extension TreeDictionary {
  /// Accesses the value associated with the given key for reading and writing.
  ///
  /// This *key-based* subscript returns the value for the given key if the key
  /// is found in the dictionary, or `nil` if the key is not found.
  ///
  /// The following example creates a new dictionary and prints the value of a
  /// key found in the dictionary (`"Coral"`) and a key not found in the
  /// dictionary (`"Cerise"`).
  ///
  ///     var hues: TreeDictionary = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
  ///     print(hues["Coral"])
  ///     // Prints "Optional(16)"
  ///     print(hues["Cerise"])
  ///     // Prints "nil"
  ///
  /// When you assign a value for a key and that key already exists, the
  /// dictionary overwrites the existing value. If the dictionary doesn't
  /// contain the key, the key and value are added as a new key-value pair.
  ///
  /// Here, the value for the key `"Coral"` is updated from `16` to `18` and a
  /// new key-value pair is added for the key `"Cerise"`.
  ///
  ///     hues["Coral"] = 18
  ///     print(hues["Coral"])
  ///     // Prints "Optional(18)"
  ///
  ///     hues["Cerise"] = 330
  ///     print(hues["Cerise"])
  ///     // Prints "Optional(330)"
  ///
  /// If you assign `nil` as the value for the given key, the dictionary
  /// removes that key and its associated value.
  ///
  /// In the following example, the key-value pair for the key `"Aquamarine"`
  /// is removed from the dictionary by assigning `nil` to the key-based
  /// subscript.
  ///
  ///     hues["Aquamarine"] = nil
  ///     print(hues)
  ///     // Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]"
  ///
  /// Updating the value of an existing key only modifies the value: it does not
  /// change the key that is stored in the dictionary. (In some cases, equal
  /// keys may be distinguishable from each other by identity comparison or
  /// some other means.)
  ///
  /// Removing or updating an existing key-value pair or inserting a new
  /// key-value pair invalidates all indices in the dictionary. Removing a
  /// key that doesn't exist does not invalidate any indices.
  ///
  /// - Parameter key: The key to find in the dictionary.
  ///
  /// - Returns: The value associated with `key` if `key` is in the dictionary;
  ///   otherwise, `nil`.
  ///
  /// - Complexity: Looking up the value for a key is expected to traverse
  ///    O(log(`count`)) tree nodes and to do at most O(1) hashing/comparison
  ///    operations on the `Element` type, as long as `Element` properly
  ///    implements hashing.
  ///
  ///    Updating the dictionary through this subscript is expected to copy at
  ///    most O(log(`count`)) existing members.
  @inlinable
  public subscript(key: Key) -> Value? {
    get {
      _root.get(.top, key, _Hash(key))
    }
    set {
      if let value = newValue {
        _updateValue(value, forKey: key)
        _invalidateIndices()
      } else {
        removeValue(forKey: key)
      }
    }
    @inline(__always) // https://github.com/apple/swift-collections/issues/164
    _modify {
      _invalidateIndices()
      var state = _root.prepareValueUpdate(key, _Hash(key))
      defer {
        _root.finalizeValueUpdate(state)
      }
      yield &state.value
    }
  }

  /// Accesses the value with the given key. If the dictionary doesn't contain
  /// the given key, accesses the provided default value as if the key and
  /// default value existed in the dictionary.
  ///
  /// Use this subscript when you want either the value for a particular key
  /// or, when that key is not present in the dictionary, a default value. This
  /// example uses the subscript with a message to use in case an HTTP response
  /// code isn't recognized:
  ///
  ///     var responseMessages: TreeDictionary = [
  ///         200: "OK",
  ///         403: "Access forbidden",
  ///         404: "File not found",
  ///         500: "Internal server error"]
  ///
  ///     let httpResponseCodes = [200, 403, 301]
  ///     for code in httpResponseCodes {
  ///         let message = responseMessages[code, default: "Unknown response"]
  ///         print("Response \(code): \(message)")
  ///     }
  ///     // Prints "Response 200: OK"
  ///     // Prints "Response 403: Access forbidden"
  ///     // Prints "Response 301: Unknown response"
  ///
  /// When a dictionary's `Value` type has value semantics, you can use this
  /// subscript to perform in-place operations on values in the dictionary.
  /// The following example uses this subscript while counting the occurrences
  /// of each letter in a string:
  ///
  ///     let message = "Hello, Elle!"
  ///     var letterCounts: TreeDictionary<Character, Int> = [:]
  ///     for letter in message {
  ///         letterCounts[letter, default: 0] += 1
  ///     }
  ///     // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...]
  ///
  /// When `letterCounts[letter, defaultValue: 0] += 1` is executed with a
  /// value of `letter` that isn't already a key in `letterCounts`, the
  /// specified default value (`0`) is returned from the subscript,
  /// incremented, and then added to the dictionary under that key.
  ///
  /// Updating the value of an existing key only modifies the value: it does not
  /// change the key that is stored in the dictionary. (In some cases, equal
  /// keys may be distinguishable from each other by identity comparison or
  /// some other means.)
  ///
  /// Calling this method invalidates all existing indices in the dictionary.
  ///
  /// - Note: Do not use this subscript to modify dictionary values if the
  ///   dictionary's `Value` type is a class. In that case, the default value
  ///   and key are not written back to the dictionary after an operation. (For
  ///   a variant of this operation that supports this usecase, see
  ///   `updateValue(forKey:default:_:)`.)
  ///
  /// - Parameters:
  ///   - key: The key the look up in the dictionary.
  ///   - defaultValue: The default value to use if `key` doesn't exist in the
  ///     dictionary.
  ///
  /// - Returns: The value associated with `key` in the dictionary; otherwise,
  ///   `defaultValue`.
  ///
  /// - Complexity: Looking up the value for a key is expected to do at most
  ///    O(1) hashing/comparison operations on the `Element` type, as long as
  ///    `Element` properly implements hashing.
  ///
  ///    Updating the dictionary through this subscript is expected to copy at
  ///    most O(log(`count`)) existing members.
  @inlinable
  public subscript(
    key: Key,
    default defaultValue: @autoclosure () -> Value
  ) -> Value {
    get {
      _root.get(.top, key, _Hash(key)) ?? defaultValue()
    }
    set {
      _updateValue(newValue, forKey: key)
      _invalidateIndices()
    }
    @inline(__always) // https://github.com/apple/swift-collections/issues/164
    _modify {
      _invalidateIndices()
      var state = _root.prepareDefaultedValueUpdate(
        .top, key, defaultValue, _Hash(key))
      defer {
        _root.finalizeDefaultedValueUpdate(state)
      }
      yield &state.item.value
    }
  }

  /// Returns the index for the given key.
  ///
  /// If the given key is found in the dictionary, this method returns an index
  /// into the dictionary that corresponds with the key-value pair. If the
  /// key is not found, then this method returns `nil`.
  ///
  /// - Parameter key: The key to find in the dictionary.
  ///
  /// - Returns: The index for `key` and its associated value if `key` is in
  ///    the dictionary; otherwise, `nil`.
  ///
  /// - Complexity: This operation is expected to perform O(1) hashing and
  ///    comparison operations on average, provided that `Element` implements
  ///    high-quality hashing.
  @inlinable
  public func index(forKey key: Key) -> Index? {
    guard let path = _root.path(to: key, _Hash(key))
    else { return nil }
    return Index(_root: _root.unmanaged, version: _version, path: path)
  }

  /// Updates the value stored in the dictionary for the given key, or appends a
  /// new key-value pair if the key does not exist.
  ///
  /// Use this method instead of key-based subscripting when you need to know
  /// whether the new value supplants the value of an existing key. If the
  /// value of an existing key is updated, `updateValue(_:forKey:)` returns
  /// the original value.
  ///
  ///     var hues: TreeDictionary = [
  ///         "Heliotrope": 296,
  ///         "Coral": 16,
  ///         "Aquamarine": 156]
  ///
  ///     if let oldValue = hues.updateValue(18, forKey: "Coral") {
  ///         print("The old value of \(oldValue) was replaced with a new one.")
  ///     }
  ///     // Prints "The old value of 16 was replaced with a new one."
  ///
  /// If the given key is not present in the dictionary, this method appends the
  /// key-value pair and returns `nil`.
  ///
  ///     if let oldValue = hues.updateValue(330, forKey: "Cerise") {
  ///         print("The old value of \(oldValue) was replaced with a new one.")
  ///     } else {
  ///         print("No value was found in the dictionary for that key.")
  ///     }
  ///     // Prints "No value was found in the dictionary for that key."
  ///
  /// Updating the value of an existing key only modifies the value: it does not
  /// change the key that is stored in the dictionary. (In some cases, equal
  /// keys may be distinguishable from each other by identity comparison or
  /// some other means.)
  ///
  /// Calling this method invalidates all existing indices in the dictionary.
  ///
  /// - Parameters:
  ///   - value: The new value to add to the dictionary.
  ///   - key: The key to associate with `value`. If `key` already exists in
  ///     the dictionary, `value` replaces the existing associated value. If
  ///     `key` isn't already a key of the dictionary, the `(key, value)` pair
  ///     is added.
  ///
  /// - Returns: The value that was replaced, or `nil` if a new key-value pair
  ///   was added.
  ///
  /// - Complexity: This operation is expected to copy at most O(log(`count`))
  ///    existing members and to perform at most O(1) hashing/comparison
  ///    operations on the `Element` type, as long as `Element` properly
  ///    implements hashing.
  @inlinable
  @discardableResult
  public mutating func updateValue(
    _ value: __owned Value, forKey key: Key
  ) -> Value? {
    defer { _fixLifetime(self) }
    let hash = _Hash(key)
    let r = _root.updateValue(.top, forKey: key, hash) {
      $0.initialize(to: (key, value))
    }
    _invalidateIndices()
    if r.inserted { return nil }
    return _UnsafeHandle.update(r.leaf) {
      let p = $0.itemPtr(at: r.slot)
      let old = p.pointee.value
      p.pointee.value = value
      return old
    }
  }

  @inlinable
  @discardableResult
  internal mutating func _updateValue(
    _ value: __owned Value, forKey key: Key
  ) -> Bool {
    defer { _fixLifetime(self) }
    let hash = _Hash(key)
    let r = _root.updateValue(.top, forKey: key, hash) {
      $0.initialize(to: (key, value))
    }
    if r.inserted { return true }
    _UnsafeHandle.update(r.leaf) {
      $0[item: r.slot].value = value
    }
    return false
  }

  /// Calls `body` to directly update the current value of `key` in the
  /// dictionary.
  ///
  /// You can use this method to perform in-place operations on values in the
  /// dictionary, whether or not `Value` has value semantics. The following
  /// example uses this method while counting the occurrences of each letter
  /// in a string:
  ///
  ///     let message = "Hello, Elle!"
  ///     var letterCounts: TreeDictionary<Character, Int> = [:]
  ///     for letter in message {
  ///         letterCounts.updateValue(forKey: letter) { count in
  ///             if count == nil {
  ///               count = 1
  ///             } else
  ///               count! += 1
  ///             }
  ///         }
  ///     }
  ///     // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...]
  ///
  /// Updating the value of an existing key only modifies the value: it does not
  /// change the key that is stored in the dictionary. (In some cases, equal
  /// keys may be distinguishable from each other by identity comparison or
  /// some other means.)
  ///
  /// Removing or updating an existing key-value pair or inserting a new
  /// key-value pair invalidates all indices in the dictionary. Removing a
  /// key that doesn't exist does not invalidate any indices.
  ///
  /// - Parameters:
  ///   - key: The key whose value to look up.
  ///   - body: A function that performs an in-place mutation on the dictionary
  ///      value. If `key` exists in the dictionary, then `body` is called with
  ///      its current value; otherwise `body` is passed `nil`.
  ///
  /// - Returns: The return value of `body`.
  ///
  /// - Complexity: In addition to calling `body`, this operation is expected
  ///    to copy at most O(log(`count`)) existing members and to perform at
  ///    most O(1) hashing/comparison operations on the `Element` type, as long
  ///    as `Element` properly implements hashing.
  @inlinable @inline(__always)
  public mutating func updateValue<R>(
    forKey key: Key,
    with body: (inout Value?) throws -> R
  ) rethrows -> R {
    try body(&self[key])
  }

  /// Ensures that the specified key exists in the dictionary (by inserting one
  /// with the supplied default value if necessary), then calls `body` to update
  /// it in place.
  ///
  /// You can use this method to perform in-place operations on values in the
  /// dictionary, whether or not `Value` has value semantics. The following
  /// example uses this method while counting the occurrences of each letter
  /// in a string:
  ///
  ///     let message = "Hello, Elle!"
  ///     var letterCounts: TreeDictionary<Character, Int> = [:]
  ///     for letter in message {
  ///         letterCounts.updateValue(forKey: letter, default: 0) { count in
  ///             count += 1
  ///         }
  ///     }
  ///     // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...]
  ///
  /// Updating the value of an existing key only modifies the value: it does not
  /// change the key that is stored in the dictionary. (In some cases, equal
  /// keys may be distinguishable from each other by identity comparison or
  /// some other means.)
  ///
  /// Calling this method invalidates all existing indices in the dictionary.
  ///
  /// - Parameters:
  ///   - key: The key to look up (or insert). If `key` does not already exist
  ///      in the dictionary, it is inserted with the supplied default value.
  ///   - defaultValue: The default value to insert if `key` doesn't exist in
  ///      the dictionary.
  ///   - body: A function that performs an in-place mutation on the dictionary
  ///      value.
  ///
  /// - Returns: The return value of `body`.
  ///
  /// - Complexity: In addition to calling `body`, this operation is expected
  ///    to copy at most O(log(`count`)) existing members and to perform at
  ///    most O(1) hashing/comparison operations on the `Element` type, as long
  ///    as `Element` properly implements hashing.
  @inlinable
  public mutating func updateValue<R>(
    forKey key: Key,
    default defaultValue: @autoclosure () -> Value,
    with body: (inout Value) throws -> R
  ) rethrows -> R {
    defer { _fixLifetime(self) }
    let hash = _Hash(key)
    let r = _root.updateValue(.top, forKey: key, hash) {
      $0.initialize(to: (key, defaultValue()))
    }
    return try _UnsafeHandle.update(r.leaf) {
      try body(&$0[item: r.slot].value)
    }
  }

  /// Removes the given key and its associated value from the dictionary.
  ///
  /// If the key is found in the dictionary, this method returns the key's
  /// associated value, and invalidates all previously returned indices.
  ///
  ///     var hues: TreeDictionary = [
  ///        "Heliotrope": 296,
  ///        "Coral": 16,
  ///        "Aquamarine": 156]
  ///     if let value = hues.removeValue(forKey: "Coral") {
  ///         print("The value \(value) was removed.")
  ///     }
  ///     // Prints "The value 16 was removed."
  ///
  /// If the key isn't found in the dictionary, `removeValue(forKey:)` returns
  /// `nil`. Removing a key that isn't in the dictionary does not invalidate
  /// any indices.
  ///
  ///     if let value = hues.removeValue(forKey: "Cerise") {
  ///         print("The value \(value) was removed.")
  ///     } else {
  ///         print("No value found for that key.")
  ///     }
  ///     // Prints "No value found for that key.""
  ///
  /// - Parameter key: The key to remove along with its associated value.
  ///
  /// - Returns: The value that was removed, or `nil` if the key was not
  ///   present in the dictionary.
  ///
  /// - Complexity: In addition to calling `body`, this operation is expected
  ///    to copy at most O(log(`count`)) existing members and to perform at
  ///    most O(1) hashing/comparison operations on the `Element` type, as long
  ///    as `Element` properly implements hashing.
  @inlinable
  @discardableResult
  public mutating func removeValue(forKey key: Key) -> Value? {
    guard let r = _root.remove(.top, key, _Hash(key)) else { return nil }
    _invalidateIndices()
    assert(r.remainder == nil)
    _invariantCheck()
    return r.removed.value
  }

  /// Removes and returns the key-value pair at the specified index.
  ///
  /// Calling this method invalidates all existing indices in the dictionary.
  ///
  /// - Parameter index: The position of the element to remove. `index` must be
  ///    a valid index of the dictionary that is not equal to `endIndex`.
  ///
  /// - Returns: The removed key-value pair.
  ///
  /// - Complexity: This operation is expected to copy at most O(log(`count`))
  ///    existing members and to perform at most O(1) hashing/comparison
  ///    operations on the `Element` type, as long as `Element` properly
  ///    implements hashing.
  @inlinable
  public mutating func remove(at index: Index) -> Element {
    precondition(_isValid(index), "Invalid index")
    precondition(index._path._isItem, "Can't remove item at end index")
    _invalidateIndices()
    let r = _root.remove(.top, at: index._path)
    assert(r.remainder == nil)
    return r.removed
  }
}