| 1 |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license |
| 2 |
|
| 3 |
""" |
| 4 |
A BTree in the style of Cormen, Leiserson, and Rivest's "Algorithms" book, with |
| 5 |
copy-on-write node updates, cursors, and optional space optimization for mostly-in-order |
| 6 |
insertion. |
| 7 |
""" |
| 8 |
|
| 9 |
from collections.abc import MutableMapping, MutableSet |
| 10 |
from typing import Any, Callable, Generic, Optional, Tuple, TypeVar, cast |
| 11 |
|
| 12 |
DEFAULT_T = 127 |
| 13 |
|
| 14 |
KT = TypeVar("KT") # the type of a key in Element |
| 15 |
|
| 16 |
|
| 17 |
class Element(Generic[KT]): |
| 18 |
"""All items stored in the BTree are Elements.""" |
| 19 |
|
| 20 |
def key(self) -> KT: |
| 21 |
"""The key for this element; the returned type must implement comparison.""" |
| 22 |
raise NotImplementedError # pragma: no cover |
| 23 |
|
| 24 |
|
| 25 |
ET = TypeVar("ET", bound=Element) # the type of a value in a _KV |
| 26 |
|
| 27 |
|
| 28 |
def _MIN(t: int) -> int: |
| 29 |
"""The minimum number of keys in a non-root node for a BTree with the specified |
| 30 |
``t`` |
| 31 |
""" |
| 32 |
return t - 1 |
| 33 |
|
| 34 |
|
| 35 |
def _MAX(t: int) -> int: |
| 36 |
"""The maximum number of keys in node for a BTree with the specified ``t``""" |
| 37 |
return 2 * t - 1 |
| 38 |
|
| 39 |
|
| 40 |
class _Creator: |
| 41 |
"""A _Creator class instance is used as a unique id for the BTree which created |
| 42 |
a node. |
| 43 |
|
| 44 |
We use a dedicated creator rather than just a BTree reference to avoid circularity |
| 45 |
that would complicate GC. |
| 46 |
""" |
| 47 |
|
| 48 |
def __str__(self): # pragma: no cover |
| 49 |
return f"{id(self):x}" |
| 50 |
|
| 51 |
|
| 52 |
class _Node(Generic[KT, ET]): |
| 53 |
"""A Node in the BTree. |
| 54 |
|
| 55 |
A Node (leaf or internal) of the BTree. |
| 56 |
""" |
| 57 |
|
| 58 |
__slots__ = ["t", "creator", "is_leaf", "elts", "children"] |
| 59 |
|
| 60 |
def __init__(self, t: int, creator: _Creator, is_leaf: bool): |
| 61 |
assert t >= 3 |
| 62 |
self.t = t |
| 63 |
self.creator = creator |
| 64 |
self.is_leaf = is_leaf |
| 65 |
self.elts: list[ET] = [] |
| 66 |
self.children: list[_Node[KT, ET]] = [] |
| 67 |
|
| 68 |
def is_maximal(self) -> bool: |
| 69 |
"""Does this node have the maximal number of keys?""" |
| 70 |
assert len(self.elts) <= _MAX(self.t) |
| 71 |
return len(self.elts) == _MAX(self.t) |
| 72 |
|
| 73 |
def is_minimal(self) -> bool: |
| 74 |
"""Does this node have the minimal number of keys?""" |
| 75 |
assert len(self.elts) >= _MIN(self.t) |
| 76 |
return len(self.elts) == _MIN(self.t) |
| 77 |
|
| 78 |
def search_in_node(self, key: KT) -> tuple[int, bool]: |
| 79 |
"""Get the index of the ``Element`` matching ``key`` or the index of its |
| 80 |
least successor. |
| 81 |
|
| 82 |
Returns a tuple of the index and an ``equal`` boolean that is ``True`` iff. |
| 83 |
the key was found. |
| 84 |
""" |
| 85 |
l = len(self.elts) |
| 86 |
if l > 0 and key > self.elts[l - 1].key(): |
| 87 |
# This is optimizing near in-order insertion. |
| 88 |
return l, False |
| 89 |
l = 0 |
| 90 |
i = len(self.elts) |
| 91 |
r = i - 1 |
| 92 |
equal = False |
| 93 |
while l <= r: |
| 94 |
m = (l + r) // 2 |
| 95 |
k = self.elts[m].key() |
| 96 |
if key == k: |
| 97 |
i = m |
| 98 |
equal = True |
| 99 |
break |
| 100 |
elif key < k: |
| 101 |
i = m |
| 102 |
r = m - 1 |
| 103 |
else: |
| 104 |
l = m + 1 |
| 105 |
return i, equal |
| 106 |
|
| 107 |
def maybe_cow_child(self, index: int) -> "_Node[KT, ET]": |
| 108 |
assert not self.is_leaf |
| 109 |
child = self.children[index] |
| 110 |
cloned = child.maybe_cow(self.creator) |
| 111 |
if cloned: |
| 112 |
self.children[index] = cloned |
| 113 |
return cloned |
| 114 |
else: |
| 115 |
return child |
| 116 |
|
| 117 |
def _get_node(self, key: KT) -> Tuple[Optional["_Node[KT, ET]"], int]: |
| 118 |
"""Get the node associated with key and its index, doing |
| 119 |
copy-on-write if we have to descend. |
| 120 |
|
| 121 |
Returns a tuple of the node and the index, or the tuple ``(None, 0)`` |
| 122 |
if the key was not found. |
| 123 |
""" |
| 124 |
i, equal = self.search_in_node(key) |
| 125 |
if equal: |
| 126 |
return (self, i) |
| 127 |
elif self.is_leaf: |
| 128 |
return (None, 0) |
| 129 |
else: |
| 130 |
child = self.maybe_cow_child(i) |
| 131 |
return child._get_node(key) |
| 132 |
|
| 133 |
def get(self, key: KT) -> ET | None: |
| 134 |
"""Get the element associated with *key* or return ``None``""" |
| 135 |
i, equal = self.search_in_node(key) |
| 136 |
if equal: |
| 137 |
return self.elts[i] |
| 138 |
elif self.is_leaf: |
| 139 |
return None |
| 140 |
else: |
| 141 |
return self.children[i].get(key) |
| 142 |
|
| 143 |
def optimize_in_order_insertion(self, index: int) -> None: |
| 144 |
"""Try to minimize the number of Nodes in a BTree where the insertion |
| 145 |
is done in-order or close to it, by stealing as much as we can from our |
| 146 |
right sibling. |
| 147 |
|
| 148 |
If we don't do this, then an in-order insertion will produce a BTree |
| 149 |
where most of the nodes are minimal. |
| 150 |
""" |
| 151 |
if index == 0: |
| 152 |
return |
| 153 |
left = self.children[index - 1] |
| 154 |
if len(left.elts) == _MAX(self.t): |
| 155 |
return |
| 156 |
left = self.maybe_cow_child(index - 1) |
| 157 |
while len(left.elts) < _MAX(self.t): |
| 158 |
if not left.try_right_steal(self, index - 1): |
| 159 |
break |
| 160 |
|
| 161 |
def insert_nonfull(self, element: ET, in_order: bool) -> ET | None: |
| 162 |
assert not self.is_maximal() |
| 163 |
while True: |
| 164 |
key = element.key() |
| 165 |
i, equal = self.search_in_node(key) |
| 166 |
if equal: |
| 167 |
# replace |
| 168 |
old = self.elts[i] |
| 169 |
self.elts[i] = element |
| 170 |
return old |
| 171 |
elif self.is_leaf: |
| 172 |
self.elts.insert(i, element) |
| 173 |
return None |
| 174 |
else: |
| 175 |
child = self.maybe_cow_child(i) |
| 176 |
if child.is_maximal(): |
| 177 |
self.adopt(*child.split()) |
| 178 |
# Splitting might result in our target moving to us, so |
| 179 |
# search again. |
| 180 |
continue |
| 181 |
oelt = child.insert_nonfull(element, in_order) |
| 182 |
if in_order: |
| 183 |
self.optimize_in_order_insertion(i) |
| 184 |
return oelt |
| 185 |
|
| 186 |
def split(self) -> tuple["_Node[KT, ET]", ET, "_Node[KT, ET]"]: |
| 187 |
"""Split a maximal node into two minimal ones and a central element.""" |
| 188 |
assert self.is_maximal() |
| 189 |
right = self.__class__(self.t, self.creator, self.is_leaf) |
| 190 |
right.elts = list(self.elts[_MIN(self.t) + 1 :]) |
| 191 |
middle = self.elts[_MIN(self.t)] |
| 192 |
self.elts = list(self.elts[: _MIN(self.t)]) |
| 193 |
if not self.is_leaf: |
| 194 |
right.children = list(self.children[_MIN(self.t) + 1 :]) |
| 195 |
self.children = list(self.children[: _MIN(self.t) + 1]) |
| 196 |
return self, middle, right |
| 197 |
|
| 198 |
def try_left_steal(self, parent: "_Node[KT, ET]", index: int) -> bool: |
| 199 |
"""Try to steal from this Node's left sibling for balancing purposes. |
| 200 |
|
| 201 |
Returns ``True`` if the theft was successful, or ``False`` if not. |
| 202 |
""" |
| 203 |
if index != 0: |
| 204 |
left = parent.children[index - 1] |
| 205 |
if not left.is_minimal(): |
| 206 |
left = parent.maybe_cow_child(index - 1) |
| 207 |
elt = parent.elts[index - 1] |
| 208 |
parent.elts[index - 1] = left.elts.pop() |
| 209 |
self.elts.insert(0, elt) |
| 210 |
if not left.is_leaf: |
| 211 |
assert not self.is_leaf |
| 212 |
child = left.children.pop() |
| 213 |
self.children.insert(0, child) |
| 214 |
return True |
| 215 |
return False |
| 216 |
|
| 217 |
def try_right_steal(self, parent: "_Node[KT, ET]", index: int) -> bool: |
| 218 |
"""Try to steal from this Node's right sibling for balancing purposes. |
| 219 |
|
| 220 |
Returns ``True`` if the theft was successful, or ``False`` if not. |
| 221 |
""" |
| 222 |
if index + 1 < len(parent.children): |
| 223 |
right = parent.children[index + 1] |
| 224 |
if not right.is_minimal(): |
| 225 |
right = parent.maybe_cow_child(index + 1) |
| 226 |
elt = parent.elts[index] |
| 227 |
parent.elts[index] = right.elts.pop(0) |
| 228 |
self.elts.append(elt) |
| 229 |
if not right.is_leaf: |
| 230 |
assert not self.is_leaf |
| 231 |
child = right.children.pop(0) |
| 232 |
self.children.append(child) |
| 233 |
return True |
| 234 |
return False |
| 235 |
|
| 236 |
def adopt(self, left: "_Node[KT, ET]", middle: ET, right: "_Node[KT, ET]") -> None: |
| 237 |
"""Adopt left, middle, and right into our Node (which must not be maximal, |
| 238 |
and which must not be a leaf). In the case were we are not the new root, |
| 239 |
then the left child must already be in the Node.""" |
| 240 |
assert not self.is_maximal() |
| 241 |
assert not self.is_leaf |
| 242 |
key = middle.key() |
| 243 |
i, equal = self.search_in_node(key) |
| 244 |
assert not equal |
| 245 |
self.elts.insert(i, middle) |
| 246 |
if len(self.children) == 0: |
| 247 |
# We are the new root |
| 248 |
self.children = [left, right] |
| 249 |
else: |
| 250 |
assert self.children[i] == left |
| 251 |
self.children.insert(i + 1, right) |
| 252 |
|
| 253 |
def merge(self, parent: "_Node[KT, ET]", index: int) -> None: |
| 254 |
"""Merge this node's parent and its right sibling into this node.""" |
| 255 |
right = parent.children.pop(index + 1) |
| 256 |
self.elts.append(parent.elts.pop(index)) |
| 257 |
self.elts.extend(right.elts) |
| 258 |
if not self.is_leaf: |
| 259 |
self.children.extend(right.children) |
| 260 |
|
| 261 |
def minimum(self) -> ET: |
| 262 |
"""The least element in this subtree.""" |
| 263 |
if self.is_leaf: |
| 264 |
return self.elts[0] |
| 265 |
else: |
| 266 |
return self.children[0].minimum() |
| 267 |
|
| 268 |
def maximum(self) -> ET: |
| 269 |
"""The greatest element in this subtree.""" |
| 270 |
if self.is_leaf: |
| 271 |
return self.elts[-1] |
| 272 |
else: |
| 273 |
return self.children[-1].maximum() |
| 274 |
|
| 275 |
def balance(self, parent: "_Node[KT, ET]", index: int) -> None: |
| 276 |
"""This Node is minimal, and we want to make it non-minimal so we can delete. |
| 277 |
We try to steal from our siblings, and if that doesn't work we will merge |
| 278 |
with one of them.""" |
| 279 |
assert not parent.is_leaf |
| 280 |
if self.try_left_steal(parent, index): |
| 281 |
return |
| 282 |
if self.try_right_steal(parent, index): |
| 283 |
return |
| 284 |
# Stealing didn't work, so both siblings must be minimal. |
| 285 |
if index == 0: |
| 286 |
# We are the left-most node so merge with our right sibling. |
| 287 |
self.merge(parent, index) |
| 288 |
else: |
| 289 |
# Have our left sibling merge with us. This lets us only have "merge right" |
| 290 |
# code. |
| 291 |
left = parent.maybe_cow_child(index - 1) |
| 292 |
left.merge(parent, index - 1) |
| 293 |
|
| 294 |
def delete( |
| 295 |
self, key: KT, parent: Optional["_Node[KT, ET]"], exact: ET | None |
| 296 |
) -> ET | None: |
| 297 |
"""Delete an element matching *key* if it exists. If *exact* is not ``None`` |
| 298 |
then it must be an exact match with that element. The Node must not be |
| 299 |
minimal unless it is the root.""" |
| 300 |
assert parent is None or not self.is_minimal() |
| 301 |
i, equal = self.search_in_node(key) |
| 302 |
original_key = None |
| 303 |
if equal: |
| 304 |
# Note we use "is" here as we meant "exactly this object". |
| 305 |
if exact is not None and self.elts[i] is not exact: |
| 306 |
raise ValueError("exact delete did not match existing elt") |
| 307 |
if self.is_leaf: |
| 308 |
return self.elts.pop(i) |
| 309 |
# Note we need to ensure exact is None going forward as we've |
| 310 |
# already checked exactness and are about to change our target key |
| 311 |
# to the least successor. |
| 312 |
exact = None |
| 313 |
original_key = key |
| 314 |
least_successor = self.children[i + 1].minimum() |
| 315 |
key = least_successor.key() |
| 316 |
i = i + 1 |
| 317 |
if self.is_leaf: |
| 318 |
# No match |
| 319 |
if exact is not None: |
| 320 |
raise ValueError("exact delete had no match") |
| 321 |
return None |
| 322 |
# recursively delete in the appropriate child |
| 323 |
child = self.maybe_cow_child(i) |
| 324 |
if child.is_minimal(): |
| 325 |
child.balance(self, i) |
| 326 |
# Things may have moved. |
| 327 |
i, equal = self.search_in_node(key) |
| 328 |
assert not equal |
| 329 |
child = self.children[i] |
| 330 |
assert not child.is_minimal() |
| 331 |
elt = child.delete(key, self, exact) |
| 332 |
if original_key is not None: |
| 333 |
node, i = self._get_node(original_key) |
| 334 |
assert node is not None |
| 335 |
assert elt is not None |
| 336 |
oelt = node.elts[i] |
| 337 |
node.elts[i] = elt |
| 338 |
elt = oelt |
| 339 |
return elt |
| 340 |
|
| 341 |
def visit_in_order(self, visit: Callable[[ET], None]) -> None: |
| 342 |
"""Call *visit* on all of the elements in order.""" |
| 343 |
for i, elt in enumerate(self.elts): |
| 344 |
if not self.is_leaf: |
| 345 |
self.children[i].visit_in_order(visit) |
| 346 |
visit(elt) |
| 347 |
if not self.is_leaf: |
| 348 |
self.children[-1].visit_in_order(visit) |
| 349 |
|
| 350 |
def _visit_preorder_by_node(self, visit: Callable[["_Node[KT, ET]"], None]) -> None: |
| 351 |
"""Visit nodes in preorder. This method is only used for testing.""" |
| 352 |
visit(self) |
| 353 |
if not self.is_leaf: |
| 354 |
for child in self.children: |
| 355 |
child._visit_preorder_by_node(visit) |
| 356 |
|
| 357 |
def maybe_cow(self, creator: _Creator) -> Optional["_Node[KT, ET]"]: |
| 358 |
"""Return a clone of this Node if it was not created by *creator*, or ``None`` |
| 359 |
otherwise (i.e. copy for copy-on-write if we haven't already copied it).""" |
| 360 |
if self.creator is not creator: |
| 361 |
return self.clone(creator) |
| 362 |
else: |
| 363 |
return None |
| 364 |
|
| 365 |
def clone(self, creator: _Creator) -> "_Node[KT, ET]": |
| 366 |
"""Make a shallow-copy duplicate of this node.""" |
| 367 |
cloned = self.__class__(self.t, creator, self.is_leaf) |
| 368 |
cloned.elts.extend(self.elts) |
| 369 |
if not self.is_leaf: |
| 370 |
cloned.children.extend(self.children) |
| 371 |
return cloned |
| 372 |
|
| 373 |
def __str__(self): # pragma: no cover |
| 374 |
if not self.is_leaf: |
| 375 |
children = " " + " ".join([f"{id(c):x}" for c in self.children]) |
| 376 |
else: |
| 377 |
children = "" |
| 378 |
return f"{id(self):x} {self.creator} {self.elts}{children}" |
| 379 |
|
| 380 |
|
| 381 |
class Cursor(Generic[KT, ET]): |
| 382 |
"""A seekable cursor for a BTree. |
| 383 |
|
| 384 |
If you are going to use a cursor on a mutable BTree, you should use it |
| 385 |
in a ``with`` block so that any mutations of the BTree automatically park |
| 386 |
the cursor. |
| 387 |
""" |
| 388 |
|
| 389 |
def __init__(self, btree: "BTree[KT, ET]"): |
| 390 |
self.btree = btree |
| 391 |
self.current_node: _Node | None = None |
| 392 |
# The current index is the element index within the current node, or |
| 393 |
# if there is no current node then it is 0 on the left boundary and 1 |
| 394 |
# on the right boundary. |
| 395 |
self.current_index: int = 0 |
| 396 |
self.recurse = False |
| 397 |
self.increasing = True |
| 398 |
self.parents: list[tuple[_Node, int]] = [] |
| 399 |
self.parked = False |
| 400 |
self.parking_key: KT | None = None |
| 401 |
self.parking_key_read = False |
| 402 |
|
| 403 |
def _seek_least(self) -> None: |
| 404 |
# seek to the least value in the subtree beneath the current index of the |
| 405 |
# current node |
| 406 |
assert self.current_node is not None |
| 407 |
while not self.current_node.is_leaf: |
| 408 |
self.parents.append((self.current_node, self.current_index)) |
| 409 |
self.current_node = self.current_node.children[self.current_index] |
| 410 |
assert self.current_node is not None |
| 411 |
self.current_index = 0 |
| 412 |
|
| 413 |
def _seek_greatest(self) -> None: |
| 414 |
# seek to the greatest value in the subtree beneath the current index of the |
| 415 |
# current node |
| 416 |
assert self.current_node is not None |
| 417 |
while not self.current_node.is_leaf: |
| 418 |
self.parents.append((self.current_node, self.current_index)) |
| 419 |
self.current_node = self.current_node.children[self.current_index] |
| 420 |
assert self.current_node is not None |
| 421 |
self.current_index = len(self.current_node.elts) |
| 422 |
|
| 423 |
def park(self): |
| 424 |
"""Park the cursor. |
| 425 |
|
| 426 |
A cursor must be "parked" before mutating the BTree to avoid undefined behavior. |
| 427 |
Cursors created in a ``with`` block register with their BTree and will park |
| 428 |
automatically. Note that a parked cursor may not observe some changes made when |
| 429 |
it is parked; for example a cursor being iterated with next() will not see items |
| 430 |
inserted before its current position. |
| 431 |
""" |
| 432 |
if not self.parked: |
| 433 |
self.parked = True |
| 434 |
|
| 435 |
def _maybe_unpark(self): |
| 436 |
if self.parked: |
| 437 |
if self.parking_key is not None: |
| 438 |
# remember our increasing hint, as seeking might change it |
| 439 |
increasing = self.increasing |
| 440 |
if self.parking_key_read: |
| 441 |
# We've already returned the parking key, so we want to be before it |
| 442 |
# if decreasing and after it if increasing. |
| 443 |
before = not self.increasing |
| 444 |
else: |
| 445 |
# We haven't returned the parking key, so we've parked right |
| 446 |
# after seeking or are on a boundary. Either way, the before |
| 447 |
# hint we want is the value of self.increasing. |
| 448 |
before = self.increasing |
| 449 |
self.seek(self.parking_key, before) |
| 450 |
self.increasing = increasing # might have been altered by seek() |
| 451 |
self.parked = False |
| 452 |
self.parking_key = None |
| 453 |
|
| 454 |
def prev(self) -> ET | None: |
| 455 |
"""Get the previous element, or return None if on the left boundary.""" |
| 456 |
self._maybe_unpark() |
| 457 |
self.parking_key = None |
| 458 |
if self.current_node is None: |
| 459 |
# on a boundary |
| 460 |
if self.current_index == 0: |
| 461 |
# left boundary, there is no prev |
| 462 |
return None |
| 463 |
else: |
| 464 |
assert self.current_index == 1 |
| 465 |
# right boundary; seek to the actual boundary |
| 466 |
# so we can do a prev() |
| 467 |
self.current_node = self.btree.root |
| 468 |
self.current_index = len(self.btree.root.elts) |
| 469 |
self._seek_greatest() |
| 470 |
while True: |
| 471 |
if self.recurse: |
| 472 |
if not self.increasing: |
| 473 |
# We only want to recurse if we are continuing in the decreasing |
| 474 |
# direction. |
| 475 |
self._seek_greatest() |
| 476 |
self.recurse = False |
| 477 |
self.increasing = False |
| 478 |
self.current_index -= 1 |
| 479 |
if self.current_index >= 0: |
| 480 |
elt = self.current_node.elts[self.current_index] |
| 481 |
if not self.current_node.is_leaf: |
| 482 |
self.recurse = True |
| 483 |
self.parking_key = elt.key() |
| 484 |
self.parking_key_read = True |
| 485 |
return elt |
| 486 |
else: |
| 487 |
if len(self.parents) > 0: |
| 488 |
self.current_node, self.current_index = self.parents.pop() |
| 489 |
else: |
| 490 |
self.current_node = None |
| 491 |
self.current_index = 0 |
| 492 |
return None |
| 493 |
|
| 494 |
def next(self) -> ET | None: |
| 495 |
"""Get the next element, or return None if on the right boundary.""" |
| 496 |
self._maybe_unpark() |
| 497 |
self.parking_key = None |
| 498 |
if self.current_node is None: |
| 499 |
# on a boundary |
| 500 |
if self.current_index == 1: |
| 501 |
# right boundary, there is no next |
| 502 |
return None |
| 503 |
else: |
| 504 |
assert self.current_index == 0 |
| 505 |
# left boundary; seek to the actual boundary |
| 506 |
# so we can do a next() |
| 507 |
self.current_node = self.btree.root |
| 508 |
self.current_index = 0 |
| 509 |
self._seek_least() |
| 510 |
while True: |
| 511 |
if self.recurse: |
| 512 |
if self.increasing: |
| 513 |
# We only want to recurse if we are continuing in the increasing |
| 514 |
# direction. |
| 515 |
self._seek_least() |
| 516 |
self.recurse = False |
| 517 |
self.increasing = True |
| 518 |
if self.current_index < len(self.current_node.elts): |
| 519 |
elt = self.current_node.elts[self.current_index] |
| 520 |
self.current_index += 1 |
| 521 |
if not self.current_node.is_leaf: |
| 522 |
self.recurse = True |
| 523 |
self.parking_key = elt.key() |
| 524 |
self.parking_key_read = True |
| 525 |
return elt |
| 526 |
else: |
| 527 |
if len(self.parents) > 0: |
| 528 |
self.current_node, self.current_index = self.parents.pop() |
| 529 |
else: |
| 530 |
self.current_node = None |
| 531 |
self.current_index = 1 |
| 532 |
return None |
| 533 |
|
| 534 |
def _adjust_for_before(self, before: bool, i: int) -> None: |
| 535 |
if before: |
| 536 |
self.current_index = i |
| 537 |
else: |
| 538 |
self.current_index = i + 1 |
| 539 |
|
| 540 |
def seek(self, key: KT, before: bool = True) -> None: |
| 541 |
"""Seek to the specified key. |
| 542 |
|
| 543 |
If *before* is ``True`` (the default) then the cursor is positioned just |
| 544 |
before *key* if it exists, or before its least successor if it doesn't. A |
| 545 |
subsequent next() will retrieve this value. If *before* is ``False``, then |
| 546 |
the cursor is positioned just after *key* if it exists, or its greatest |
| 547 |
precessessor if it doesn't. A subsequent prev() will return this value. |
| 548 |
""" |
| 549 |
self.current_node = self.btree.root |
| 550 |
assert self.current_node is not None |
| 551 |
self.recurse = False |
| 552 |
self.parents = [] |
| 553 |
self.increasing = before |
| 554 |
self.parked = False |
| 555 |
self.parking_key = key |
| 556 |
self.parking_key_read = False |
| 557 |
while not self.current_node.is_leaf: |
| 558 |
i, equal = self.current_node.search_in_node(key) |
| 559 |
if equal: |
| 560 |
self._adjust_for_before(before, i) |
| 561 |
if before: |
| 562 |
self._seek_greatest() |
| 563 |
else: |
| 564 |
self._seek_least() |
| 565 |
return |
| 566 |
self.parents.append((self.current_node, i)) |
| 567 |
self.current_node = self.current_node.children[i] |
| 568 |
assert self.current_node is not None |
| 569 |
i, equal = self.current_node.search_in_node(key) |
| 570 |
if equal: |
| 571 |
self._adjust_for_before(before, i) |
| 572 |
else: |
| 573 |
self.current_index = i |
| 574 |
|
| 575 |
def seek_first(self) -> None: |
| 576 |
"""Seek to the left boundary (i.e. just before the least element). |
| 577 |
|
| 578 |
A subsequent next() will return the least element if the BTree isn't empty.""" |
| 579 |
self.current_node = None |
| 580 |
self.current_index = 0 |
| 581 |
self.recurse = False |
| 582 |
self.increasing = True |
| 583 |
self.parents = [] |
| 584 |
self.parked = False |
| 585 |
self.parking_key = None |
| 586 |
|
| 587 |
def seek_last(self) -> None: |
| 588 |
"""Seek to the right boundary (i.e. just after the greatest element). |
| 589 |
|
| 590 |
A subsequent prev() will return the greatest element if the BTree isn't empty. |
| 591 |
""" |
| 592 |
self.current_node = None |
| 593 |
self.current_index = 1 |
| 594 |
self.recurse = False |
| 595 |
self.increasing = False |
| 596 |
self.parents = [] |
| 597 |
self.parked = False |
| 598 |
self.parking_key = None |
| 599 |
|
| 600 |
def __enter__(self): |
| 601 |
self.btree.register_cursor(self) |
| 602 |
return self |
| 603 |
|
| 604 |
def __exit__(self, exc_type, exc_value, traceback): |
| 605 |
self.btree.deregister_cursor(self) |
| 606 |
return False |
| 607 |
|
| 608 |
|
| 609 |
class Immutable(Exception): |
| 610 |
"""The BTree is immutable.""" |
| 611 |
|
| 612 |
|
| 613 |
class BTree(Generic[KT, ET]): |
| 614 |
"""An in-memory BTree with copy-on-write and cursors.""" |
| 615 |
|
| 616 |
def __init__(self, *, t: int = DEFAULT_T, original: Optional["BTree"] = None): |
| 617 |
"""Create a BTree. |
| 618 |
|
| 619 |
If *original* is not ``None``, then the BTree is shallow-cloned from |
| 620 |
*original* using copy-on-write. Otherwise a new BTree with the specified |
| 621 |
*t* value is created. |
| 622 |
|
| 623 |
The BTree is not thread-safe. |
| 624 |
""" |
| 625 |
# We don't use a reference to ourselves as a creator as we don't want |
| 626 |
# to prevent GC of old btrees. |
| 627 |
self.creator = _Creator() |
| 628 |
self._immutable = False |
| 629 |
self.t: int |
| 630 |
self.root: _Node |
| 631 |
self.size: int |
| 632 |
self.cursors: set[Cursor] = set() |
| 633 |
if original is not None: |
| 634 |
if not original._immutable: |
| 635 |
raise ValueError("original BTree is not immutable") |
| 636 |
self.t = original.t |
| 637 |
self.root = original.root |
| 638 |
self.size = original.size |
| 639 |
else: |
| 640 |
if t < 3: |
| 641 |
raise ValueError("t must be >= 3") |
| 642 |
self.t = t |
| 643 |
self.root = _Node(self.t, self.creator, True) |
| 644 |
self.size = 0 |
| 645 |
|
| 646 |
def make_immutable(self): |
| 647 |
"""Make the BTree immutable. |
| 648 |
|
| 649 |
Attempts to alter the BTree after making it immutable will raise an |
| 650 |
Immutable exception. This operation cannot be undone. |
| 651 |
""" |
| 652 |
if not self._immutable: |
| 653 |
self._immutable = True |
| 654 |
|
| 655 |
def _check_mutable_and_park(self) -> None: |
| 656 |
if self._immutable: |
| 657 |
raise Immutable |
| 658 |
for cursor in self.cursors: |
| 659 |
cursor.park() |
| 660 |
|
| 661 |
# Note that we don't use insert() and delete() but rather insert_element() and |
| 662 |
# delete_key() so that BTreeDict can be a proper MutableMapping and supply the |
| 663 |
# rest of the standard mapping API. |
| 664 |
|
| 665 |
def insert_element(self, elt: ET, in_order: bool = False) -> ET | None: |
| 666 |
"""Insert the element into the BTree. |
| 667 |
|
| 668 |
If *in_order* is ``True``, then extra work will be done to make left siblings |
| 669 |
full, which optimizes storage space when the the elements are inserted in-order |
| 670 |
or close to it. |
| 671 |
|
| 672 |
Returns the previously existing element at the element's key or ``None``. |
| 673 |
""" |
| 674 |
self._check_mutable_and_park() |
| 675 |
cloned = self.root.maybe_cow(self.creator) |
| 676 |
if cloned: |
| 677 |
self.root = cloned |
| 678 |
if self.root.is_maximal(): |
| 679 |
old_root = self.root |
| 680 |
self.root = _Node(self.t, self.creator, False) |
| 681 |
self.root.adopt(*old_root.split()) |
| 682 |
oelt = self.root.insert_nonfull(elt, in_order) |
| 683 |
if oelt is None: |
| 684 |
# We did not replace, so something was added. |
| 685 |
self.size += 1 |
| 686 |
return oelt |
| 687 |
|
| 688 |
def get_element(self, key: KT) -> ET | None: |
| 689 |
"""Get the element matching *key* from the BTree, or return ``None`` if it |
| 690 |
does not exist. |
| 691 |
""" |
| 692 |
return self.root.get(key) |
| 693 |
|
| 694 |
def _delete(self, key: KT, exact: ET | None) -> ET | None: |
| 695 |
self._check_mutable_and_park() |
| 696 |
cloned = self.root.maybe_cow(self.creator) |
| 697 |
if cloned: |
| 698 |
self.root = cloned |
| 699 |
elt = self.root.delete(key, None, exact) |
| 700 |
if elt is not None: |
| 701 |
# We deleted something |
| 702 |
self.size -= 1 |
| 703 |
if len(self.root.elts) == 0: |
| 704 |
# The root is now empty. If there is a child, then collapse this root |
| 705 |
# level and make the child the new root. |
| 706 |
if not self.root.is_leaf: |
| 707 |
assert len(self.root.children) == 1 |
| 708 |
self.root = self.root.children[0] |
| 709 |
return elt |
| 710 |
|
| 711 |
def delete_key(self, key: KT) -> ET | None: |
| 712 |
"""Delete the element matching *key* from the BTree. |
| 713 |
|
| 714 |
Returns the matching element or ``None`` if it does not exist. |
| 715 |
""" |
| 716 |
return self._delete(key, None) |
| 717 |
|
| 718 |
def delete_exact(self, element: ET) -> ET | None: |
| 719 |
"""Delete *element* from the BTree. |
| 720 |
|
| 721 |
Returns the matching element or ``None`` if it was not in the BTree. |
| 722 |
""" |
| 723 |
delt = self._delete(element.key(), element) |
| 724 |
assert delt is element |
| 725 |
return delt |
| 726 |
|
| 727 |
def __len__(self): |
| 728 |
return self.size |
| 729 |
|
| 730 |
def visit_in_order(self, visit: Callable[[ET], None]) -> None: |
| 731 |
"""Call *visit*(element) on all elements in the tree in sorted order.""" |
| 732 |
self.root.visit_in_order(visit) |
| 733 |
|
| 734 |
def _visit_preorder_by_node(self, visit: Callable[[_Node], None]) -> None: |
| 735 |
self.root._visit_preorder_by_node(visit) |
| 736 |
|
| 737 |
def cursor(self) -> Cursor[KT, ET]: |
| 738 |
"""Create a cursor.""" |
| 739 |
return Cursor(self) |
| 740 |
|
| 741 |
def register_cursor(self, cursor: Cursor) -> None: |
| 742 |
"""Register a cursor for the automatic parking service.""" |
| 743 |
self.cursors.add(cursor) |
| 744 |
|
| 745 |
def deregister_cursor(self, cursor: Cursor) -> None: |
| 746 |
"""Deregister a cursor from the automatic parking service.""" |
| 747 |
self.cursors.discard(cursor) |
| 748 |
|
| 749 |
def __copy__(self): |
| 750 |
return self.__class__(original=self) |
| 751 |
|
| 752 |
def __iter__(self): |
| 753 |
with self.cursor() as cursor: |
| 754 |
while True: |
| 755 |
elt = cursor.next() |
| 756 |
if elt is None: |
| 757 |
break |
| 758 |
yield elt.key() |
| 759 |
|
| 760 |
|
| 761 |
VT = TypeVar("VT") # the type of a value in a BTreeDict |
| 762 |
|
| 763 |
|
| 764 |
class KV(Element, Generic[KT, VT]): |
| 765 |
"""The BTree element type used in a ``BTreeDict``.""" |
| 766 |
|
| 767 |
def __init__(self, key: KT, value: VT): |
| 768 |
self._key = key |
| 769 |
self._value = value |
| 770 |
|
| 771 |
def key(self) -> KT: |
| 772 |
return self._key |
| 773 |
|
| 774 |
def value(self) -> VT: |
| 775 |
return self._value |
| 776 |
|
| 777 |
def __str__(self): # pragma: no cover |
| 778 |
return f"KV({self._key}, {self._value})" |
| 779 |
|
| 780 |
def __repr__(self): # pragma: no cover |
| 781 |
return f"KV({self._key}, {self._value})" |
| 782 |
|
| 783 |
|
| 784 |
class BTreeDict(Generic[KT, VT], BTree[KT, KV[KT, VT]], MutableMapping[KT, VT]): |
| 785 |
"""A MutableMapping implemented with a BTree. |
| 786 |
|
| 787 |
Unlike a normal Python dict, the BTreeDict may be mutated while iterating. |
| 788 |
""" |
| 789 |
|
| 790 |
def __init__( |
| 791 |
self, |
| 792 |
*, |
| 793 |
t: int = DEFAULT_T, |
| 794 |
original: BTree | None = None, |
| 795 |
in_order: bool = False, |
| 796 |
): |
| 797 |
super().__init__(t=t, original=original) |
| 798 |
self.in_order = in_order |
| 799 |
|
| 800 |
def __getitem__(self, key: KT) -> VT: |
| 801 |
elt = self.get_element(key) |
| 802 |
if elt is None: |
| 803 |
raise KeyError |
| 804 |
else: |
| 805 |
return cast(KV, elt).value() |
| 806 |
|
| 807 |
def __setitem__(self, key: KT, value: VT) -> None: |
| 808 |
elt = KV(key, value) |
| 809 |
self.insert_element(elt, self.in_order) |
| 810 |
|
| 811 |
def __delitem__(self, key: KT) -> None: |
| 812 |
if self.delete_key(key) is None: |
| 813 |
raise KeyError |
| 814 |
|
| 815 |
|
| 816 |
class Member(Element, Generic[KT]): |
| 817 |
"""The BTree element type used in a ``BTreeSet``.""" |
| 818 |
|
| 819 |
def __init__(self, key: KT): |
| 820 |
self._key = key |
| 821 |
|
| 822 |
def key(self) -> KT: |
| 823 |
return self._key |
| 824 |
|
| 825 |
|
| 826 |
class BTreeSet(BTree, Generic[KT], MutableSet[KT]): |
| 827 |
"""A MutableSet implemented with a BTree. |
| 828 |
|
| 829 |
Unlike a normal Python set, the BTreeSet may be mutated while iterating. |
| 830 |
""" |
| 831 |
|
| 832 |
def __init__( |
| 833 |
self, |
| 834 |
*, |
| 835 |
t: int = DEFAULT_T, |
| 836 |
original: BTree | None = None, |
| 837 |
in_order: bool = False, |
| 838 |
): |
| 839 |
super().__init__(t=t, original=original) |
| 840 |
self.in_order = in_order |
| 841 |
|
| 842 |
def __contains__(self, key: Any) -> bool: |
| 843 |
return self.get_element(key) is not None |
| 844 |
|
| 845 |
def add(self, value: KT) -> None: |
| 846 |
elt = Member(value) |
| 847 |
self.insert_element(elt, self.in_order) |
| 848 |
|
| 849 |
def discard(self, value: KT) -> None: |
| 850 |
self.delete_key(value) |