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
use std::mem::size_of;
use humansize::{file_size_opts, FileSize};
use smallvec::SmallVec;
use rle::{Searchable, merge_items, MergeIter};
use super::safe_cursor::ItemIterator;
use super::*;
pub type DeleteResult<E> = SmallVec<[E; 2]>;
impl<E: ContentTraits, I: TreeIndex<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
pub fn new() -> Pin<Box<Self>> {
let mut tree = Box::pin(Self {
count: I::IndexValue::default(),
root: unsafe { Node::Leaf(Box::pin(NodeLeaf::new(None))) },
_pin: marker::PhantomPinned,
});
let parent_ref = unsafe { tree.as_ref().get_ref().to_parent_ptr() };
tree.as_mut().root_ref_mut().set_parent(parent_ref);
tree
}
fn root_ref_mut(self: Pin<&mut Self>) -> &mut Node<E, I, IE, LE> {
unsafe {
&mut self.get_unchecked_mut().root
}
}
pub fn len(&self) -> I::IndexValue {
self.count
}
pub(crate) unsafe fn to_parent_ptr(&self) -> ParentPtr<E, I, IE, LE> {
ParentPtr::Root(ref_to_nonnull(self))
}
pub fn unsafe_cursor_at_query<F, G>(&self, raw_pos: usize, stick_end: bool, offset_to_num: F, entry_to_num: G) -> UnsafeCursor<E, I, IE, LE>
where F: Fn(I::IndexValue) -> usize, G: Fn(E) -> usize {
unsafe {
let mut node = self.root.as_ptr();
let mut offset_remaining = raw_pos;
while let NodePtr::Internal(data) = node {
let (new_offset_remaining, next) = data.as_ref()
.find_child_at_offset(offset_remaining, stick_end, &offset_to_num)
.expect("Internal consistency violation");
offset_remaining = new_offset_remaining;
node = next;
};
let leaf_ptr = node.unwrap_leaf();
let node = leaf_ptr.as_ref();
let (idx, offset_remaining) = if node.num_entries == 0 {
(0, usize::MAX)
} else {
node.find_offset(offset_remaining, stick_end, entry_to_num)
.expect("Element does not contain entry")
};
UnsafeCursor {
node: leaf_ptr,
idx,
offset: offset_remaining,
}
}
}
pub fn unsafe_cursor_at_start(&self) -> UnsafeCursor<E, I, IE, LE> {
unsafe {
let mut node = self.root.as_ptr();
while let NodePtr::Internal(data) = node {
node = data.as_ref().children[0].as_ref().unwrap().as_ptr()
};
let leaf_ptr = node.unwrap_leaf();
UnsafeCursor {
node: leaf_ptr,
idx: 0,
offset: if leaf_ptr.as_ref().num_entries == 0 { usize::MAX } else { 0 },
}
}
}
pub fn unsafe_cursor_at_end(&self) -> UnsafeCursor<E, I, IE, LE> {
let cursor = unsafe {
let mut node = self.root.as_ptr();
while let NodePtr::Internal(ptr) = node {
node = ptr.as_ref().last_child();
};
let leaf_ptr = node.unwrap_leaf();
let leaf = leaf_ptr.as_ref();
let (idx, offset) = if leaf.len_entries() == 0 {
(0, usize::MAX)
} else {
let idx = leaf.len_entries() - 1;
let offset = leaf.data[idx].len();
(idx, offset)
};
UnsafeCursor {
node: leaf_ptr,
idx,
offset
}
};
if cfg!(debug_assertions) {
let mut cursor = cursor.clone();
let node = unsafe { cursor.node.as_ref() };
if let Some(entry) = cursor.try_get_raw_entry() {
assert_eq!(entry.len(), cursor.offset);
}
if node.len_entries() > 0 {
assert_eq!(cursor.idx, node.len_entries() - 1);
}
assert!(!cursor.next_entry());
}
cursor
}
pub fn raw_iter(&self) -> Cursor<E, I, IE, LE> { self.cursor_at_start() }
pub fn iter(&self) -> MergeIter<Cursor<E, I, IE, LE>> { merge_items(self.cursor_at_start()) }
pub fn item_iter(&self) -> ItemIterator<E, I, IE, LE> {
ItemIterator(self.raw_iter())
}
pub fn next_entry_or_panic(cursor: &mut UnsafeCursor<E, I, IE, LE>, marker: &mut I::IndexUpdate) {
if !cursor.next_entry_marker(Some(marker)) {
panic!("Local delete past the end of the document");
}
}
fn check_leaf(leaf: &NodeLeaf<E, I, IE, LE>, expected_parent: ParentPtr<E, I, IE, LE>) -> I::IndexValue {
assert_eq!(leaf.parent, expected_parent);
let mut count = I::IndexValue::default();
for e in &leaf.data[..leaf.num_entries as usize] {
assert_ne!(e.len(), 0, "Invalid leaf - 0 length");
I::increment_offset(&mut count, e);
}
if let ParentPtr::Internal(_) = leaf.parent {
assert_ne!(leaf.num_entries, 0, "Non-root leaf is empty");
}
let next = leaf.adjacent_leaf_by_traversal(true);
assert_eq!(next, leaf.next);
count
}
fn check_internal(node: &NodeInternal<E, I, IE, LE>, expected_parent: ParentPtr<E, I, IE, LE>) -> I::IndexValue {
assert_eq!(node.parent, expected_parent);
let mut count_total = I::IndexValue::default();
let mut done = false;
let mut child_type = None;
let self_parent = unsafe { node.to_parent_ptr() };
for idx in 0..node.index.len() {
let child_count_expected = node.index[idx];
let child = &node.children[idx];
if let Some(child) = child {
assert!(!done);
let child_ref = child;
let actual_type = match child_ref {
Node::Internal(_) => 1,
Node::Leaf(_) => 2,
};
if child_type.is_none() { child_type = Some(actual_type) }
else { assert_eq!(child_type, Some(actual_type)); }
let count_actual = match child_ref {
Node::Leaf(ref n) => { Self::check_leaf(n.as_ref().get_ref(), self_parent) },
Node::Internal(ref n) => { Self::check_internal(n.as_ref().get_ref(), self_parent) },
};
assert_eq!(child_count_expected, count_actual, "Child node count does not match");
count_total += count_actual;
} else {
done = true;
}
}
count_total
}
pub fn check(&self) {
let root = &self.root;
let expected_parent = ParentPtr::Root(unsafe { ref_to_nonnull(self) });
let expected_size = match root {
Node::Internal(n) => { Self::check_internal(n, expected_parent) },
Node::Leaf(n) => { Self::check_leaf(n, expected_parent) },
};
assert_eq!(self.count, expected_size, "tree.count is incorrect");
}
fn print_node_tree(node: &Node<E, I, IE, LE>, depth: usize) {
for _ in 0..depth { eprint!(" "); }
match node {
Node::Internal(n) => {
let n = n.as_ref().get_ref();
eprintln!("Internal {:?} (parent: {:?})", n as *const _, n.parent);
let mut unused = 0;
for e in &n.children[..] {
if let Some(e) = e {
Self::print_node_tree(e, depth + 1);
} else { unused += 1; }
}
if unused > 0 {
for _ in 0..=depth { eprint!(" "); }
eprintln!("({} empty places)", unused);
}
},
Node::Leaf(n) => {
eprintln!("Leaf {:?} (parent: {:?}) - {} filled", n as *const _, n.parent, n.len_entries());
}
}
}
#[allow(unused)]
pub fn print_ptr_tree(&self) {
eprintln!("Tree count {:?} ptr {:?}", self.count, self as *const _);
Self::print_node_tree(&self.root, 1);
}
#[allow(unused)]
pub fn print_stats(&self, name: &str, detailed: bool) {
let mut size_counts = vec!();
for entry in self.raw_iter() {
let bucket = entry.len() as usize;
if bucket >= size_counts.len() {
size_counts.resize(bucket + 1, 0);
}
size_counts[bucket] += 1;
}
let (num_internal_nodes, num_leaf_nodes) = self.count_nodes();
let leaf_node_size = num_leaf_nodes * size_of::<NodeLeaf<E, I, IE, LE>>();
let internal_node_size = num_internal_nodes * size_of::<NodeInternal<E, I, IE, LE>>();
let num_entries = self.count_entries();
println!("-------- Range tree {} stats --------", name);
println!("Number of {} byte entries: {} ({} bytes of entries)",
size_of::<E>(),
num_entries,
(num_entries * size_of::<E>()).file_size(file_size_opts::CONVENTIONAL).unwrap()
);
println!("Number of {} byte internal nodes {} ({})",
size_of::<NodeInternal<E, I, IE, LE>>(),
num_internal_nodes,
internal_node_size.file_size(file_size_opts::CONVENTIONAL).unwrap());
println!("Number of {} byte leaf nodes {} ({}) (space for {} entries)",
size_of::<NodeLeaf<E, I, IE, LE>>(),
num_leaf_nodes,
leaf_node_size.file_size(file_size_opts::CONVENTIONAL).unwrap(),
num_leaf_nodes * LE
);
println!("Depth {}", self.get_depth());
println!("Total range tree memory usage {}",
self.count_total_memory().file_size(file_size_opts::CONVENTIONAL).unwrap());
let compacted_entries = merge_items(self.raw_iter()).count();
println!("Compacts to {} entries / {} bytes",
compacted_entries,
(compacted_entries * size_of::<E>()).file_size(file_size_opts::CONVENTIONAL).unwrap()
);
if detailed {
println!("Entry distribution {:?}", size_counts);
println!("Internal node size {}", std::mem::size_of::<NodeInternal<E, I, IE, LE>>());
println!("Node entry size {} alignment {}",
std::mem::size_of::<Option<Node<E, I, IE, LE>>>(),
std::mem::align_of::<Option<Node<E, I, IE, LE>>>());
println!("Leaf size {}", std::mem::size_of::<NodeLeaf<E, I, IE, LE>>());
}
}
fn get_depth(&self) -> usize {
unsafe {
let mut depth = 0;
let mut node = self.root.as_ptr();
while let NodePtr::Internal(data) = node {
depth += 1;
node = data.as_ref().children[0].as_ref().unwrap().as_ptr()
};
depth
}
}
#[allow(unused)]
pub fn count_entries(&self) -> usize {
self.raw_iter().fold(0, |a, _| a + 1)
}
fn count_nodes_internal(node: &Node<E, I, IE, LE>, num: &mut (usize, usize)) {
if let Node::Internal(n) = node {
num.0 += 1;
for e in &n.children[..] {
if let Some(e) = e {
Self::count_nodes_internal(e, num);
}
}
} else { num.1 += 1; }
}
#[allow(unused)]
pub fn count_nodes(&self) -> (usize, usize) {
let mut num = (0, 0);
Self::count_nodes_internal(&self.root, &mut num);
num
}
fn count_memory_internal(node: &Node<E, I, IE, LE>, size: &mut usize) {
match node {
Node::Internal(n) => {
*size += size_of::<NodeInternal<E, I, IE, LE>>();
for e in &n.children[..] {
if let Some(e) = e {
Self::count_memory_internal(e, size);
}
}
}
Node::Leaf(_) => {
*size += std::mem::size_of::<NodeLeaf<E, I, IE, LE>>();
}
}
}
#[allow(unused)]
pub fn count_total_memory(&self) -> usize {
let mut size = size_of::<ContentTreeRaw<E, I, IE, LE>>();
Self::count_memory_internal(&self.root, &mut size);
size
}
}
impl<E: ContentTraits + Searchable, I: TreeIndex<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
pub unsafe fn cursor_before_item(loc: E::Item, ptr: NonNull<NodeLeaf<E, I, IE, LE>>) -> UnsafeCursor<E, I, IE, LE> {
let leaf = ptr.as_ref();
leaf.find(loc).expect("Position not in named leaf")
}
}
impl<E: ContentTraits + ContentLength, I: FindContent<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
pub fn content_len(&self) -> usize {
I::index_to_content(self.count)
}
pub fn unsafe_cursor_at_content_pos(&self, pos: usize, stick_end: bool) -> UnsafeCursor<E, I, IE, LE> {
self.unsafe_cursor_at_query(pos, stick_end, I::index_to_content, |e| e.content_len())
}
pub fn cursor_at_content_pos(&self, pos: usize, stick_end: bool) -> Cursor<E, I, IE, LE> {
self.cursor_at_query(pos, stick_end, I::index_to_content, |e| e.content_len())
}
pub fn mut_cursor_at_content_pos<'a>(self: &'a mut Pin<Box<Self>>, pos: usize, stick_end: bool) -> MutCursor<'a, E, I, IE, LE> {
self.mut_cursor_at_query(pos, stick_end, I::index_to_content, |e| e.content_len())
}
}
impl<E: ContentTraits, I: FindOffset<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
pub fn offset_len(&self) -> usize {
I::index_to_offset(self.count)
}
pub fn unsafe_cursor_at_offset_pos(&self, pos: usize, stick_end: bool) -> UnsafeCursor<E, I, IE, LE> {
self.unsafe_cursor_at_query(pos, stick_end, I::index_to_offset, |e| e.len())
}
pub fn cursor_at_offset_pos(&self, pos: usize, stick_end: bool) -> Cursor<E, I, IE, LE> {
self.cursor_at_query(pos, stick_end, I::index_to_offset, |e| e.len())
}
pub fn mut_cursor_at_offset_pos<'a>(self: &'a mut Pin<Box<Self>>, pos: usize, stick_end: bool) -> MutCursor<'a, E, I, IE, LE> {
self.mut_cursor_at_query(pos, stick_end, I::index_to_offset, |e| e.len())
}
}
impl<E: ContentTraits + Searchable, I: FindOffset<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
pub fn at_offset(&self, pos: usize) -> Option<E::Item> {
let cursor = self.unsafe_cursor_at_offset_pos(pos, false);
unsafe { cursor.get_item() }
}
}
impl<E: ContentTraits + ContentLength + Searchable, I: FindContent<E>, const IE: usize, const LE: usize> ContentTreeRaw<E, I, IE, LE> {
pub fn at_content(&self, pos: usize) -> Option<E::Item> {
let cursor = self.unsafe_cursor_at_content_pos(pos, false);
unsafe { cursor.get_item() }
}
}