Skip to content

Commit

Permalink
Deferring deep copy of KDTree to the point where actual reference-typ…
Browse files Browse the repository at this point in the history
…e mutation occurs
  • Loading branch information
LuizZak committed Jul 23, 2024
1 parent 46f9a29 commit 7335b50
Showing 1 changed file with 8 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,6 @@ public struct KDTree<Element: KDTreeLocatable> where Element.Vector: VectorCompa

/// Inserts a given element on this k-d tree.
public mutating func insert(_ element: Element) {
ensureUnique()

guard let root else {
root = Subdivision(
state: .empty(
Expand All @@ -130,13 +128,12 @@ public struct KDTree<Element: KDTreeLocatable> where Element.Vector: VectorCompa
let path = subdivisionPath(forInserting: element)
let reversed = path.reversed

ensureUnique()
root.inserting(element, path: reversed.asPath)
}

/// If `element` is contained within this k-d tree, it is removed in-place.
public mutating func remove(_ element: Element) where Element: Equatable {
ensureUnique()

guard let root else {
return
}
Expand All @@ -155,14 +152,20 @@ public struct KDTree<Element: KDTreeLocatable> where Element.Vector: VectorCompa

/// Removes an element at a given index in this k-d tree.
public mutating func remove(at index: Index) {
ensureUnique()
guard let root, root.pathExists(index.path) else {
fatalError("Index \(index) is not part of this k-d tree.")
}

ensureUnique()
self.root = root.removing(at: index.path)
}

/// Removes all elements contained within this k-d tree.
public mutating func removeAll() {
ensureUnique()
root = nil
}

/// Encodes a path to a specific subdivision within a k-d tree.
public enum SubdivisionPath: Hashable, CustomStringConvertible {
/// Specifies the root element.
Expand Down

0 comments on commit 7335b50

Please sign in to comment.