_Rope: Add a leaf node reference to indices. Implement explicit index invalidation

This commit is contained in:
Karoy Lorentey committed 2023-03-20 13:12:09 -07:00
1 parent 8f48c3ae37
commit 3cc5a3888a
21 files changed
+671 -281

No files matched your search

@@ -58,12 +58,11 @@ extension _BString {
to i: Index,
preferEnd: Bool
) -> (path: Path, chunk: Chunk) {
let r = rope.find(at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd)
return r.node!.readLeaf {
let slot = r.index[height: 0]
let index = $0.children[slot].value.index(at: r.remaining, utf16Delta: i._utf16Delta)
return (Path(r.index, index), $0.children[slot].value)
}
let (ropeIndex, remaining) = rope.find(
at: i._utf8Offset, in: UTF8Metric(), preferEnd: preferEnd)
let chunk = rope[ropeIndex]
let chunkIndex = chunk.index(at: remaining, utf16Delta: i._utf16Delta)
return (Path(ropeIndex, chunkIndex), chunk)
}
}
@@ -36,7 +36,8 @@ extension _BString {
// full grapheme breaking state of the ingester at the start of the insertion.
// (We'll use it to resync grapheme breaks in the parts that follow the insertion.)
var (ingester, _, path) = ingester(forInserting: other, at: index, allowForwardPeek: false)
let r = rope[path.rope].insert(from: &ingester, at: path.chunk)
let i = path.chunk
let r = rope.update(at: &path.rope) { $0.insert(from: &ingester, at: i) }
switch r {
case let .inline(r):
assert(ingester.isAtEnd)
@@ -22,6 +22,12 @@ private func _addressString<T: AnyObject>(for object: Unmanaged<T>) -> String {
_addressString(for: object.toOpaque())
}
extension _Rope.UnmanagedLeaf: CustomStringConvertible {
var description: String {
_addressString(for: _ref.toOpaque())
}
}
extension _Rope {
var nodeCount: Int { _root?.nodeCount ?? 0 }
}
+103 -68
View File
@@ -17,7 +17,9 @@ extension _Rope {
typealias Item = _Rope.Item
typealias Storage = _Rope.Storage
typealias UnsafeHandle = _Rope.UnsafeHandle
typealias Path = _Rope.Path
typealias UnmanagedLeaf = _Rope.UnmanagedLeaf
var object: AnyObject
var summary: Summary
@@ -335,59 +337,86 @@ extension _Rope.Node {
}
extension _Rope.Node {
var startIndex: Index {
var i = Index(height: self.height)
descendToFirstItem(under: &i)
return i
var startPath: Path {
Path(height: self.height)
}
var lastIndex: Index {
var i = Index(height: self.height)
descendToLastItem(under: &i)
return i
var lastPath: Path {
var path = Path(height: self.height)
_ = descendToLastItem(under: &path)
return path
}
func isAtEnd(_ i: Index) -> Bool {
i[height: self.height] == childCount
func isAtEnd(_ path: Path) -> Bool {
path[self.height] == childCount
}
func descendToFirstItem(under i: inout Index) {
i.clear(below: self.height + 1)
func descendToFirstItem(under path: inout Path) -> UnmanagedLeaf {
path.clear(below: self.height + 1)
return unmanagedLeaf(at: path)
}
func descendToLastItem(under i: inout Index) {
func descendToLastItem(under path: inout Path) -> UnmanagedLeaf {
let h = self.height
let slot = self.childCount - 1
i[height: h] = slot
path[h] = slot
if h > 0 {
readInner { $0.children[slot].descendToLastItem(under: &i) }
return readInner { $0.children[slot].descendToLastItem(under: &path) }
}
return asUnmanagedLeaf
}
var asUnmanagedLeaf: UnmanagedLeaf {
assert(height == 0)
return UnmanagedLeaf(unsafeDowncast(self.object, to: Storage<Item>.self))
}
func unmanagedLeaf(at path: Path) -> UnmanagedLeaf {
if height == 0 {
return asUnmanagedLeaf
}
let slot = path[height]
return readInner { $0.children[slot].unmanagedLeaf(at: path) }
}
}
extension _Rope.Node {
func formSuccessor(of i: inout Index) -> Bool {
let h = self.height
var slot = i[height: h]
var slot = i._path[h]
if h == 0 {
slot += 1
guard slot < childCount else { return false }
i[height: h] = slot
slot &+= 1
guard slot < childCount else {
return false
}
i._path[h] = slot
i._leaf = asUnmanagedLeaf
return true
}
return readInner {
let c = $0.children
if c[slot].formSuccessor(of: &i) {
return true
}
slot += 1
guard slot < childCount else {
return false
}
i._path[h] = slot
i._leaf = c[slot].descendToFirstItem(under: &i._path)
return true
}
let success = readInner { $0.children[slot].formSuccessor(of: &i) }
if success { return true }
slot += 1
guard slot < childCount else { return false }
i[height: h] = slot
i.clear(below: h)
return true
}
func formPredecessor(of i: inout Index) -> Bool {
let h = self.height
var slot = i[height: h]
var slot = i._path[h]
if h == 0 {
guard slot > 0 else { return false }
i[height: h] = slot - 1
guard slot > 0 else {
return false
}
i._path[h] = slot &- 1
i._leaf = asUnmanagedLeaf
return true
}
return readInner {
@@ -395,17 +424,21 @@ extension _Rope.Node {
if slot < c.count, c[slot].formPredecessor(of: &i) {
return true
}
guard slot > 0 else { return false }
guard slot > 0 else {
return false
}
slot -= 1
i[height: h] = slot
c[slot].descendToLastItem(under: &i)
i._path[h] = slot
i._leaf = c[slot].descendToLastItem(under: &i._path)
return true
}
}
}
extension _Rope.Node {
var lastItem: Item {
get {
self[lastIndex]
self[lastPath]
}
_modify {
assert(childCount > 0)
@@ -413,87 +446,89 @@ extension _Rope.Node {
defer {
_ = _finalizeModify(&state)
}
yield &state.value
yield &state.item
}
}
var firstItem: Item {
get {
self[startIndex]
self[startPath]
}
_modify {
yield &self[startIndex]
yield &self[startPath]
}
}
subscript(i: Index) -> Item {
subscript(path: Path) -> Item {
get {
let h = height
let slot = i[height: h]
precondition(slot < childCount, "Index out of bounds")
let slot = path[h]
precondition(slot < childCount, "Path out of bounds")
guard h == 0 else {
return readInner { $0.children[slot][i] }
return readInner { $0.children[slot][path] }
}
return readLeaf { $0.children[slot] }
}
@inline(__always)
_modify {
var state = _prepareModify(at: i)
var state = _prepareModify(at: path)
defer {
_ = _finalizeModify(&state)
}
yield &state.value
yield &state.item
}
}
struct ModifyState {
var index: Index
var value: Item
var path: Path
var item: Item
var summary: Summary
}
mutating func _prepareModify(at i: Index) -> ModifyState {
mutating func _prepareModify(at path: Path) -> ModifyState {
ensureUnique()
let h = height
let slot = i[height: h]
precondition(slot < childCount, "Index out of bounds")
let slot = path[h]
precondition(slot < childCount, "Path out of bounds")
guard h == 0 else {
return updateInner { $0.mutableChildren[slot]._prepareModify(at: i) }
return updateInner { $0.mutableChildren[slot]._prepareModify(at: path) }
}
let value = updateLeaf { $0.mutableChildren.moveElement(from: slot) }
return ModifyState(index: i, value: value, summary: value.summary)
let item = updateLeaf { $0.mutableChildren.moveElement(from: slot) }
return ModifyState(path: path, item: item, summary: item.summary)
}
mutating func _prepareModifyLast() -> ModifyState {
var i = Index(height: height)
return _prepareModifyLast(&i)
var path = Path(height: height)
return _prepareModifyLast(&path)
}
mutating func _prepareModifyLast(_ i: inout Index) -> ModifyState {
mutating func _prepareModifyLast(_ path: inout Path) -> ModifyState {
ensureUnique()
let h = height
let slot = self.childCount - 1
i[height: h] = slot
path[h] = slot
guard h == 0 else {
return updateInner { $0.mutableChildren[slot]._prepareModifyLast(&i) }
return updateInner { $0.mutableChildren[slot]._prepareModifyLast(&path) }
}
let value = updateLeaf { $0.mutableChildren.moveElement(from: slot) }
return ModifyState(index: i, value: value, summary: value.summary)
let item = updateLeaf { $0.mutableChildren.moveElement(from: slot) }
return ModifyState(path: path, item: item, summary: item.summary)
}
mutating func _finalizeModify(_ state: inout ModifyState) -> Summary {
mutating func _finalizeModify(
_ state: inout ModifyState
) -> (delta: Summary, leaf: UnmanagedLeaf) {
assert(isUnique())
let h = height
let slot = state.index[height: h]
assert(slot < childCount, "Index out of bounds")
let slot = state.path[h]
assert(slot < childCount, "Path out of bounds")
guard h == 0 else {
let delta = updateInner { $0.mutableChildren[slot]._finalizeModify(&state) }
summary.add(delta)
return delta
let r = updateInner { $0.mutableChildren[slot]._finalizeModify(&state) }
summary.add(r.delta)
return r
}
let delta = state.value.summary.subtracting(state.summary)
updateLeaf { $0.mutableChildren.initializeElement(at: slot, to: state.value) }
let delta = state.item.summary.subtracting(state.summary)
updateLeaf { $0.mutableChildren.initializeElement(at: slot, to: state.item) }
summary.add(delta)
return delta
return (delta, asUnmanagedLeaf)
}
}
@@ -0,0 +1,43 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2023 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 {
struct UnmanagedLeaf {
typealias Item = _Rope.Item
typealias Leaf = Storage<Item>
typealias UnsafeHandle = _Rope.UnsafeHandle
var _ref: Unmanaged<Leaf>
init(_ leaf: __shared Leaf) {
_ref = .passUnretained(leaf)
}
}
}
extension _Rope.UnmanagedLeaf: Equatable {
static func ==(left: Self, right: Self) -> Bool {
left._ref.toOpaque() == right._ref.toOpaque()
}
}
extension _Rope.UnmanagedLeaf {
func read<R>(
body: (UnsafeHandle<Item>) -> R
) -> R {
_ref._withUnsafeGuaranteedRef { leaf in
leaf.withUnsafeMutablePointers { h, p in
let handle = UnsafeHandle(isMutable: false, header: h, start: p)
return body(handle)
}
}
}
}
@@ -185,4 +185,15 @@ extension _Rope.UnsafeHandle {
src.childCount -= count
return children.prefix(count)._sum()
}
func distance(from start: Int, to end: Int, in metric: some _RopeMetric<Element>) -> Int {
if start <= end {
return children[start ..< end].reduce(into: 0) {
$0 += metric.nonnegativeSize(of: $1.summary)
}
}
return -children[end ..< start].reduce(into: 0) {
$0 += metric.nonnegativeSize(of: $1.summary)
}
}
}
+6 -2
View File
@@ -14,15 +14,18 @@
/// quick lookup operations.
struct _Rope<Element: _RopeElement> {
var _root: Node?
var _version: _RopeVersion
init() {
self._root = nil
self._version = _RopeVersion()
}
init(root: Node?) {
self._root = root
self._version = _RopeVersion()
}
var root: Node {
get { _root.unsafelyUnwrapped }
@inline(__always) _modify { yield &_root! }
@@ -30,6 +33,7 @@ struct _Rope<Element: _RopeElement> {
init(_ value: Element) {
self._root = .createLeaf(Item(value))
self._version = _RopeVersion()
}
}
@@ -0,0 +1,98 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2023 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
//
//===----------------------------------------------------------------------===//
struct _RopePath<Summary: _RopeSummary> {
// ┌──────────────────────────────────┬────────┐
// │ b63:b8 │ b7:b0 │
// ├──────────────────────────────────┼────────┤
// │ path │ height │
// └──────────────────────────────────┴────────┘
var _value: UInt64
@inline(__always)
static var _pathBitWidth: Int { 56 }
init(height: UInt8) {
self._value = UInt64(truncatingIfNeeded: height)
assert((Int(height) + 1) * Summary.nodeSizeBitWidth <= Self._pathBitWidth)
}
}
extension _Rope {
typealias Path = _RopePath<Summary>
}
extension _RopePath: Equatable {
static func ==(left: Self, right: Self) -> Bool {
left._value == right._value
}
}
extension _RopePath: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(_value)
}
}
extension _RopePath: Comparable {
static func <(left: Self, right: Self) -> Bool {
left._value < right._value
}
}
extension _RopePath: CustomStringConvertible {
var description: String {
var r = "<"
for h in stride(from: height, through: 0, by: -1) {
r += "\(self[h])"
if h > 0 { r += ", " }
}
r += ">"
return r
}
}
extension _RopePath {
var height: UInt8 {
UInt8(truncatingIfNeeded: _value)
}
subscript(height: UInt8) -> Int {
get {
assert(height <= self.height)
let shift = 8 + Int(height) * Summary.nodeSizeBitWidth
let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1
return numericCast((_value &>> shift) & mask)
}
set {
assert(height <= self.height)
assert(newValue >= 0 && newValue <= Summary.maxNodeSize)
let shift = 8 + Int(height) * Summary.nodeSizeBitWidth
let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1
_value &= ~(mask &<< shift)
_value |= numericCast(newValue) &<< shift
}
}
func isEmpty(below height: UInt8) -> Bool {
let shift = Int(height) * Summary.nodeSizeBitWidth
assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth)
let mask: UInt64 = ((1 &<< shift) - 1) &<< 8
return (_value & mask) == 0
}
mutating func clear(below height: UInt8) {
let shift = Int(height) * Summary.nodeSizeBitWidth
assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth)
let mask: UInt64 = ((1 &<< shift) - 1) &<< 8
_value &= ~mask
}
}
@@ -0,0 +1,41 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2023 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
//
//===----------------------------------------------------------------------===//
struct _RopeVersion {
// FIXME: Replace this probabilistic mess with atomics when Swift gets its act together.
var _value: UInt
init() {
var rng = SystemRandomNumberGenerator()
_value = rng.next()
}
init(_ value: UInt) {
self._value = value
}
}
extension _RopeVersion: Equatable {
static func ==(left: Self, right: Self) -> Bool {
left._value == right._value
}
}
extension _RopeVersion {
mutating func bump() {
_value &+= 1
}
mutating func reset() {
var rng = SystemRandomNumberGenerator()
_value = rng.next()
}
}
@@ -9,21 +9,54 @@
//
//===----------------------------------------------------------------------===//
extension _Rope {
func isValid(_ index: Index) -> Bool {
index._version == _version
}
func validate(_ index: Index) {
precondition(isValid(index), "Invalid index")
}
mutating func invalidateIndices() {
_version.bump()
}
func ensureLeaf(in index: inout Index) {
validate(index)
guard index._leaf == nil else { return }
index._leaf = _unmanagedLeaf(at: index._path)
}
}
extension _Rope: BidirectionalCollection {
var height: UInt8 { _root?.height ?? 0 }
var height: UInt8 {
_root?.height ?? 0
}
var isEmpty: Bool {
guard _root != nil else { return true }
return root.childCount == 0
}
var startIndex: Index { Index(height: height) }
var startPath: Path {
Path(height: height)
}
var endPath: Path {
guard let root = _root else { return startPath }
var path = Path(height: height)
path[height] = root.childCount
return path
}
var startIndex: Index {
// Note: `leaf` is intentionally not set here, to speed up accessing this property.
return Index(version: _version, path: startPath, leaf: nil)
}
var endIndex: Index {
guard let root = _root else { return startIndex }
var i = Index(height: height)
i[height: height] = root.childCount
return i
Index(version: _version, path: endPath, leaf: nil)
}
func index(after i: Index) -> Index {
@@ -39,114 +72,75 @@ extension _Rope: BidirectionalCollection {
}
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
}
}
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")
}
subscript(i: Index) -> Element {
get { root[i].value }
@inline(__always) _modify { yield &root[i].value }
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 {
struct Index {
typealias Summary = _Rope.Summary
// ┌──────────────────────────────────┬────────┐
// │ b63:b8 │ b7:b0 │
// ├──────────────────────────────────┼────────┤
// │ path │ height │
// └──────────────────────────────────┴────────┘
var _path: UInt64
@inline(__always)
static var _pathBitWidth: Int { 56 }
init(height: UInt8) {
self._path = UInt64(truncatingIfNeeded: height)
assert((Int(height) + 1) * Summary.nodeSizeBitWidth <= Self._pathBitWidth)
/// Update the element at the given index, while keeping the index valid.
mutating func update<R>(
at index: inout Index,
by body: (inout Element) -> R
) -> R {
validate(index)
var state = root._prepareModify(at: index._path)
defer {
index._leaf = root._finalizeModify(&state).leaf
}
}
}
extension _Rope.Index: Equatable {
static func ==(left: Self, right: Self) -> Bool {
left._path == right._path
}
}
extension _Rope.Index: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(_path)
}
}
extension _Rope.Index: Comparable {
static func <(left: Self, right: Self) -> Bool {
left._path < right._path
}
}
extension _Rope.Index: CustomStringConvertible {
var description: String {
var r = "<"
for h in stride(from: height, through: 0, by: -1) {
r += "\(self[height: h])"
if h > 0 { r += ", " }
}
r += ">"
return r
}
}
extension _Rope.Index {
var height: UInt8 {
UInt8(truncatingIfNeeded: _path)
}
subscript(height height: UInt8) -> Int {
get {
assert(height <= self.height)
let shift = 8 + Int(height) * Summary.nodeSizeBitWidth
let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1
return numericCast((_path &>> shift) & mask)
}
set {
assert(height <= self.height)
assert(newValue >= 0 && newValue <= Summary.maxNodeSize)
let shift = 8 + Int(height) * Summary.nodeSizeBitWidth
let mask: UInt64 = (1 &<< Summary.nodeSizeBitWidth) &- 1
_path &= ~(mask &<< shift)
_path |= numericCast(newValue) &<< shift
}
}
func isEmpty(below height: UInt8) -> Bool {
let shift = Int(height) * Summary.nodeSizeBitWidth
assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth)
let mask: UInt64 = ((1 &<< shift) - 1) &<< 8
return (_path & mask) == 0
}
mutating func clear(below height: UInt8) {
let shift = Int(height) * Summary.nodeSizeBitWidth
assert(shift + Summary.nodeSizeBitWidth <= Self._pathBitWidth)
let mask: UInt64 = ((1 &<< shift) - 1) &<< 8
_path &= ~mask
return body(&state.item.value)
}
}
extension _Rope {
static var maxHeight: Int {
Index._pathBitWidth / Summary.nodeSizeBitWidth
Path._pathBitWidth / Summary.nodeSizeBitWidth
}
/// The estimated maximum number of items that can fit in this rope in the worst possible case,
@@ -195,8 +189,19 @@ extension _Rope.Node {
extension _Rope {
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)
}
@@ -204,29 +209,25 @@ extension _Rope {
}
func offset(of index: Index, in metric: some _RopeMetric<Element>) -> Int {
distance(from: startIndex, to: index, in: metric)
validate(index)
if _root == nil { return 0 }
return root.distanceFromStart(to: index, in: metric)
}
}
extension _Rope.Node {
func distanceFromStart(to index: Index, in metric: some _RopeMetric<Element>) -> Int {
let slot = index[height: height]
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.children[..<slot].reduce(into: 0) {
$0 += metric.nonnegativeSize(of: $1.summary)
}
}
return readLeaf { $0.distance(from: 0, to: slot, in: metric) }
}
return readInner {
var distance = $0.children[..<slot].reduce(into: 0) {
$0 += metric.nonnegativeSize(of: $1.summary)
}
var distance = $0.distance(from: 0, to: slot, in: metric)
distance += $0.children[slot].distanceFromStart(to: index, in: metric)
return distance
}
@@ -240,8 +241,8 @@ extension _Rope.Node {
func distance(from start: Index, to end: Index, in metric: some _RopeMetric<Element>) -> Int {
assert(start < end)
let a = start[height: height]
let b = end[height: height]
let a = start._path[height]
let b = end._path[height]
precondition(a < childCount, "Invalid index")
precondition(b <= childCount, "Invalid index")
assert(a <= b)
@@ -251,9 +252,7 @@ extension _Rope.Node {
}
if height == 0 {
assert(a < b)
return readLeaf {
$0.children[a..<b].reduce(into: 0) { $0 += metric.size(of: $1.summary) }
}
return readLeaf { $0.distance(from: a, to: b, in: metric) }
}
return readInner {
let c = $0.children
@@ -261,7 +260,7 @@ extension _Rope.Node {
return c[a].distance(from: start, to: end, in: metric)
}
var d = c[a].distanceToEnd(from: start, in: metric)
d += c[(a + 1) ..< b].reduce(into: 0) { $0 += metric.nonnegativeSize(of: $1.summary) }
d += $0.distance(from: a + 1, to: b, in: metric)
d += c[b].distanceFromStart(to: end, in: metric)
return d
}
@@ -275,6 +274,7 @@ extension _Rope {
in metric: some _RopeMetric<Element>,
preferEnd: Bool
) {
validate(i)
if _root == nil {
precondition(distance == 0, "Position out of bounds")
return
@@ -286,6 +286,13 @@ extension _Rope {
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
}
@@ -294,7 +301,10 @@ extension _Rope {
}
func index(
_ i: Index, offsetBy distance: Int, in metric: some _RopeMetric<Element>, preferEnd: Bool
_ i: Index,
offsetBy distance: Int,
in metric: some _RopeMetric<Element>,
preferEnd: Bool
) -> (index: Index, remainder: Int) {
var i = i
var distance = distance
@@ -303,6 +313,53 @@ extension _Rope {
}
}
extension _Rope.UnsafeHandle {
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
}
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 {
func seekForward(
from i: inout Index,
@@ -311,26 +368,20 @@ extension _Rope.Node {
preferEnd: Bool
) -> Bool {
assert(distance >= 0)
var slot = i[height: height]
precondition(slot < childCount, "Invalid index")
if height == 0 {
return readLeaf {
let c = $0.children
while slot < c.count {
let d = metric.nonnegativeSize(of: c[slot].summary)
if preferEnd ? d >= distance : d > distance {
i[height: 0] = slot
return true
}
distance &-= d
slot &+= 1
}
return false
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
@@ -339,7 +390,7 @@ extension _Rope.Node {
while slot < c.count {
let d = metric.size(of: c[slot].summary)
if preferEnd ? d >= distance : d > distance {
i[height: $0.height] = slot
i._path[$0.height] = slot
i.clear(below: $0.height)
let success = c[slot].seekForward(
from: &i, by: &distance, in: metric, preferEnd: preferEnd)
@@ -361,28 +412,15 @@ extension _Rope.Node {
) -> Bool {
assert(distance >= 0)
guard distance > 0 || preferEnd else { return true }
var slot = i[height: height]
precondition(slot <= childCount, "Invalid index")
if height == 0 {
return readLeaf {
let c = $0.children
slot &-= 1
while slot >= 0 {
let d = metric.nonnegativeSize(of: c[slot].summary)
if preferEnd ? d > distance : d >= distance {
i[height: 0] = slot
distance = d &- distance
return true
}
distance &-= d
slot &-= 1
}
return false
$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) {
@@ -392,7 +430,7 @@ extension _Rope.Node {
while slot >= 0 {
let d = metric.size(of: c[slot].summary)
if preferEnd ? d > distance : d >= distance {
i[height: $0.height] = slot
i._path[$0.height] = slot
i.clear(below: $0.height)
distance = d - distance
let success = c[slot].seekForward(
@@ -0,0 +1,67 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2023 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 {
struct Index {
typealias Path = _Rope.Path
typealias Summary = _Rope.Summary
var _version: _RopeVersion
var _path: Path
/// A direct reference to the leaf node addressed by this index.
/// This must only be dereferenced while we own a tree with a matching
/// version.
var _leaf: UnmanagedLeaf?
init(version: _RopeVersion, path: Path, leaf: __shared UnmanagedLeaf?) {
self._version = version
self._path = path
self._leaf = leaf
}
}
}
extension _Rope.Index: Equatable {
static func ==(left: Self, right: Self) -> Bool {
left._path == right._path
}
}
extension _Rope.Index: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(_path)
}
}
extension _Rope.Index: Comparable {
static func <(left: Self, right: Self) -> Bool {
left._path < right._path
}
}
extension _Rope.Index: CustomStringConvertible {
var description: String {
"\(_path)"
}
}
extension _Rope.Index {
var height: UInt8 {
_path.height
}
func isEmpty(below height: UInt8) -> Bool {
_path.isEmpty(below: height)
}
mutating func clear(below height: UInt8) {
_path.clear(below: height)
}
}
@@ -21,16 +21,16 @@ extension _Rope: Sequence {
struct Iterator: IteratorProtocol {
let rope: _Rope
private(set) var index: Index
private var leaf: Node?
init(_ rope: _Rope, from start: Index) {
rope.validate(start)
self.rope = rope
self.index = start
self.leaf = start == rope.endIndex ? nil : rope._leaf(at: start)
self.rope.ensureLeaf(in: &index)
}
var isAtEnd: Bool {
leaf == nil
index._leaf == nil
}
var isAtStart: Bool {
@@ -38,48 +38,35 @@ extension _Rope: Sequence {
}
var current: Element {
leaf!.readLeaf { $0.children[index[height: 0]].value }
guard let leaf = index._leaf else {
preconditionFailure("Cannot access current element in iterator at end")
}
return leaf.read { $0.children[index._path[0]].value }
}
func withCurrent<R>(_ body: (Element) -> R) -> R {
leaf!.readLeaf { body($0.children[index[height: 0]].value) }
guard let leaf = index._leaf else {
preconditionFailure("Cannot access current element in iterator at end")
}
return leaf.read { body($0.children[index._path[0]].value) }
}
mutating func stepForward() -> Bool {
guard let leaf = self.leaf else { return false }
self.leaf = nil
if leaf.formSuccessor(of: &index) {
self.leaf = leaf
} else if rope.root.formSuccessor(of: &index) {
self.leaf = rope._leaf(at: index)
} else {
self.leaf = leaf
return false
}
let end = rope.endPath
guard index._path < end else { return false }
let next = rope.index(after: index)
guard next._path < end else { return false }
index = next
return true
}
mutating func stepBackward() -> Bool {
guard let leaf = self.leaf else {
guard !rope.isEmpty else { return false }
self.index = rope.index(before: rope.endIndex)
self.leaf = rope._leaf(at: index)
return true
}
self.leaf = nil
if leaf.formPredecessor(of: &index) {
self.leaf = leaf
} else if rope.root.formPredecessor(of: &index) {
self.leaf = rope._leaf(at: index)
} else {
self.leaf = leaf
return false
}
guard index._path > rope.startPath else { return false }
rope.formIndex(before: &index)
return true
}
mutating func stepToEnd() {
leaf = nil
index = rope.endIndex
}
@@ -95,12 +82,19 @@ extension _Rope: Sequence {
}
extension _Rope {
func _leaf(at index: Index) -> Node? {
assert(index.height == root.height)
func _unmanagedLeaf(at path: Path) -> UnmanagedLeaf? {
assert(path.height == self.height)
guard path < endPath else { return nil }
return root.unmanagedLeaf(at: path)
}
func _leaf(at path: Path) -> Node? {
assert(path.height == self.height)
guard _root != nil else { return nil }
var node = root
while true {
let h = node.height
let slot = index[height: h]
let slot = path[h]
guard slot < node.childCount else { return nil }
if h == 0 { break }
node = node.readInner { $0.child(at: slot)! }
@@ -11,6 +11,7 @@
extension _Rope {
mutating func append(_ item: __owned Element) {
invalidateIndices()
if _root == nil {
_root = .createLeaf(Item(item))
return
@@ -14,26 +14,27 @@ extension _Rope {
at position: Int,
in metric: some _RopeMetric<Element>,
preferEnd: Bool
) -> (index: Index, node: Node?, remaining: Int) {
) -> (index: Index, remaining: Int) {
let wholeSize = _root == nil ? 0 : metric.size(of: root.summary)
precondition(position >= 0 && position <= wholeSize, "Position out of bounds")
guard preferEnd || position < wholeSize else {
return (endIndex, nil, position)
return (endIndex, position)
}
var position = position
var node = root
var index = Index(height: node.height)
var path = Path(height: node.height)
while node.height > 0 {
node = node.readInner {
let r = $0.findSlot(at: position, in: metric, preferEnd: preferEnd)
position = r.remaining
index[height: $0.height] = r.slot
path[$0.height] = r.slot
return $0.children[r.slot]
}
}
let r = node.readLeaf { $0.findSlot(at: position, in: metric, preferEnd: preferEnd) }
index[height: 0] = r.slot
return (index, node, r.remaining)
path[0] = r.slot
let index = Index(version: _version, path: path, leaf: node.asUnmanagedLeaf)
return (index, r.remaining)
}
}
@@ -11,6 +11,7 @@
extension _Rope {
mutating func prepend(_ item: __owned Element) {
invalidateIndices()
insert(item, at: startIndex)
}
@@ -18,13 +19,22 @@ extension _Rope {
_ item: __owned Element,
at index: Index
) {
if index == endIndex {
validate(index)
insert(item, at: index._path)
}
mutating func insert(
_ item: __owned Element,
at path: Path
) {
if path == endPath {
append(item)
return
}
if let spawn = root.insert(Item(item), at: index) {
if let spawn = root.insert(Item(item), at: path) {
_root = .createInner(children: root, spawn)
}
invalidateIndices()
}
mutating func insert(
@@ -39,24 +49,25 @@ extension _Rope {
if let spawn = root.insert(Item(item), at: position, in: metric) {
_root = .createInner(children: root, spawn)
}
invalidateIndices()
}
}
extension _Rope.Node {
mutating func prepend(_ item: __owned Item) -> Self? {
insert(item, at: startIndex)
insert(item, at: startPath)
}
mutating func insert(
_ item: __owned Item,
at index: Index
at path: Path
) -> Self? {
ensureUnique()
let h = height
let slot = index[height: h]
let slot = path[h]
if h > 0 {
precondition(slot < childCount, "Index out of bounds")
return _innerInsert(at: slot) { $0.insert(item, at: index) }
return _innerInsert(at: slot) { $0.insert(item, at: path) }
}
precondition(slot <= childCount, "Index out of bounds")
return _leafInsert(item, at: slot)
@@ -38,8 +38,14 @@ extension _Rope {
from index: inout Index,
_ body: (inout Element) -> Bool
) -> Bool {
validate(index)
guard _root != nil else { return true }
return root.mutatingForEach(from: &index, body: body).continue
defer {
invalidateIndices()
index._version = _version
}
let r = root.mutatingForEach(from: &index, body: body).continue
return r
}
}
@@ -50,7 +56,7 @@ extension _Rope.Node {
) -> (continue: Bool, delta: Summary) {
ensureUnique()
let h = height
var slot = index[height: h]
var slot = index._path[h]
precondition(slot <= childCount, "Index out of bounds")
guard slot < childCount else { return (true, .zero) }
var delta = Summary.zero
@@ -63,13 +69,15 @@ extension _Rope.Node {
delta.add(d)
guard r else { return false }
slot += 1
index.clear(below: h)
index[height: h] = slot
index._path.clear(below: h)
index._path[h] = slot
}
index._leaf = nil
return true
}
return (r, delta)
}
index._leaf = asUnmanagedLeaf
let r = updateLeaf {
let c = $0.mutableChildren
while slot < c.count {
@@ -78,7 +86,7 @@ extension _Rope.Node {
delta.add(c[slot].summary.subtracting(sum))
guard r else { return false }
slot += 1
index[height: h] = slot
index._path[h] = slot
}
return true
}
@@ -11,28 +11,30 @@
extension _Rope {
mutating func remove(at index: Index) -> Element {
let old = root.remove(at: index).removed
validate(index)
let old = root.remove(at: index._path).removed
if root.isEmpty {
_root = nil
} else if root.childCount == 1, root.height > 0 {
root = root.readInner { $0.children.first! }
}
invalidateIndices()
return old.value
}
}
extension _Rope.Node {
mutating func remove(
at index: Index
at path: Path
) -> (removed: Item, delta: Summary, needsFixing: Bool) {
ensureUnique()
let slot = index[height: height]
let slot = path[height]
precondition(slot < childCount, "Invalid index")
guard height > 0 else {
let r = _removeItem(at: slot)
return (r.removed, r.delta, self.isUndersized)
}
let r = updateInner { $0.mutableChildren[slot].remove(at: index) }
let r = updateInner { $0.mutableChildren[slot].remove(at: path) }
self.summary.subtract(r.delta)
if r.needsFixing {
fixDeficiency(at: slot)
@@ -46,6 +48,7 @@ extension _Rope {
at position: Int,
in metric: some _RopeMetric<Element>
) -> Element {
invalidateIndices()
let old = root.remove(at: position, in: metric).removed
if root.isEmpty {
_root = nil
@@ -14,6 +14,7 @@ extension _Rope {
_ bounds: Range<Int>,
in metric: some _RopeMetric<Element>
) {
invalidateIndices()
precondition(
bounds.lowerBound >= 0 && bounds.upperBound <= count(in: metric),
"Position out of bounds")
@@ -31,6 +32,7 @@ extension _Rope {
// FIXME: Implement insert(contentsOf:at:in:) and dispatch to it when bounds.isEmpty.
// FIXME: Add fast path for replacing tiny ranges with tiny data.
// FIXME: Add special cases if newElements is itself a _Rope etc.
invalidateIndices()
var builder = builder(removing: bounds, in: metric)
for item in newElements {
builder.append(item)
@@ -42,6 +44,7 @@ extension _Rope {
removing bounds: Range<Int>,
in metric: some _RopeMetric<Element>
) -> Builder {
invalidateIndices()
let size = metric.size(of: summary)
precondition(
bounds.lowerBound >= 0 && bounds.upperBound <= size,
@@ -14,6 +14,7 @@ extension _Rope {
splittingAt position: Int,
in metric: some _RopeMetric<Element>
) -> Builder {
invalidateIndices()
var builder = Builder()
var position = position
@@ -35,20 +36,22 @@ extension _Rope {
}
mutating func split(at index: Index) -> (builder: Builder, item: Element) {
validate(index)
precondition(index < endIndex)
var builder = Builder()
var node = root
_root = nil
while !node.isLeaf {
let slot = index[height: node.height]
let slot = index._path[node.height]
precondition(slot < node.childCount, "Index out of bounds")
node._innerSplit(at: slot, into: &builder)
}
let slot = index[height: node.height]
let slot = index._path[node.height]
precondition(slot < node.childCount, "Index out of bounds")
let item = node._leafSplit(at: slot, into: &builder)
invalidateIndices()
return (builder, item.value)
}
+11 -2
View File
@@ -150,8 +150,17 @@ class TestRope: XCTestCase {
Chunk(length: ($0 % 4) + 1, value: $0)
}
let rope = _Rope(ref)
XCTAssertTrue(rope.elementsEqual(ref))
var it = rope.makeIterator()
var i = 0
while let next = it.next() {
let expected = ref[i]
XCTAssertEqual(next, expected)
guard next == expected else { break }
i += 1
}
XCTAssertEqual(i, ref.count)
let expectedLength = ref.reduce(into: 0) { $0 += $1.length }
let actualLength = rope.reduce(into: 0) { $0 += $1.length }
XCTAssertEqual(actualLength, expectedLength)
@@ -20,6 +20,20 @@
ReferencedContainer = "container:..">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "RopeModuleTests"
BuildableName = "RopeModuleTests"
BlueprintName = "RopeModuleTests"
ReferencedContainer = "container:..">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction