raw-btree 0.3.2

Generic B-Tree implementation.
Documentation
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use crate::{
	balancing::rebalance,
	node::{Address, Offset},
	utils::Array,
	Node, M,
};
use core::fmt;
use std::{cmp::Ordering, ptr::NonNull};

/// BTree node storage.
///
/// # Safety
///
/// An *active* identifier is a node identifier (`Self::Node`) that has been
/// created using `allocate_node` (or `insert_node`) but not yet released using
/// `release_node` or a `Dropper` (created with `start_dropping`).
///
/// - Default method implementations must not be overridden by the implementor.
/// - `allocate_node` must not return an *active* identifier.
///   Once returned and until released using `release_node`, this identifier
///   must always map to the same node through `get` and `get_mut`.
///   We say that the identifier and node are "bound" together by the storage.
///   The created node must live at least as long as its identifier is active
///   and the storage is not dropped.
/// - `release_node` may only drop the node bound to the given identifier.
/// - `start_dropping` creates a dropper for this storage.
/// - `get` must return the node bound to the given identifier.
/// - `get_mut` must return the node bound to the given identifier.
pub unsafe trait Storage<T>: Default {
	/// Node.
	type Node: Copy + PartialEq + core::fmt::Debug;

	/// Nodes dropper.
	type Dropper: Dropper<T, Self>;

	/// Allocates the given node.
	fn allocate_node(&mut self, node: Node<T, Self>) -> Self::Node;

	/// # Safety
	///
	/// Input node must not have been deallocated.
	unsafe fn release_node(&mut self, id: Self::Node) -> Node<T, Self>;

	/// Creates a new dropper.
	///
	/// Returns `None` if no dropper is required to eventually drop all the
	/// nodes.
	fn start_dropping(&self) -> Option<Self::Dropper>;

	/// # Safety
	///
	/// Input node must not have been deallocated.
	unsafe fn get(&self, id: Self::Node) -> &Node<T, Self>;

	/// # Safety
	///
	/// - Input node must not have been deallocated.
	/// - Different `id` must map to non-aliased nodes.
	/// - Must not be used to create more than one concurrent mutable reference
	///   to the same node.
	unsafe fn get_mut(&mut self, id: Self::Node) -> &mut Node<T, Self>;

	/// Inserts the given node into the storage, setting the children parent.
	///
	/// # Safety
	///
	/// The input node's children must not have been deallocated.
	unsafe fn insert_node(&mut self, node: Node<T, Self>) -> Self::Node {
		let children: Array<Self::Node, M> = node.children().collect();
		let id = self.allocate_node(node);
		for child_id in children {
			self.get_mut(child_id).set_parent(Some(id));
		}

		id
	}

	/// Normalizes the given address.
	///
	/// # Safety
	///
	/// Input address's node must not have been deallocated.
	unsafe fn normalize(&self, mut addr: Address<Self::Node>) -> Option<Address<Self::Node>> {
		loop {
			let node = self.get(addr.node);
			if addr.offset >= node.item_count() {
				match node.parent() {
					Some(parent_id) => {
						addr.offset = self.get(parent_id).child_index(addr.node).unwrap().into();
						addr.node = parent_id;
					}
					None => break None,
				}
			} else {
				break Some(addr);
			}
		}
	}

	/// Converts this arbitrary address into a leaf address.
	///
	/// # Safety
	///
	/// Input address's node must not have been deallocated.
	#[inline]
	unsafe fn leaf_address(&self, mut addr: Address<Self::Node>) -> Address<Self::Node> {
		loop {
			let node = self.get(addr.node);
			match node.child_id_opt(addr.offset.unwrap()) {
				// TODO unwrap may fail here!
				Some(child_id) => {
					addr.node = child_id;
					addr.offset = self.get(child_id).item_count().into()
				}
				None => break,
			}
		}

		addr
	}

	/// Get the address of the item located before this address.
	///
	/// # Safety
	///
	/// Input address's node must not have been deallocated.
	#[inline]
	unsafe fn previous_item_address(
		&self,
		mut addr: Address<Self::Node>,
	) -> Option<Address<Self::Node>> {
		loop {
			let node = self.get(addr.node);

			match node.child_id_opt(addr.offset.unwrap()) {
				// TODO unwrap may fail here.
				Some(child_id) => {
					addr.offset = self.get(child_id).item_count().into();
					addr.node = child_id;
				}
				None => loop {
					if addr.offset > 0 {
						addr.offset.decr();
						return Some(addr);
					}

					match self.get(addr.node).parent() {
						Some(parent_id) => {
							addr.offset =
								self.get(parent_id).child_index(addr.node).unwrap().into();
							addr.node = parent_id;
						}
						None => return None,
					}
				},
			}
		}
	}

	/// Returns the front address directly preceding the given address.
	///
	/// # Safety
	///
	/// Input address's node must not have been deallocated.
	#[inline]
	unsafe fn previous_front_address(
		&self,
		mut addr: Address<Self::Node>,
	) -> Option<Address<Self::Node>> {
		loop {
			let node = self.get(addr.node);
			match addr.offset.value() {
				Some(offset) => {
					let index = if offset < node.item_count() {
						offset
					} else {
						node.item_count()
					};

					match node.child_id_opt(index) {
						Some(child_id) => {
							addr.offset = (self.get(child_id).item_count()).into();
							addr.node = child_id;
						}
						None => {
							addr.offset.decr();
							break;
						}
					}
				}
				None => match node.parent() {
					Some(parent_id) => {
						addr.offset = self.get(parent_id).child_index(addr.node).unwrap().into();
						addr.offset.decr();
						addr.node = parent_id;
						break;
					}
					None => return None,
				},
			}
		}

		Some(addr)
	}

	/// Get the address of the item located after this address if any.
	///
	/// # Safety
	///
	/// Input address's node must not have been deallocated.
	#[inline]
	unsafe fn next_item_address(
		&self,
		mut addr: Address<Self::Node>,
	) -> Option<Address<Self::Node>> {
		let item_count = self.get(addr.node).item_count();
		match addr.offset.partial_cmp(&item_count) {
			Some(std::cmp::Ordering::Less) => {
				addr.offset.incr();
			}
			Some(std::cmp::Ordering::Greater) => {
				return None;
			}
			_ => (),
		}

		// let original_addr_shifted = addr;

		loop {
			let node = self.get(addr.node);

			match node.child_id_opt(addr.offset.unwrap()) {
				// unwrap may fail here.
				Some(child_id) => {
					addr.offset = 0.into();
					addr.node = child_id;
				}
				None => {
					loop {
						let node = self.get(addr.node);

						if addr.offset < node.item_count() {
							return Some(addr);
						}

						match node.parent() {
							Some(parent_id) => {
								addr.offset =
									self.get(parent_id).child_index(addr.node).unwrap().into();
								addr.node = parent_id;
							}
							None => {
								// return Some(original_addr_shifted)
								return None;
							}
						}
					}
				}
			}
		}
	}

	//// Returns the back address directly following the given address.
	///
	/// # Safety
	///
	/// Input address's node must not have been deallocated.
	#[inline]
	unsafe fn next_back_address(
		&self,
		mut addr: Address<Self::Node>,
	) -> Option<Address<Self::Node>> {
		loop {
			let node = self.get(addr.node);
			let index = match addr.offset.value() {
				Some(offset) => offset + 1,
				None => 0,
			};

			if index <= node.item_count() {
				match node.child_id_opt(index) {
					Some(child_id) => {
						addr.offset = Offset::before();
						addr.node = child_id;
					}
					None => {
						addr.offset = index.into();
						break;
					}
				}
			} else {
				match node.parent() {
					Some(parent_id) => {
						addr.offset = self.get(parent_id).child_index(addr.node).unwrap().into();
						addr.node = parent_id;
						break;
					}
					None => return None,
				}
			}
		}

		Some(addr)
	}

	/// Returns the item address or back address directly following the given
	/// address.
	///
	/// # Safety
	///
	/// Input address's node must not have been deallocated.
	#[inline]
	unsafe fn next_item_or_back_address(
		&self,
		mut addr: Address<Self::Node>,
	) -> Option<Address<Self::Node>> {
		let item_count = self.get(addr.node).item_count();
		match addr.offset.partial_cmp(&item_count) {
			Some(std::cmp::Ordering::Less) => {
				addr.offset.incr();
			}
			Some(std::cmp::Ordering::Greater) => {
				return None;
			}
			_ => (),
		}

		let original_addr_shifted = addr;

		loop {
			let node = self.get(addr.node);

			match node.child_id_opt(addr.offset.unwrap()) {
				// TODO unwrap may fail here.
				Some(child_id) => {
					addr.offset = 0.into();
					addr.node = child_id;
				}
				None => loop {
					let node = self.get(addr.node);

					if addr.offset < node.item_count() {
						return Some(addr);
					}

					match node.parent() {
						Some(parent_id) => {
							addr.offset =
								self.get(parent_id).child_index(addr.node).unwrap().into();
							addr.node = parent_id;
						}
						None => return Some(original_addr_shifted),
					}
				},
			}
		}
	}

	/// # Safety
	///
	/// Input node must not have been deallocated.
	unsafe fn address_in<Q: ?Sized>(
		&self,
		mut id: Self::Node,
		cmp: impl Fn(&T, &Q) -> Ordering,
		key: &Q,
	) -> Result<Address<Self::Node>, Address<Self::Node>> {
		loop {
			match self.get(id).offset_of(&cmp, key) {
				Ok(offset) => return Ok(Address { node: id, offset }),
				Err((offset, None)) => return Err(Address::new(id, offset.into())),
				Err((_, Some(child_id))) => {
					id = child_id;
				}
			}
		}
	}

	/// Inserts the item at the given address.
	///
	/// # Safety
	///
	/// Input nodes must not have been deallocated.
	unsafe fn insert_at(
		&mut self,
		root: Option<Self::Node>,
		addr: Option<Address<Self::Node>>,
		item: T,
	) -> (Option<Self::Node>, Option<Address<Self::Node>>) {
		self.insert_exactly_at(root, addr.map(|addr| self.leaf_address(addr)), item, None)
	}

	/// Inserts the given item exactly at the provided **leaf** address.
	///
	/// # Safety
	///
	/// Input nodes must not have been deallocated.
	unsafe fn insert_exactly_at(
		&mut self,
		root: Option<Self::Node>,
		addr: Option<Address<Self::Node>>,
		item: T,
		opt_right_id: Option<Self::Node>,
	) -> (Option<Self::Node>, Option<Address<Self::Node>>) {
		match addr {
			Some(addr) => {
				self.get_mut(addr.node)
					.insert(addr.offset, item, opt_right_id);
				rebalance(self, root, addr.node, addr)
			}
			None => {
				let new_root = Node::leaf(None, item);
				let id = self.insert_node(new_root);
				let addr = Address {
					node: id,
					offset: 0.into(),
				};
				(Some(id), Some(addr))
			}
		}
	}

	/// Replaces the item located at the given address.
	///
	/// # Safety
	///
	/// Input address's node must not have been deallocated.
	unsafe fn replace_at(&mut self, addr: Address<Self::Node>, item: T) -> T {
		std::mem::replace(self.get_mut(addr.node).item_mut(addr.offset).unwrap(), item)
	}

	/// # Safety
	///
	/// Input nodes must not have been deallocated.
	#[inline]
	unsafe fn remove_at(
		&mut self,
		root: Option<Self::Node>,
		addr: Address<Self::Node>,
	) -> Option<RemovedItem<T, Self>> {
		match self.get_mut(addr.node).leaf_remove(addr.offset) {
			Some(Ok(item)) => {
				// removed from a leaf.
				let (new_root, new_addr) = rebalance(self, root, addr.node, addr);
				Some(RemovedItem {
					new_root,
					item,
					new_addr,
				})
			}
			Some(Err(left_child_id)) => {
				// removed from an internal node.
				let new_addr = self.next_item_or_back_address(addr).unwrap();
				let (separator, leaf_id) = self.remove_rightmost_leaf_of(left_child_id);
				let item = self.get_mut(addr.node).replace(addr.offset, separator);
				let (new_root, new_addr) = rebalance(self, root, leaf_id, new_addr);
				Some(RemovedItem {
					new_root,
					item,
					new_addr,
				})
			}
			None => None,
		}
	}

	/// Remove the rightmost leaf node under the given node.
	///
	/// # Safety
	///
	/// Input node must not have been deallocated.
	#[inline]
	unsafe fn remove_rightmost_leaf_of(&mut self, mut id: Self::Node) -> (T, Self::Node) {
		loop {
			match self.get_mut(id).remove_rightmost_leaf() {
				Ok(result) => return (result, id),
				Err(child_id) => {
					id = child_id;
				}
			}
		}
	}
}

pub struct RemovedItem<T, S: Storage<T>> {
	pub new_root: Option<S::Node>,
	pub item: T,
	pub new_addr: Option<Address<S::Node>>,
}

/// Storage dropper.
///
/// Used to drop all the nodes of a node storage.
///
/// # Safety
///
/// `drop_node` may only drop the node bound to the given identifier.
pub unsafe trait Dropper<T, S: Storage<T>>: Sized {
	/// Drops the given node.
	///
	/// # Safety
	///
	/// - The node must not have been deallocated.
	/// - No reference to the node or the node's content must exist.
	/// - The node cannot be dereferenced anymore.
	unsafe fn drop_node(&mut self, id: S::Node);
}

#[derive(Default)]
pub struct BoxStorage;

pub struct BoxPtr<T>(NonNull<Node<T, BoxStorage>>); // TODO use `core::ptr::Unique` when it is stable.

unsafe impl<T: Send> Send for BoxPtr<T> {}
unsafe impl<T: Sync> Sync for BoxPtr<T> {}

unsafe impl<T> Storage<T> for BoxStorage {
	type Node = BoxPtr<T>;

	type Dropper = BoxDrop;

	fn allocate_node(&mut self, node: Node<T, Self>) -> Self::Node {
		let b = Box::new(node);
		BoxPtr(NonNull::new(Box::into_raw(b)).unwrap())
	}

	unsafe fn release_node(&mut self, id: Self::Node) -> Node<T, Self> {
		let b = Box::from_raw(id.0.as_ptr());
		*b
	}

	fn start_dropping(&self) -> Option<Self::Dropper> {
		Some(BoxDrop)
	}

	unsafe fn get(&self, id: Self::Node) -> &Node<T, Self> {
		&*id.0.as_ptr()
	}

	unsafe fn get_mut(&mut self, id: Self::Node) -> &mut Node<T, Self> {
		&mut *id.0.as_ptr()
	}
}

impl<T> fmt::Debug for BoxPtr<T> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

impl<T> Clone for BoxPtr<T> {
	fn clone(&self) -> Self {
		*self
	}
}

impl<T> Copy for BoxPtr<T> {}

impl<T> PartialEq for BoxPtr<T> {
	fn eq(&self, other: &Self) -> bool {
		self.0 == other.0
	}
}

impl<T> Eq for BoxPtr<T> {}

impl<T> From<BoxPtr<T>> for usize {
	fn from(value: BoxPtr<T>) -> Self {
		value.0.as_ptr() as usize
	}
}

pub struct BoxDrop;

unsafe impl<T> Dropper<T, BoxStorage> for BoxDrop {
	unsafe fn drop_node(&mut self, id: BoxPtr<T>) {
		let _ = Box::from_raw(id.0.as_ptr());
	}
}