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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
use crate::bucket::{BucketCell, BucketIApi, BucketRwCell, BucketRwIApi};
use crate::common::page::{CoerciblePage, RefPage, BUCKET_LEAF_FLAG};
use crate::common::tree::{MappedBranchPage, MappedLeafPage, TreePage};
use crate::common::{BVec, PgId};
use crate::node::NodeRwCell;
use crate::tx::{TxCell, TxIApi, TxRwCell};
use crate::Error::IncompatibleValue;
use bumpalo::Bump;
use std::marker::PhantomData;

/// Read-only Cursor API
pub trait CursorApi<'tx> {
  /// Moves the cursor to the first item in the bucket and returns its key and value.
  ///
  /// If the bucket is empty then None is returned.
  ///
  /// ```rust
  /// use bbolt_rs::*;
  ///
  /// fn main() -> Result<()> {
  ///   let mut db = Bolt::open_mem()?;
  ///
  ///   db.update(|mut tx| {
  ///     let mut b = tx.create_bucket_if_not_exists("test")?;
  ///     b.put("key1", "value1")?;
  ///     b.put("key2", "value2")?;
  ///     b.put("key3", "value3")?;
  ///     Ok(())
  ///   })?;
  ///
  ///   db.view(|tx| {
  ///     let b = tx.bucket("test").unwrap();
  ///     let mut c = b.cursor();
  ///     let first = c.first();
  ///     assert_eq!(Some((b"key1".as_slice(), Some(b"value1".as_slice()))), first);
  ///     Ok(())
  ///   })?;
  ///
  ///   Ok(())
  /// }
  /// ```
  fn first(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)>;

  /// Moves the cursor to the last item in the bucket and returns its key and value.
  ///
  /// If the bucket is empty then None is returned.
  ///
  /// ```rust
  /// use bbolt_rs::*;
  ///
  /// fn main() -> Result<()> {
  ///   let mut db = Bolt::open_mem()?;
  ///
  ///   db.update(|mut tx| {
  ///     let mut b = tx.create_bucket_if_not_exists("test")?;
  ///     b.put("key1", "value1")?;
  ///     b.put("key2", "value2")?;
  ///     b.put("key3", "value3")?;
  ///     Ok(())
  ///   })?;
  ///
  ///   db.view(|tx| {
  ///     let b = tx.bucket("test").unwrap();
  ///     let mut c = b.cursor();
  ///     let last = c.last();
  ///     assert_eq!(Some((b"key3".as_slice(), Some(b"value3".as_slice()))), last);
  ///     Ok(())
  ///   })?;
  ///
  ///   Ok(())
  /// }
  /// ```
  fn last(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)>;

  /// Moves the cursor to the next item in the bucket and returns its key and value.
  ///
  /// If the cursor is at the end of the bucket then None is returned.
  ///
  /// ```rust
  /// use bbolt_rs::*;
  ///
  /// fn main() -> Result<()> {
  ///   let mut db = Bolt::open_mem()?;
  ///
  ///   db.update(|mut tx| {
  ///     let mut b = tx.create_bucket_if_not_exists("test")?;
  ///     b.put("key1", "value1")?;
  ///     b.put("key2", "value2")?;
  ///     b.put("key3", "value3")?;
  ///     Ok(())
  ///   })?;
  ///
  ///   db.view(|tx| {
  ///     let b = tx.bucket("test").unwrap();
  ///     let mut c = b.cursor();
  ///     c.first();
  ///     let next = c.next();
  ///     assert_eq!(Some((b"key2".as_slice(), Some(b"value2".as_slice()))), next);
  ///     Ok(())
  ///   })?;
  ///
  ///   Ok(())
  /// }
  /// ```
  fn next(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)>;

  /// Moves the cursor to the previous item in the bucket and returns its key and value.
  /// If the cursor is at the beginning of the bucket then None is returned.
  ///
  /// ```rust
  /// use bbolt_rs::*;
  ///
  /// fn main() -> Result<()> {
  ///   let mut db = Bolt::open_mem()?;
  ///
  ///   db.update(|mut tx| {
  ///     let mut b = tx.create_bucket_if_not_exists("test")?;
  ///     b.put("key1", "value1")?;
  ///     b.put("key2", "value2")?;
  ///     b.put("key3", "value3")?;
  ///     Ok(())
  ///   })?;
  ///
  ///   db.view(|tx| {
  ///     let b = tx.bucket("test").unwrap();
  ///     let mut c = b.cursor();
  ///     c.last();
  ///     let prev = c.prev();
  ///     assert_eq!(Some((b"key2".as_slice(), Some(b"value2".as_slice()))), prev);
  ///     Ok(())
  ///   })?;
  ///
  ///   Ok(())
  /// }
  /// ```
  fn prev(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)>;

  /// Moves the cursor to a given key using a b-tree search and returns it.
  ///
  /// If the key does not exist then the next key is used. If no keys
  /// follow, None is returned.
  ///
  /// ```rust
  /// use bbolt_rs::*;
  ///
  /// fn main() -> Result<()> {
  ///   let mut db = Bolt::open_mem()?;
  ///
  ///   db.update(|mut tx| {
  ///     let mut b = tx.create_bucket_if_not_exists("test")?;
  ///     b.put("key1", "value1")?;
  ///     b.put("key2", "value2")?;
  ///     b.put("key3", "value3")?;
  ///     Ok(())
  ///   })?;
  ///
  ///   db.view(|tx| {
  ///     let b = tx.bucket("test").unwrap();
  ///     let mut c = b.cursor();
  ///     let seek = c.seek("key2");
  ///     assert_eq!(Some((b"key2".as_slice(), Some(b"value2".as_slice()))), seek);
  ///     Ok(())
  ///   })?;
  ///
  ///   Ok(())
  /// }
  /// ```
  fn seek<T: AsRef<[u8]>>(&mut self, seek: T) -> Option<(&'tx [u8], Option<&'tx [u8]>)>;
}

/// RW Bucket API
pub trait CursorRwApi<'tx>: CursorApi<'tx> {
  /// Removes the current key/value under the cursor from the bucket.
  ///
  /// ```rust
  /// use bbolt_rs::*;
  ///
  /// fn main() -> Result<()> {
  ///   let mut db = Bolt::open_mem()?;
  ///
  ///   db.update(|mut tx| {
  ///     let mut b = tx.create_bucket_if_not_exists("test")?;
  ///     b.put("key1", "value1")?;
  ///     b.put("key2", "value2")?;
  ///     b.put("key3", "value3")?;
  ///     Ok(())
  ///   })?;
  ///
  ///   db.update(|mut tx| {
  ///     let mut b = tx.bucket_mut("test").unwrap();
  ///     let mut c = b.cursor_mut();
  ///     c.seek("key2");
  ///     c.delete()?;
  ///     Ok(())
  ///   })?;
  ///
  ///   db.view(|tx| {
  ///     let b = tx.bucket("test").unwrap();
  ///     let mut c = b.cursor();
  ///     let seek = c.seek("key2");
  ///     assert_eq!(Some((b"key3".as_slice(), Some(b"value3".as_slice()))), seek);
  ///     Ok(())
  ///   })?;
  ///
  ///   Ok(())
  /// }
  /// ```
  fn delete(&mut self) -> crate::Result<()>;
}

pub(crate) enum CursorWrapper<'tx> {
  R(InnerCursor<'tx, TxCell<'tx>, BucketCell<'tx>>),
  RW(InnerCursor<'tx, TxRwCell<'tx>, BucketRwCell<'tx>>),
}

/// Read-only Cursor
///
pub struct CursorImpl<'tx> {
  c: CursorWrapper<'tx>,
}

impl<'tx> From<InnerCursor<'tx, TxCell<'tx>, BucketCell<'tx>>> for CursorImpl<'tx> {
  fn from(value: InnerCursor<'tx, TxCell<'tx>, BucketCell<'tx>>) -> Self {
    CursorImpl {
      c: CursorWrapper::R(value),
    }
  }
}

impl<'tx> From<InnerCursor<'tx, TxRwCell<'tx>, BucketRwCell<'tx>>> for CursorImpl<'tx> {
  fn from(value: InnerCursor<'tx, TxRwCell<'tx>, BucketRwCell<'tx>>) -> Self {
    CursorImpl {
      c: CursorWrapper::RW(value),
    }
  }
}

impl<'tx> CursorApi<'tx> for CursorImpl<'tx> {
  fn first(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    match &mut self.c {
      CursorWrapper::R(r) => r.api_first(),
      CursorWrapper::RW(rw) => rw.api_first(),
    }
  }

  fn last(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    match &mut self.c {
      CursorWrapper::R(r) => r.api_last(),
      CursorWrapper::RW(rw) => rw.api_last(),
    }
  }

  fn next(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    match &mut self.c {
      CursorWrapper::R(r) => r.api_next(),
      CursorWrapper::RW(rw) => rw.api_next(),
    }
  }

  fn prev(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    match &mut self.c {
      CursorWrapper::R(r) => r.api_prev(),
      CursorWrapper::RW(rw) => rw.api_prev(),
    }
  }

  fn seek<T: AsRef<[u8]>>(&mut self, seek: T) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    match &mut self.c {
      CursorWrapper::R(r) => r.api_seek(seek.as_ref()),
      CursorWrapper::RW(rw) => rw.api_seek(seek.as_ref()),
    }
  }
}

/// Read/Write Cursor
pub struct CursorRwImpl<'tx> {
  c: InnerCursor<'tx, TxRwCell<'tx>, BucketRwCell<'tx>>,
}

impl<'tx> CursorRwImpl<'tx> {
  pub(crate) fn new(c: InnerCursor<'tx, TxRwCell<'tx>, BucketRwCell<'tx>>) -> Self {
    CursorRwImpl { c }
  }
}

impl<'tx> From<InnerCursor<'tx, TxRwCell<'tx>, BucketRwCell<'tx>>> for CursorRwImpl<'tx> {
  fn from(value: InnerCursor<'tx, TxRwCell<'tx>, BucketRwCell<'tx>>) -> Self {
    CursorRwImpl::new(value)
  }
}

impl<'tx> CursorApi<'tx> for CursorRwImpl<'tx> {
  fn first(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    self.c.api_first()
  }

  fn last(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    self.c.api_last()
  }

  fn next(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    self.c.api_next()
  }

  fn prev(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    self.c.api_prev()
  }

  fn seek<T: AsRef<[u8]>>(&mut self, seek: T) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    self.c.api_seek(seek.as_ref())
  }
}

impl<'tx> CursorRwApi<'tx> for CursorRwImpl<'tx> {
  fn delete(&mut self) -> crate::Result<()> {
    self.c.api_delete()
  }
}

pub(crate) trait CursorIApi<'tx>: Clone {
  /// See [CursorApi::first]
  fn api_first(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)>;

  fn i_first(&mut self) -> Option<(&'tx [u8], &'tx [u8], u32)>;

  /// See [CursorApi::next]
  fn api_next(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)>;

  /// i_next moves to the next leaf element and returns the key and value.
  /// If the cursor is at the last leaf element then it stays there and returns nil.
  fn i_next(&mut self) -> Option<(&'tx [u8], &'tx [u8], u32)>;

  /// See [CursorApi::prev]
  fn api_prev(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)>;

  /// i_prev moves the cursor to the previous item in the bucket and returns its key and value.
  /// If the cursor is at the beginning of the bucket then a nil key and value are returned.
  fn i_prev(&mut self) -> Option<(&'tx [u8], &'tx [u8], u32)>;

  /// See [CursorApi::last]
  fn api_last(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)>;

  /// i_last moves the cursor to the last leaf element under the last page in the stack.
  fn i_last(&mut self);

  /// key_value returns the key and value of the current leaf element.
  fn key_value(&self) -> Option<(&'tx [u8], &'tx [u8], u32)>;

  /// See [CursorApi::seek]
  fn api_seek(&mut self, seek: &[u8]) -> Option<(&'tx [u8], Option<&'tx [u8]>)>;

  /// i_seek moves the cursor to a given key and returns it.
  /// If the key does not exist then the next key is used.
  fn i_seek(&mut self, seek: &[u8]) -> Option<(&'tx [u8], &'tx [u8], u32)>;

  /// first moves the cursor to the first leaf element under the last page in the stack.
  fn go_to_first_element_on_the_stack(&mut self);

  /// search recursively performs a binary search against a given page/node until it finds a given key.
  fn search(&mut self, key: &[u8], pgid: PgId);

  fn search_inodes(&mut self, key: &[u8]);

  fn search_node(&mut self, key: &[u8], node: NodeRwCell<'tx>);

  fn search_page(&mut self, key: &[u8], page: &RefPage);
}

pub(crate) trait CursorRwIApi<'tx>: CursorIApi<'tx> {
  /// node returns the node that the cursor is currently positioned on.
  fn node(&mut self) -> NodeRwCell<'tx>;

  /// See [CursorRwApi::delete]
  fn api_delete(&mut self) -> crate::Result<()>;
}

#[derive(Copy, Clone)]
pub enum PageNode<'tx> {
  Page(RefPage<'tx>),
  Node(NodeRwCell<'tx>),
}

#[derive(Clone)]
pub struct ElemRef<'tx> {
  pn: PageNode<'tx>,
  index: i32,
}

impl<'tx> ElemRef<'tx> {
  /// count returns the number of inodes or page elements.
  fn count(&self) -> u32 {
    match &self.pn {
      PageNode::Page(r) => r.count as u32,
      PageNode::Node(n) => n.cell.borrow().inodes.len() as u32,
    }
  }

  /// is_leaf returns whether the ref is pointing at a leaf page/node.
  fn is_leaf(&self) -> bool {
    match &self.pn {
      PageNode::Page(r) => r.is_leaf(),
      PageNode::Node(n) => n.cell.borrow().is_leaf,
    }
  }
}

#[derive(Clone)]
pub(crate) struct InnerCursor<'tx, T: TxIApi<'tx>, B: BucketIApi<'tx, T>> {
  bucket: B,
  stack: BVec<'tx, ElemRef<'tx>>,
  phantom_t: PhantomData<T>,
}

impl<'tx, T: TxIApi<'tx>, B: BucketIApi<'tx, T>> InnerCursor<'tx, T, B> {
  pub(crate) fn new(cell: B, bump: &'tx Bump) -> Self {
    cell
      .tx()
      .split_r()
      .stats
      .as_ref()
      .unwrap()
      .inc_cursor_count(1);
    InnerCursor {
      bucket: cell,
      stack: BVec::with_capacity_in(0, bump),
      phantom_t: PhantomData,
    }
  }
}

impl<'tx, T: TxIApi<'tx>, B: BucketIApi<'tx, T>> CursorIApi<'tx> for InnerCursor<'tx, T, B> {
  fn api_first(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    let (k, v, flags) = self.i_first()?;
    if (flags & BUCKET_LEAF_FLAG) != 0 {
      return Some((k, None));
    }
    Some((k, Some(v)))
  }

  fn i_first(&mut self) -> Option<(&'tx [u8], &'tx [u8], u32)> {
    self.stack.clear();

    // TODO: Optimize this a bit for the internal API. BucketImpl::root_page_node?
    let root = self.bucket.root();
    let pn = self.bucket.page_node(root);
    self.stack.push(ElemRef { pn, index: 0 });

    self.go_to_first_element_on_the_stack();

    // If we land on an empty page then move to the next value.
    // https://github.com/boltdb/bolt/issues/450
    if self.stack.last().unwrap().count() == 0 {
      self.i_next();
    }

    let (k, v, flags) = self.key_value()?;
    if (flags & BUCKET_LEAF_FLAG) != 0 {
      return Some((k, &[], flags));
    }
    Some((k, v, flags))
  }

  fn api_next(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    let (k, v, flags) = self.i_next()?;
    if flags & BUCKET_LEAF_FLAG != 0 {
      Some((k, None))
    } else {
      Some((k, Some(v)))
    }
  }

  /// next moves to the next leaf element and returns the key and value.
  /// If the cursor is at the last leaf element then it stays there and returns nil.
  fn i_next(&mut self) -> Option<(&'tx [u8], &'tx [u8], u32)> {
    loop {
      // Attempt to move over one element until we're successful.
      // Move up the stack as we hit the end of each page in our stack.
      let mut stack_exhausted = true;
      let mut new_stack_depth = 0;
      for (depth, elem) in self.stack.iter_mut().enumerate().rev() {
        new_stack_depth = depth + 1;
        if elem.index < elem.count() as i32 - 1 {
          elem.index += 1;
          stack_exhausted = false;
          break;
        }
      }

      // If we've hit the root page then stop and return. This will leave the
      // cursor on the last element of the last page.
      if stack_exhausted {
        return None;
      }

      // Otherwise start from where we left off in the stack and find the
      // first element of the first leaf page.
      self.stack.truncate(new_stack_depth);
      self.go_to_first_element_on_the_stack();

      // If this is an empty page then restart and move back up the stack.
      // https://github.com/boltdb/bolt/issues/450
      if let Some(elem) = self.stack.last() {
        if elem.count() == 0 {
          continue;
        }
      }

      return self.key_value();
    }
  }

  fn api_prev(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    let (k, v, flags) = self.i_prev()?;
    if flags & BUCKET_LEAF_FLAG != 0 {
      Some((k, None))
    } else {
      Some((k, Some(v)))
    }
  }

  /// prev moves the cursor to the previous item in the bucket and returns its key and value.
  /// If the cursor is at the beginning of the bucket then a nil key and value are returned.
  fn i_prev(&mut self) -> Option<(&'tx [u8], &'tx [u8], u32)> {
    // Attempt to move back one element until we're successful.
    // Move up the stack as we hit the beginning of each page in our stack.
    let mut new_stack_depth = 0;
    let mut stack_exhausted = true;
    for (depth, elem) in self.stack.iter_mut().enumerate().rev() {
      new_stack_depth = depth + 1;
      if elem.index > 0 {
        elem.index -= 1;
        stack_exhausted = false;
        break;
      }
    }
    if stack_exhausted {
      self.stack.truncate(0);
    } else {
      self.stack.truncate(new_stack_depth);
    }

    // If we've hit the end then return None
    if self.stack.is_empty() {
      return None;
    }

    // Move down the stack to find the last element of the last leaf under this branch.
    self.i_last();

    self.key_value()
  }

  fn api_last(&mut self) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    self.stack.truncate(0);
    let root = self.bucket.root();
    let pn = self.bucket.page_node(root);
    let mut elem_ref = ElemRef { pn, index: 0 };
    elem_ref.index = elem_ref.count() as i32 - 1;
    self.stack.push(elem_ref);
    self.i_last();

    while !self.stack.is_empty() && self.stack.last().unwrap().count() == 0 {
      self.i_prev();
    }

    if self.stack.is_empty() {
      return None;
    }

    let (k, v, flags) = self.key_value().unwrap();

    if flags & BUCKET_LEAF_FLAG != 0 {
      Some((k, None))
    } else {
      Some((k, Some(v)))
    }
  }

  /// last moves the cursor to the last leaf element under the last page in the stack.

  fn i_last(&mut self) {
    loop {
      // Exit when we hit a leaf page.
      if let Some(elem) = self.stack.last() {
        if elem.is_leaf() {
          break;
        }

        // Keep adding pages pointing to the last element in the stack.
        let pgid = match &elem.pn {
          PageNode::Page(page) => {
            let branch_page = MappedBranchPage::coerce_ref(page).unwrap();
            branch_page.get_elem(elem.index as u16).unwrap().pgid()
          }
          PageNode::Node(node) => node.cell.borrow().inodes[elem.index as usize].pgid(),
        };

        let pn = self.bucket.page_node(pgid);
        let mut next_elem = ElemRef { pn, index: 0 };
        next_elem.index = next_elem.count() as i32 - 1;
        self.stack.push(next_elem);
      }
    }
  }

  fn key_value(&self) -> Option<(&'tx [u8], &'tx [u8], u32)> {
    let elem_ref = self.stack.last().unwrap();
    let pn_count = elem_ref.count();

    // If the cursor is pointing to the end of page/node then return nil.
    if pn_count == 0 || elem_ref.index as u32 > pn_count {
      return None;
    }

    match &elem_ref.pn {
      // Retrieve value from page.
      PageNode::Page(r) => {
        let l = MappedLeafPage::coerce_ref(r).unwrap();
        l.get_elem(elem_ref.index as u16)
          .map(|inode| (inode.key(), inode.value(), inode.flags()))
      }
      // Retrieve value from node.
      PageNode::Node(n) => {
        let ref_node = n.cell.borrow();
        ref_node
          .inodes
          .get(elem_ref.index as usize)
          .map(|inode| (inode.key(), inode.value(), inode.flags()))
      }
    }
  }

  fn api_seek(&mut self, seek: &[u8]) -> Option<(&'tx [u8], Option<&'tx [u8]>)> {
    let mut vals = self.i_seek(seek);

    if let Some(elem_ref) = self.stack.last() {
      if elem_ref.index >= elem_ref.count() as i32 {
        vals = self.i_next();
      }
    }

    let (k, v, flags) = vals?;
    if flags & BUCKET_LEAF_FLAG != 0 {
      Some((k, None))
    } else {
      Some((k, Some(v)))
    }
  }

  fn i_seek(&mut self, seek: &[u8]) -> Option<(&'tx [u8], &'tx [u8], u32)> {
    self.stack.truncate(0);
    let root = self.bucket.root();
    self.search(seek, root);

    self.key_value()
  }

  /// first moves the cursor to the first leaf element under the last page in the stack.
  fn go_to_first_element_on_the_stack(&mut self) {
    loop {
      let _slice = self.stack.as_slice();
      let pgid = {
        // Exit when we hit a leaf page.
        let r = self.stack.last().unwrap();
        if r.is_leaf() {
          break;
        }

        // Keep adding pages pointing to the first element to the stack.
        match r.pn {
          PageNode::Page(page) => {
            let branch_page = MappedBranchPage::coerce_ref(&page).unwrap();
            let elem = branch_page.get_elem(r.index as u16).unwrap();
            elem.pgid()
          }
          PageNode::Node(node) => {
            let node_borrow = node.cell.borrow();
            node_borrow.inodes[r.index as usize].pgid()
          }
        }
      };
      let pn = self.bucket.page_node(pgid);
      self.stack.push(ElemRef { pn, index: 0 })
    }
  }

  /// search recursively performs a binary search against a given page/node until it finds a given key.
  fn search(&mut self, key: &[u8], pgid: PgId) {
    let pn = self.bucket.page_node(pgid);

    if let PageNode::Page(page) = &pn {
      if !page.is_leaf() && !page.is_branch() {
        panic!("invalid page type: {}, {:X}", page.id, page.flags);
      }
    }

    let elem = ElemRef { pn, index: 0 };

    // If we're on a leaf page/node then find the specific node.
    let elem_is_leaf = elem.is_leaf();

    self.stack.push(elem);

    if elem_is_leaf {
      self.search_inodes(key);
      return;
    }

    match &pn {
      PageNode::Page(page) => self.search_page(key, page),
      PageNode::Node(node) => self.search_node(key, *node),
    }
  }

  /// search_inodes searches the leaf node on the top of the stack for a key.
  fn search_inodes(&mut self, key: &[u8]) {
    if let Some(elem) = self.stack.last_mut() {
      let index = match &elem.pn {
        // If we have a page then search its leaf elements.
        PageNode::Page(page) => {
          let leaf_page = MappedLeafPage::coerce_ref(page).unwrap();
          leaf_page
            .elements()
            .partition_point(|elem| unsafe { elem.key(leaf_page.page_ptr().cast_const()) } < key)
        }
        // If we have a node then search its inodes.
        PageNode::Node(node) => node
          .cell
          .borrow()
          .inodes
          .partition_point(|inode| inode.key() < key),
      };
      elem.index = index as i32;
    }
  }

  fn search_node(&mut self, key: &[u8], node: NodeRwCell<'tx>) {
    let (index, pgid) = {
      let w = node.cell.borrow();

      let r = w.inodes.binary_search_by_key(&key, |inode| inode.key());
      let index = r.unwrap_or_else(|index| if index > 0 { index - 1 } else { index });
      (index as u32, w.inodes[index].pgid())
    };

    if let Some(elem) = self.stack.last_mut() {
      elem.index = index as i32;
    }

    // Recursively search to the next page.
    self.search(key, pgid)
  }

  fn search_page(&mut self, key: &[u8], page: &RefPage) {
    let branch_page = MappedBranchPage::coerce_ref(page).unwrap();
    let elements = branch_page.elements();
    debug_assert_ne!(0, elements.len());
    let r = branch_page
      .elements()
      .binary_search_by_key(&key, |elem| unsafe {
        elem.key(branch_page.page_ptr().cast_const())
      });
    let index = r.unwrap_or_else(|index| if index > 0 { index - 1 } else { index });

    if let Some(elem) = self.stack.last_mut() {
      elem.index = index as i32;
    }
    let pgid = branch_page.elements()[index].pgid();

    // Recursively search to the next page.
    self.search(key, pgid)
  }
}

impl<'tx, B: BucketRwIApi<'tx>> CursorRwIApi<'tx> for InnerCursor<'tx, TxRwCell<'tx>, B> {
  fn node(&mut self) -> NodeRwCell<'tx> {
    assert!(
      !self.stack.is_empty(),
      "accessing a node with a zero-length cursor stack"
    );

    // If the top of the stack is a leaf node then just return it.
    if let Some(elem_ref) = self.stack.last() {
      if let PageNode::Node(node) = elem_ref.pn {
        if node.cell.borrow().is_leaf {
          return node;
        }
      }
    }

    // Start from root and traverse down the hierarchy.
    let mut n = {
      match &self.stack.first().unwrap().pn {
        PageNode::Page(page) => self.bucket.node(page.id, None),
        PageNode::Node(node) => *node,
      }
    };
    let _stack = &self.stack[0..self.stack.len() - 1];
    for elem in &self.stack[0..self.stack.len() - 1] {
      assert!(!n.cell.borrow().is_leaf, "expected branch node");
      n = n.child_at(elem.index as u32);
    }
    assert!(n.cell.borrow().is_leaf, "expected leaf node");
    n
  }

  fn api_delete(&mut self) -> crate::Result<()> {
    let (k, _, flags) = self.key_value().unwrap();
    if flags & BUCKET_LEAF_FLAG != 0 {
      return Err(IncompatibleValue);
    }
    self.node().del(k);
    Ok(())
  }
}

#[cfg(test)]
mod tests {
  use crate::test_support::TestDb;
  use crate::{
    BucketApi, BucketRwApi, CursorApi, CursorRwApi, DbApi, DbRwAPI, Error, TxApi, TxRwRefApi,
  };

  /// Ensure that a Tx cursor can seek to the appropriate keys.
  #[test]
  fn test_cursor_seek() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    db.update(|mut tx| {
      let mut b = tx.create_bucket(b"widgets")?;
      b.put(b"foo", b"0001")?;
      b.put(b"bar", b"0002")?;
      b.put(b"baz", b"0003")?;
      let _ = b.create_bucket(b"bkt")?;
      Ok(())
    })?;
    db.view(|tx| {
      let b = tx.bucket(b"widgets").unwrap();
      let mut c = b.cursor();
      // Exact match should go to the key.
      assert_eq!(
        (b"bar".as_slice(), Some(b"0002".as_slice())),
        c.seek(b"bar").unwrap()
      );
      // Inexact match should go to the next key.
      assert_eq!(
        (b"baz".as_slice(), Some(b"0003".as_slice())),
        c.seek(b"bas").unwrap()
      );
      // Low key should go to the first key.
      assert_eq!(
        (b"bar".as_slice(), Some(b"0002".as_slice())),
        c.seek(b"").unwrap()
      );
      // High key should return no key.
      assert_eq!(None, c.seek(b"zzz"));
      // Buckets should return their key but no value.
      assert_eq!((b"bkt".as_slice(), None), c.seek(b"bkt").unwrap());
      Ok(())
    })
  }

  #[test]
  #[cfg(not(miri))]
  fn test_cursor_delete() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    let count = 1000u64;
    let value = [0u8; 100];
    db.update(|mut tx| {
      let mut b = tx.create_bucket(b"widgets")?;
      for i in 0..count {
        let be_i = i.to_be_bytes();
        b.put(be_i, value)?;
      }
      let _ = b.create_bucket(b"sub")?;
      Ok(())
    })?;
    db.must_check();
    db.update(|mut tx| {
      let b = tx.bucket_mut(b"widgets").unwrap();
      let mut c = b.cursor_mut();
      let bound = (count / 2).to_be_bytes();
      let (mut key, _) = c.first().unwrap();
      while key < bound.as_slice() {
        c.delete()?;
        key = c.next().unwrap().0;
      }
      c.seek(b"sub");
      assert_eq!(Err(Error::IncompatibleValue), c.delete());
      Ok(())
    })?;
    db.must_check();
    db.view(|tx| {
      let b = tx.bucket(b"widgets").unwrap();
      let stats = b.stats();
      assert_eq!((count / 2) + 1, stats.key_n as u64);
      Ok(())
    })?;
    Ok(())
  }

  #[test]
  #[cfg(not(miri))]
  fn test_cursor_seek_large() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    let count = 1000u64;
    let value = [0u8; 100];
    db.update(|mut tx| {
      let mut b = tx.create_bucket(b"widgets")?;
      for i in (0..count).step_by(100) {
        for j in (i..i + 100).step_by(2) {
          let k = j.to_be_bytes();
          b.put(k, value)?;
        }
      }
      Ok(())
    })?;
    db.view(|tx| {
      let b = tx.bucket(b"widgets").unwrap();
      let mut c = b.cursor();
      for i in 0..count {
        let seek = i.to_be_bytes();
        let sought = c.seek(seek);

        if i == count - 1 {
          assert!(sought.is_none(), "expected None");
          continue;
        }
        let k = sought.unwrap().0;
        let num = u64::from_be_bytes(k.try_into().unwrap());
        if i % 2 == 0 {
          assert_eq!(num, i, "unexpected num: {}", num)
        } else {
          assert_eq!(num, i + 1, "unexpected num: {}", num)
        }
      }
      Ok(())
    })?;
    Ok(())
  }

  #[test]
  fn test_cursor_empty_bucket() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    db.update(|mut tx| {
      let _ = tx.create_bucket(b"widgets")?;
      Ok(())
    })?;
    db.view(|tx| {
      let b = tx.bucket(b"widgets").unwrap();
      let mut c = b.cursor();
      let kv = c.first();
      assert_eq!(None, kv, "unexpected kv: {:?}", kv);
      Ok(())
    })?;
    Ok(())
  }

  #[test]
  fn test_cursor_empty_bucket_reverse() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    db.update(|mut tx| {
      let _ = tx.create_bucket(b"widgets")?;
      Ok(())
    })?;
    db.view(|tx| {
      let b = tx.bucket(b"widgets").unwrap();
      let mut c = b.cursor();
      let kv = c.last();
      assert_eq!(None, kv, "unexpected kv: {:?}", kv);
      Ok(())
    })?;
    Ok(())
  }

  #[test]
  fn test_cursor_iterate_leaf() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    db.update(|mut tx| {
      let mut b = tx.create_bucket(b"widgets")?;
      b.put(b"baz", [])?;
      b.put(b"foo", [0])?;
      b.put(b"bar", [1])?;
      Ok(())
    })?;
    let tx = db.begin()?;
    {
      let b = tx.bucket(b"widgets").unwrap();
      let mut c = b.cursor();
      assert_eq!(Some((b"bar".as_slice(), Some([1].as_slice()))), c.first());
      assert_eq!(Some((b"baz".as_slice(), Some([].as_slice()))), c.next());
      assert_eq!(Some((b"foo".as_slice(), Some([0].as_slice()))), c.next());
      assert_eq!(None, c.next());
      assert_eq!(None, c.next());
    }
    Ok(())
  }

  #[test]
  fn test_cursor_leaf_root_reverse() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    db.update(|mut tx| {
      let mut b = tx.create_bucket(b"widgets")?;
      b.put(b"baz", [])?;
      b.put(b"foo", [0])?;
      b.put(b"bar", [1])?;
      Ok(())
    })?;
    let tx = db.begin()?;
    {
      let b = tx.bucket(b"widgets").unwrap();
      let mut c = b.cursor();
      assert_eq!(Some((b"foo".as_slice(), Some([0].as_slice()))), c.last());
      assert_eq!(Some((b"baz".as_slice(), Some([].as_slice()))), c.prev());
      assert_eq!(Some((b"bar".as_slice(), Some([1].as_slice()))), c.prev());
      assert_eq!(None, c.prev());
      assert_eq!(None, c.prev());
    }
    Ok(())
  }

  #[test]
  fn test_cursor_restart() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    db.update(|mut tx| {
      let mut b = tx.create_bucket(b"widgets")?;
      b.put("foo", [])?;
      b.put("bar", [])?;
      Ok(())
    })?;
    let tx = db.begin()?;
    {
      let b = tx.bucket(b"widgets").unwrap();
      let mut c = b.cursor();
      assert_eq!(Some((b"bar".as_slice(), Some([].as_slice()))), c.first());
      assert_eq!(Some((b"foo".as_slice(), Some([].as_slice()))), c.next());
      assert_eq!(Some((b"bar".as_slice(), Some([].as_slice()))), c.first());
      assert_eq!(Some((b"foo".as_slice(), Some([].as_slice()))), c.next());
    }
    Ok(())
  }

  #[test]
  fn test_cursor_first_empty_pages() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    db.update(|mut tx| {
      let mut b = tx.create_bucket(b"widgets")?;
      for i in 1..1000u64 {
        b.put(bytemuck::bytes_of(&i), [])?;
      }
      Ok(())
    })?;
    db.update(|mut tx| {
      let mut b = tx.bucket_mut(b"widgets").unwrap();
      for i in 1..600u64 {
        b.delete(bytemuck::bytes_of(&i))?;
      }
      let mut c = b.cursor();
      let mut kv = c.first();
      let mut n = 0;
      while kv.is_some() {
        n += 1;
        kv = c.next();
      }
      assert_eq!(400, n, "unexpected key count");
      Ok(())
    })
  }

  #[test]
  fn test_cursor_last_empty_pages() -> crate::Result<()> {
    let mut db = TestDb::new()?;
    db.update(|mut tx| {
      let mut b = tx.create_bucket(b"widgets")?;
      for i in 0..1000u64 {
        b.put(bytemuck::bytes_of(&i), [])?;
      }
      Ok(())
    })?;
    db.update(|mut tx| {
      let mut b = tx.bucket_mut(b"widgets").unwrap();
      for i in 200..1000u64 {
        b.delete(bytemuck::bytes_of(&i))?;
      }
      let mut c = b.cursor();
      let mut kv = c.last();
      let mut n = 0;
      while kv.is_some() {
        n += 1;
        kv = c.prev();
      }
      assert_eq!(200, n, "unexpected key count");
      Ok(())
    })
  }

  #[test]
  #[ignore]
  fn test_cursor_quick_check() {
    todo!()
  }

  #[test]
  #[ignore]
  fn test_cursor_quick_check_reverse() {
    todo!()
  }

  #[test]
  #[ignore]
  fn test_cursor_quick_check_buckets_only() {
    todo!()
  }

  #[test]
  #[ignore]
  fn test_cursor_quick_check_buckets_only_reverse() {
    todo!()
  }
}