File: Rope%2BCollection.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 (493 lines) | stat: -rw-r--r-- 13,289 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2023 - 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
//
//===----------------------------------------------------------------------===//

extension Rope {
  @inlinable
  public func isValid(_ index: Index) -> Bool {
    index._version == _version
  }

  @inlinable
  public func validate(_ index: Index) {
    precondition(isValid(index), "Invalid index")
  }

  @inlinable
  internal mutating func _invalidateIndices() {
    _version.bump()
  }

  /// Validate `index` and fill out all cached information in it,
  /// to speed up subsequent lookups.
  @inlinable
  public func grease(_ index: inout Index) {
    validate(index)
    guard index._leaf == nil else { return }
    index._leaf = _unmanagedLeaf(at: index._path)
  }
}

extension Rope {
  @inlinable
  public var _height: UInt8 {
    _root?.height ?? 0
  }

  @inlinable
  internal var _startPath: _Path {
    _Path(height: _height)
  }

  @inlinable
  internal var _endPath: _Path {
    guard let root = _root else { return _startPath }
    var path = _Path(height: _height)
    path[_height] = root.childCount
    return path
  }
}

extension Rope: BidirectionalCollection {
  public typealias SubSequence = Slice<Self>

  @inlinable
  public var isEmpty: Bool {
    guard _root != nil else { return true }
    return root.childCount == 0
  }

  @inlinable
  public var startIndex: Index {
    // Note: `leaf` is intentionally not set here, to speed up accessing this property.
    return Index(version: _version, path: _startPath, leaf: nil)
  }

  @inlinable
  public var endIndex: Index {
    Index(version: _version, path: _endPath, leaf: nil)
  }

  @inlinable
  public func index(after i: Index) -> Index {
    var i = i
    formIndex(after: &i)
    return i
  }

  @inlinable
  public func index(before i: Index) -> Index {
    var i = i
    formIndex(before: &i)
    return i
  }

  @inlinable
  public func formIndex(after i: inout Index) {
    validate(i)
    precondition(i < endIndex, "Can't move after endIndex")
    if let leaf = i._leaf {
      let done = leaf.read {
        let slot = i._path[$0.height] &+ 1
        guard slot < $0.childCount else { return false }
        i._path[$0.height] = slot
        return true
      }
      if done { return }
    }
    if !root.formSuccessor(of: &i) {
      i = endIndex
    }
  }

  @inlinable
  public func formIndex(before i: inout Index) {
    validate(i)
    precondition(i > startIndex, "Can't move before startIndex")
    if let leaf = i._leaf {
      let done = leaf.read {
        let slot = i._path[$0.height]
        guard slot > 0 else { return false }
        i._path[$0.height] = slot &- 1
        return true
      }
      if done { return }
    }
    let success = root.formPredecessor(of: &i)
    precondition(success, "Invalid index")
  }

  @inlinable
  public subscript(i: Index) -> Element {
    get {
      validate(i)
      if let ref = i._leaf {
        return ref.read {
          $0.children[i._path[$0.height]].value
        }
      }
      return root[i._path].value
    }
    @inline(__always) _modify {
      validate(i)
      // Note: we must not use _leaf -- it may not be on a unique path.
      defer { _invalidateIndices() }
      yield &root[i._path].value
    }
  }
}

extension Rope {
  /// Update the element at the given index, while keeping the index valid.
  @inlinable
  public mutating func update<R>(
    at index: inout Index,
    by body: (inout Element) -> R
  ) -> R {
    validate(index)
    var state = root._prepareModify(at: index._path)
    defer {
      _invalidateIndices()
      index._version = self._version
      index._leaf = root._finalizeModify(&state).leaf
    }
    return body(&state.item.value)
  }
}

extension Rope {
  @inlinable @inline(__always)
  public static var _maxHeight: Int {
    _Path._pathBitWidth / Summary.nodeSizeBitWidth
  }

  /// The estimated maximum number of items that can fit in this rope in the worst possible case,
  /// i.e., when the tree consists of minimum-sized nodes. (The data structure itself has no
  /// inherent limit, but this implementation of it is limited by the fixed 56-bit path
  /// representation used in the `Index` type.)
  ///
  /// This is one less than the minimum possible size for a rope whose size exceeds the maximum.
  @inlinable
  public static var _minimumCapacity: Int {
    var c = 2
    for _ in 0 ..< _maxHeight {
      let (r, overflow) = c.multipliedReportingOverflow(by: Summary.minNodeSize)
      if overflow { return .max }
      c = r
    }
    return c - 1
  }

  /// The maximum number of items that can fit in this rope in the best possible case, i.e., when
  /// the tree consists of maximum-sized nodes. (The data structure itself has no inherent limit,
  /// but this implementation of it is limited by the fixed 56-bit path representation used in
  /// the `Index` type.)
  @inlinable
  public static var _maximumCapacity: Int {
    var c = 1
    for _ in 0 ... _maxHeight {
      let (r, overflow) = c.multipliedReportingOverflow(by: Summary.maxNodeSize)
      if overflow { return .max }
      c = r
    }
    return c
  }
}

extension Rope {
  @inlinable
  public func count(in metric: some RopeMetric<Element>) -> Int {
    guard _root != nil else { return 0 }
    return root.count(in: metric)
  }
}

extension Rope._Node {
  @inlinable
  public func count(in metric: some RopeMetric<Element>) -> Int {
    metric._nonnegativeSize(of: self.summary)
  }
}

extension Rope {
  @inlinable
  public func distance(from start: Index, to end: Index, in metric: some RopeMetric<Element>) -> Int {
    validate(start)
    validate(end)
    if start == end { return 0 }
    precondition(_root != nil, "Invalid index")
    if start._leaf == end._leaf, let leaf = start._leaf {
      // Fast path: both indices are pointing within the same leaf.
      return leaf.read {
        let h = $0.height
        let a = start._path[h]
        let b = end._path[h]
        return $0.distance(from: a, to: b, in: metric)
      }
    }
    if start < end {
      return root.distance(from: start, to: end, in: metric)
    }
    return -root.distance(from: end, to: start, in: metric)
  }

  @inlinable
  public func offset(of index: Index, in metric: some RopeMetric<Element>) -> Int {
    validate(index)
    if _root == nil { return 0 }
    return root.distanceFromStart(to: index, in: metric)
  }
}

extension Rope._Node {
  @inlinable
  internal func distanceFromStart(
    to index: Index, in metric: some RopeMetric<Element>
  ) -> Int {
    let slot = index._path[height]
    precondition(slot <= childCount, "Invalid index")
    if slot == childCount {
      precondition(index._isEmpty(below: height), "Invalid index")
      return metric._nonnegativeSize(of: self.summary)
    }
    if height == 0 {
      return readLeaf { $0.distance(from: 0, to: slot, in: metric) }
    }
    return readInner {
      var distance = $0.distance(from: 0, to: slot, in: metric)
      distance += $0.children[slot].distanceFromStart(to: index, in: metric)
      return distance
    }
  }

  @inlinable
  internal func distanceToEnd(
    from index: Index, in metric: some RopeMetric<Element>
  ) -> Int {
    let d = metric._nonnegativeSize(of: self.summary) - self.distanceFromStart(to: index, in: metric)
    assert(d >= 0)
    return d
  }

  @inlinable
  internal func distance(
    from start: Index, to end: Index, in metric: some RopeMetric<Element>
  ) -> Int {
    assert(start < end)
    let a = start._path[height]
    let b = end._path[height]
    precondition(a < childCount, "Invalid index")
    precondition(b <= childCount, "Invalid index")
    assert(a <= b)
    if b == childCount {
      precondition(end._isEmpty(below: height), "Invalid index")
      return distanceToEnd(from: start, in: metric)
    }
    if height == 0 {
      assert(a < b)
      return readLeaf { $0.distance(from: a, to: b, in: metric) }
    }
    return readInner {
      let c = $0.children
      if a == b {
        return c[a].distance(from: start, to: end, in: metric)
      }
      var d = c[a].distanceToEnd(from: start, in: metric)
      d += $0.distance(from: a + 1, to: b, in: metric)
      d += c[b].distanceFromStart(to: end, in: metric)
      return d
    }
  }
}

extension Rope {
  @inlinable
  public func formIndex(
    _ i: inout Index,
    offsetBy distance: inout Int,
    in metric: some RopeMetric<Element>,
    preferEnd: Bool
  ) {
    validate(i)
    if _root == nil {
      precondition(distance == 0, "Position out of bounds")
      return
    }
    if distance <= 0 {
      distance = -distance
      let success = root.seekBackward(
        from: &i, by: &distance, in: metric, preferEnd: preferEnd)
      precondition(success, "Position out of bounds")
      return
    }
    if let leaf = i._leaf {
      // Fast path: move within a single leaf
      let r = leaf.read {
        $0._seekForwardInLeaf(from: &i._path, by: &distance, in: metric, preferEnd: preferEnd)
      }
      if r { return }
    }
    if root.seekForward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) {
      return
    }
    precondition(distance == 0, "Position out of bounds")
    i = endIndex
  }

  @inlinable
  public func index(
    _ i: Index,
    offsetBy distance: Int,
    in metric: some RopeMetric<Element>,
    preferEnd: Bool
  ) -> (index: Index, remaining: Int) {
    var i = i
    var distance = distance
    formIndex(&i, offsetBy: &distance, in: metric, preferEnd: preferEnd)
    return (i, distance)
  }
}

extension Rope._UnsafeHandle {
  @inlinable
  func _seekForwardInLeaf(
    from path: inout Rope._Path,
    by distance: inout Int,
    in metric: some RopeMetric<Element>,
    preferEnd: Bool
  ) -> Bool {
    assert(distance >= 0)
    assert(height == 0)
    let c = children
    var slot = path[0]
    defer { path[0] = slot }
    while slot < c.count {
      let d = metric._nonnegativeSize(of: c[slot].summary)
      if preferEnd ? d >= distance : d > distance {
        return true
      }
      distance &-= d
      slot &+= 1
    }
    return false
  }

  @inlinable
  func _seekBackwardInLeaf(
    from path: inout Rope._Path,
    by distance: inout Int,
    in metric: some RopeMetric<Element>,
    preferEnd: Bool
  ) -> Bool {
    assert(distance >= 0)
    assert(height == 0)
    let c = children
    var slot = path[0] &- 1
    while slot >= 0 {
      let d = metric._nonnegativeSize(of: c[slot].summary)
      if preferEnd ? d > distance : d >= distance {
        path[0] = slot
        distance = d &- distance
        return true
      }
      distance &-= d
      slot &-= 1
    }
    return false
  }
}

extension Rope._Node {
  @inlinable
  func seekForward(
    from i: inout Index,
    by distance: inout Int,
    in metric: some RopeMetric<Element>,
    preferEnd: Bool
  ) -> Bool {
    assert(distance >= 0)

    if height == 0 {
      let r = readLeaf {
        $0._seekForwardInLeaf(from: &i._path, by: &distance, in: metric, preferEnd: preferEnd)
      }
      if r {
        i._leaf = asUnmanagedLeaf
      }
      return r
    }
    
    return readInner {
      var slot = i._path[height]
      precondition(slot < childCount, "Invalid index")
      let c = $0.children
      if c[slot].seekForward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) {
        return true
      }
      slot &+= 1
      while slot < c.count {
        let d = metric.size(of: c[slot].summary)
        if preferEnd ? d >= distance : d > distance {
          i._path[$0.height] = slot
          i._clear(below: $0.height)
          let success = c[slot].seekForward(
            from: &i, by: &distance, in: metric, preferEnd: preferEnd)
          precondition(success)
          return true
        }
        distance &-= d
        slot &+= 1
      }
      return false
    }
  }

  @inlinable
  func seekBackward(
    from i: inout Index,
    by distance: inout Int,
    in metric: some RopeMetric<Element>,
    preferEnd: Bool
  ) -> Bool {
    assert(distance >= 0)
    guard distance > 0 || preferEnd else { return true }
    if height == 0 {
      return readLeaf {
        $0._seekBackwardInLeaf(from: &i._path, by: &distance, in: metric, preferEnd: preferEnd)
      }
    }
    
    return readInner {
      var slot = i._path[height]
      precondition(slot <= childCount, "Invalid index")
      let c = $0.children
      if slot < childCount,
         c[slot].seekBackward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) {
        return true
      }
      slot -= 1
      while slot >= 0 {
        let d = metric.size(of: c[slot].summary)
        if preferEnd ? d > distance : d >= distance {
          i._path[$0.height] = slot
          i._clear(below: $0.height)
          distance = d - distance
          let success = c[slot].seekForward(
            from: &i, by: &distance, in: metric, preferEnd: preferEnd)
          precondition(success)
          return true
        }
        distance -= d
        slot -= 1
      }
      return false
    }
  }
}