From 7335b50117c8092255dc64ad70f751c14535d01c Mon Sep 17 00:00:00 2001 From: Luiz Fernando Silva Date: Tue, 23 Jul 2024 16:01:53 -0300 Subject: [PATCH] Deferring deep copy of KDTree to the point where actual reference-type mutation occurs --- .../SpatialPartitioning/KDTree/KDTree.swift | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Sources/GeometriaAlgorithms/SpatialPartitioning/KDTree/KDTree.swift b/Sources/GeometriaAlgorithms/SpatialPartitioning/KDTree/KDTree.swift index 433c7ae6..c7a2017e 100644 --- a/Sources/GeometriaAlgorithms/SpatialPartitioning/KDTree/KDTree.swift +++ b/Sources/GeometriaAlgorithms/SpatialPartitioning/KDTree/KDTree.swift @@ -110,8 +110,6 @@ public struct KDTree 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( @@ -130,13 +128,12 @@ public struct KDTree 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 } @@ -155,14 +152,20 @@ public struct KDTree 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.