redb 4.2.0

Rust Embedded DataBase
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
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
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
#[cfg(feature = "experimental-api-5")]
use crate::KeyRange;
use crate::db::TransactionGuard;
use crate::sealed::Sealed;
use crate::sync::Mutex;
#[cfg(feature = "experimental-api-5")]
use crate::tree_store::BtreeCursor;
#[cfg(feature = "experimental_cursor")]
use crate::tree_store::BtreeCursorMut;
#[cfg(not(feature = "experimental-api-5"))]
use crate::tree_store::encode_bounds;
use crate::tree_store::{
    AccessGuardMutInPlace, Btree, BtreeCursorRange, BtreeExtractIf, BtreeHeader, BtreeMut,
    MAX_PAIR_LENGTH, MAX_VALUE_LENGTH, PageAllocator, PageHint, PageNumber, PageResolver,
    PageTracker, RawBtree,
};
use crate::types::{Key, MutInPlaceValue, Value};
use crate::{AccessGuard, AccessGuardMut, StorageError, WriteTransaction};
use crate::{Result, TableHandle};
use alloc::string::String;
use alloc::string::ToString;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::borrow::Borrow;
use core::fmt::{Debug, Formatter};
use core::marker::PhantomData;
use core::ops::Bound;
#[cfg(not(feature = "experimental-api-5"))]
use core::ops::RangeBounds;

/// Informational storage stats about a table
#[derive(Debug)]
pub struct TableStats {
    pub(crate) tree_height: u32,
    pub(crate) leaf_pages: u64,
    pub(crate) branch_pages: u64,
    pub(crate) stored_leaf_bytes: u64,
    pub(crate) metadata_bytes: u64,
    pub(crate) fragmented_bytes: u64,
}

impl TableStats {
    /// Maximum traversal distance to reach the deepest (key, value) pair in the table
    pub fn tree_height(&self) -> u32 {
        self.tree_height
    }

    /// Number of leaf pages that store user data
    pub fn leaf_pages(&self) -> u64 {
        self.leaf_pages
    }

    /// Number of branch pages in the btree that store user data
    pub fn branch_pages(&self) -> u64 {
        self.branch_pages
    }

    /// Number of bytes consumed by keys and values that have been inserted.
    /// Does not include indexing overhead
    pub fn stored_bytes(&self) -> u64 {
        self.stored_leaf_bytes
    }

    /// Number of bytes consumed by keys in internal branch pages, plus other metadata
    pub fn metadata_bytes(&self) -> u64 {
        self.metadata_bytes
    }

    /// Number of bytes consumed by fragmentation, both in data pages and internal metadata tables
    pub fn fragmented_bytes(&self) -> u64 {
        self.fragmented_bytes
    }
}

/// A table containing key-value mappings
pub struct Table<'txn, K: Key + 'static, V: Value + 'static> {
    name: String,
    transaction: &'txn WriteTransaction,
    tree: BtreeMut<K, V>,
}

impl<K: Key + 'static, V: Value + 'static> TableHandle for Table<'_, K, V> {
    fn name(&self) -> &str {
        &self.name
    }
}

struct RetainPanicGuard<'txn> {
    transaction: &'txn WriteTransaction,
    disarmed: bool,
}

impl<'txn> RetainPanicGuard<'txn> {
    fn new(transaction: &'txn WriteTransaction) -> Self {
        Self {
            transaction,
            disarmed: false,
        }
    }

    fn disarm(&mut self) {
        self.disarmed = true;
    }
}

impl Drop for RetainPanicGuard<'_> {
    fn drop(&mut self) {
        if !self.disarmed && crate::panicking() {
            self.transaction.poison();
        }
    }
}

impl<'txn, K: Key + 'static, V: Value + 'static> Table<'txn, K, V> {
    pub(crate) fn new(
        name: &str,
        table_root: Option<BtreeHeader>,
        freed_pages: Arc<Mutex<Vec<PageNumber>>>,
        allocated_pages: Arc<PageTracker>,
        page_allocator: PageAllocator,
        transaction: &'txn WriteTransaction,
    ) -> Table<'txn, K, V> {
        Table {
            name: name.to_string(),
            transaction,
            tree: BtreeMut::new(
                table_root,
                transaction.transaction_guard(),
                page_allocator,
                freed_pages,
                allocated_pages,
            ),
        }
    }

    #[allow(dead_code)]
    #[cfg(not(redb_no_std))]
    pub(crate) fn print_debug(&self, include_values: bool) -> Result {
        self.tree.print_debug(include_values)
    }

    /// Returns an accessor, which allows mutation, to the value corresponding to the given key
    pub fn get_mut<'k>(
        &mut self,
        key: impl Borrow<K::SelfType<'k>>,
    ) -> Result<Option<AccessGuardMut<'_, V>>> {
        self.tree.get_mut(key.borrow())
    }

    /// Removes and returns the first key-value pair in the table
    pub fn pop_first(&mut self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.tree.pop_first()
    }

    /// Removes and returns the last key-value pair in the table
    pub fn pop_last(&mut self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.tree.pop_last()
    }

    /// Applies `predicate` to all key-value pairs. All entries for which
    /// `predicate` evaluates to `true` are returned in an iterator, and those which are read from the iterator are removed
    ///
    /// Note: values not read from the iterator will not be removed
    ///
    /// If the iterator returns an error, later calls keep returning an error
    /// (the failure is not recoverable). Entries already yielded stay
    /// removed; if finalizing their removal fails too, the write transaction
    /// is poisoned and cannot be committed.
    ///
    /// The predicate must not panic. If it panics, the write transaction is
    /// poisoned and [`crate::WriteTransaction::commit`] will return
    /// [`crate::CommitError::TransactionPoisoned`].
    pub fn extract_if<F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        predicate: F,
    ) -> Result<ExtractIf<'_, K, V, F>> {
        self.extract_in_bounds(Bound::Unbounded, Bound::Unbounded, predicate)
    }

    /// Applies `predicate` to all key-value pairs in the specified range. All entries for which
    /// `predicate` evaluates to `true` are returned in an iterator, and those which are read from the iterator are removed
    ///
    /// Note: values not read from the iterator will not be removed
    ///
    /// If the iterator returns an error, later calls keep returning an error
    /// (the failure is not recoverable). Entries already yielded stay
    /// removed; if finalizing their removal fails too, the write transaction
    /// is poisoned and cannot be committed.
    ///
    /// The predicate must not panic. If it panics, the write transaction is
    /// poisoned and [`crate::WriteTransaction::commit`] will return
    /// [`crate::CommitError::TransactionPoisoned`].
    #[cfg(feature = "experimental-api-5")]
    pub fn extract_from_if<'a, F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        range: impl KeyRange<'a, K>,
        predicate: F,
    ) -> Result<ExtractIf<'_, K, V, F>> {
        let (lower, upper) = range.key_bounds();
        self.extract_in_bounds(lower, upper, predicate)
    }

    /// Applies `predicate` to all key-value pairs in the specified range. All entries for which
    /// `predicate` evaluates to `true` are returned in an iterator, and those which are read from the iterator are removed
    ///
    /// Note: values not read from the iterator will not be removed
    ///
    /// If the iterator returns an error, later calls keep returning an error
    /// (the failure is not recoverable). Entries already yielded stay
    /// removed; if finalizing their removal fails too, the write transaction
    /// is poisoned and cannot be committed.
    ///
    /// The predicate must not panic. If it panics, the write transaction is
    /// poisoned and [`crate::WriteTransaction::commit`] will return
    /// [`crate::CommitError::TransactionPoisoned`].
    #[cfg(not(feature = "experimental-api-5"))]
    pub fn extract_from_if<'a, KR, F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        range: impl RangeBounds<KR> + 'a,
        predicate: F,
    ) -> Result<ExtractIf<'_, K, V, F>>
    where
        KR: Borrow<K::SelfType<'a>> + 'a,
    {
        let (lower, upper) = encode_bounds::<K, KR, _>(&range);
        self.extract_in_bounds(lower, upper, predicate)
    }

    fn range_in_bounds(
        &self,
        lower: Bound<Vec<u8>>,
        upper: Bound<Vec<u8>>,
    ) -> Result<Range<'_, K, V>> {
        self.tree
            .range_bounds(lower, upper)
            .map(|x| Range::new(x, self.transaction.transaction_guard()))
    }

    fn extract_in_bounds<F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        lower: Bound<Vec<u8>>,
        upper: Bound<Vec<u8>>,
        predicate: F,
    ) -> Result<ExtractIf<'_, K, V, F>> {
        let inner = self.tree.extract_from_bounds(lower, upper, predicate)?;
        Ok(ExtractIf::new(inner, Some(self.transaction)))
    }

    /// Applies `predicate` to all key-value pairs. All entries for which
    /// `predicate` evaluates to `false` are removed.
    ///
    /// The predicate must not panic. If it panics, the write transaction is
    /// poisoned and [`crate::WriteTransaction::commit`] will return
    /// [`crate::CommitError::TransactionPoisoned`].
    ///
    pub fn retain<F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        predicate: F,
    ) -> Result {
        self.retain_in_bounds(Bound::Unbounded, Bound::Unbounded, predicate)
    }

    /// Applies `predicate` to all key-value pairs in the range `start..end`. All entries for which
    /// `predicate` evaluates to `false` are removed.
    ///
    /// The predicate must not panic. If it panics, the write transaction is
    /// poisoned and [`crate::WriteTransaction::commit`] will return
    /// [`crate::CommitError::TransactionPoisoned`].
    ///
    #[cfg(feature = "experimental-api-5")]
    pub fn retain_in<'a, F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        range: impl KeyRange<'a, K>,
        predicate: F,
    ) -> Result {
        let (lower, upper) = range.key_bounds();
        self.retain_in_bounds(lower, upper, predicate)
    }

    /// Applies `predicate` to all key-value pairs in the range `start..end`. All entries for which
    /// `predicate` evaluates to `false` are removed.
    ///
    /// The predicate must not panic. If it panics, the write transaction is
    /// poisoned and [`crate::WriteTransaction::commit`] will return
    /// [`crate::CommitError::TransactionPoisoned`].
    ///
    #[cfg(not(feature = "experimental-api-5"))]
    pub fn retain_in<'a, KR, F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        range: impl RangeBounds<KR> + 'a,
        predicate: F,
    ) -> Result
    where
        KR: Borrow<K::SelfType<'a>> + 'a,
    {
        let (lower, upper) = encode_bounds::<K, KR, _>(&range);
        self.retain_in_bounds(lower, upper, predicate)
    }

    fn retain_in_bounds<F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool>(
        &mut self,
        lower: Bound<Vec<u8>>,
        upper: Bound<Vec<u8>>,
        predicate: F,
    ) -> Result {
        let mut panic_guard = RetainPanicGuard::new(self.transaction);
        let mut poisoned = false;
        let result = self
            .tree
            .retain_in_bounds(predicate, lower, upper, &mut poisoned);
        panic_guard.disarm();
        if poisoned {
            self.transaction.poison();
        }
        result
    }

    /// Insert mapping of the given key to the given value
    ///
    /// If key is already present it is replaced
    ///
    /// Returns the old value, if the key was present in the table, otherwise None is returned
    pub fn insert<'k, 'v>(
        &mut self,
        key: impl Borrow<K::SelfType<'k>>,
        value: impl Borrow<V::SelfType<'v>>,
    ) -> Result<Option<AccessGuard<'_, V>>> {
        let value_len = V::as_bytes(value.borrow()).as_ref().len();
        if value_len > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(value_len));
        }
        let key_len = K::as_bytes(key.borrow()).as_ref().len();
        if key_len > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(key_len));
        }
        if value_len + key_len > MAX_PAIR_LENGTH {
            return Err(StorageError::ValueTooLarge(value_len + key_len));
        }
        self.tree.insert(key.borrow(), value.borrow())
    }

    /// Removes the given key
    ///
    /// Returns the old value, if the key was present in the table
    pub fn remove<'a>(
        &mut self,
        key: impl Borrow<K::SelfType<'a>>,
    ) -> Result<Option<AccessGuard<'_, V>>> {
        self.tree.remove(key.borrow())
    }

    /// Returns a [`CursorMut`] pointing at the gap before the smallest key
    /// greater than the given bound.
    ///
    /// Passing `Bound::Included(x)` will return a cursor pointing to the gap
    /// before the smallest key greater than or equal to `x`.
    ///
    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the gap
    /// before the smallest key greater than `x`.
    ///
    /// Passing `Bound::Unbounded` will return a cursor pointing to the gap
    /// before the smallest key in the table.
    ///
    /// This is analogous to [`std::collections::BTreeMap::lower_bound_mut`].
    #[cfg(feature = "experimental_cursor")]
    pub fn lower_bound_mut<'a>(
        &mut self,
        bound: Bound<impl Borrow<K::SelfType<'a>>>,
    ) -> Result<CursorMut<'_, K, V>> {
        let bound = bound_to_bytes::<K, _>(&bound);
        let mut inner = self.tree.cursor_mut();
        inner.seek_lower_bound(bound.as_ref().map(|bytes| bytes.as_slice()))?;
        Ok(CursorMut::new(inner, self.transaction))
    }

    /// Returns a [`CursorMut`] pointing at the gap after the greatest key
    /// smaller than the given bound.
    ///
    /// Passing `Bound::Included(x)` will return a cursor pointing to the gap
    /// after the greatest key smaller than or equal to `x`.
    ///
    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the gap
    /// after the greatest key smaller than `x`.
    ///
    /// Passing `Bound::Unbounded` will return a cursor pointing to the gap
    /// after the greatest key in the table.
    ///
    /// This is analogous to [`std::collections::BTreeMap::upper_bound_mut`].
    ///
    /// # Examples
    ///
    /// Inserting a stream of ascending keys through the gap at the end of
    /// the table:
    ///
    /// ```rust
    /// use std::ops::Bound;
    /// use redb::{Database, Error, ReadableTableMetadata, TableDefinition};
    /// # use tempfile::NamedTempFile;
    /// const TABLE: TableDefinition<u64, u64> = TableDefinition::new("my_data");
    ///
    /// # fn main() -> Result<(), Error> {
    /// # #[cfg(not(target_os = "wasi"))]
    /// # let tmpfile = NamedTempFile::new().unwrap();
    /// # #[cfg(target_os = "wasi")]
    /// # let tmpfile = NamedTempFile::new_in("/tmp").unwrap();
    /// # let filename = tmpfile.path();
    /// let db = Database::create(filename)?;
    /// let write_txn = db.begin_write()?;
    /// {
    ///     let mut table = write_txn.open_table(TABLE)?;
    ///     let mut cursor = table.upper_bound_mut(Bound::<u64>::Unbounded)?;
    ///     for key in 0..1000 {
    ///         cursor.insert_before(key, &(key * 2))?;
    ///     }
    ///     cursor.close()?;
    ///     assert_eq!(table.len()?, 1000);
    /// }
    /// write_txn.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "experimental_cursor")]
    pub fn upper_bound_mut<'a>(
        &mut self,
        bound: Bound<impl Borrow<K::SelfType<'a>>>,
    ) -> Result<CursorMut<'_, K, V>> {
        let bound = bound_to_bytes::<K, _>(&bound);
        let mut inner = self.tree.cursor_mut();
        inner.seek_upper_bound(bound.as_ref().map(|bytes| bytes.as_slice()))?;
        Ok(CursorMut::new(inner, self.transaction))
    }

    /// Gets the given key's corresponding entry in the table for in-place manipulation.
    ///
    /// This is analogous to [`std::collections::BTreeMap::entry`], and avoids the double
    /// lookup that a `get` followed by `insert` would require when updating a value.
    pub fn entry<'a>(&'a mut self, key: K::SelfType<'a>) -> Result<Entry<'a, K, V>> {
        let key_len = K::as_bytes(&key).as_ref().len();
        if key_len > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(key_len));
        }
        if self.tree.get(&key)?.is_some() {
            Ok(Entry::Occupied(OccupiedEntry {
                tree: &mut self.tree,
                key,
            }))
        } else {
            Ok(Entry::Vacant(VacantEntry {
                tree: &mut self.tree,
                key,
            }))
        }
    }
}

impl<K: Key + 'static, V: MutInPlaceValue + 'static> Table<'_, K, V> {
    /// Reserve space to insert a key-value pair
    ///
    /// If key is already present it is replaced
    ///
    /// The returned reference will have length equal to `value_length`
    pub fn insert_reserve<'a>(
        &mut self,
        key: impl Borrow<K::SelfType<'a>>,
        value_length: usize,
    ) -> Result<AccessGuardMutInPlace<'_, V>> {
        if value_length > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(value_length));
        }
        let key_len = K::as_bytes(key.borrow()).as_ref().len();
        if key_len > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(key_len));
        }
        if value_length + key_len > MAX_PAIR_LENGTH {
            return Err(StorageError::ValueTooLarge(value_length + key_len));
        }
        self.tree.insert_reserve(key.borrow(), value_length)
    }
}

impl<K: Key + 'static, V: Value + 'static> ReadableTableMetadata for Table<'_, K, V> {
    fn stats(&self) -> Result<TableStats> {
        let tree_stats = self.tree.stats()?;

        Ok(TableStats {
            tree_height: tree_stats.tree_height,
            leaf_pages: tree_stats.leaf_pages,
            branch_pages: tree_stats.branch_pages,
            stored_leaf_bytes: tree_stats.stored_leaf_bytes,
            metadata_bytes: tree_stats.metadata_bytes,
            fragmented_bytes: tree_stats.fragmented_bytes,
        })
    }

    fn len(&self) -> Result<u64> {
        self.tree.len()
    }
}

impl<K: Key + 'static, V: Value + 'static> ReadableTable<K, V> for Table<'_, K, V> {
    fn get<'a>(&self, key: impl Borrow<K::SelfType<'a>>) -> Result<Option<AccessGuard<'_, V>>> {
        self.tree.get(key.borrow())
    }

    #[cfg(feature = "experimental-api-5")]
    fn range<'a>(&self, range: impl KeyRange<'a, K>) -> Result<Range<'_, K, V>> {
        let (lower, upper) = range.key_bounds();
        self.range_in_bounds(lower, upper)
    }

    #[cfg(not(feature = "experimental-api-5"))]
    fn range<'a, KR>(&self, range: impl RangeBounds<KR> + 'a) -> Result<Range<'_, K, V>>
    where
        KR: Borrow<K::SelfType<'a>> + 'a,
    {
        let (lower, upper) = encode_bounds::<K, KR, _>(&range);
        self.range_in_bounds(lower, upper)
    }

    fn first(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.tree.first()
    }

    fn last(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.tree.last()
    }

    #[cfg(feature = "experimental-api-5")]
    fn lower_bound<'a>(
        &self,
        bound: Bound<impl Borrow<K::SelfType<'a>>>,
    ) -> Result<Cursor<'_, K, V>> {
        let bound = bound_to_bytes::<K, _>(&bound);
        let mut inner = self.tree.cursor()?;
        inner.seek_lower_bound(bound.as_ref().map(|bytes| bytes.as_slice()))?;
        Ok(Cursor::new(inner, self.transaction.transaction_guard()))
    }

    #[cfg(feature = "experimental-api-5")]
    fn upper_bound<'a>(
        &self,
        bound: Bound<impl Borrow<K::SelfType<'a>>>,
    ) -> Result<Cursor<'_, K, V>> {
        let bound = bound_to_bytes::<K, _>(&bound);
        let mut inner = self.tree.cursor()?;
        inner.seek_upper_bound(bound.as_ref().map(|bytes| bytes.as_slice()))?;
        Ok(Cursor::new(inner, self.transaction.transaction_guard()))
    }
}

impl<K: Key, V: Value> Sealed for Table<'_, K, V> {}

impl<K: Key + 'static, V: Value + 'static> Drop for Table<'_, K, V> {
    fn drop(&mut self) {
        self.transaction.close_table(
            &self.name,
            &self.tree,
            self.tree.get_root().map(|x| x.length).unwrap_or_default(),
        );
    }
}

fn debug_helper<K: Key + 'static, V: Value + 'static>(
    f: &mut Formatter<'_>,
    name: &str,
    len: Result<u64>,
    first: Result<Option<(AccessGuard<K>, AccessGuard<V>)>>,
    last: Result<Option<(AccessGuard<K>, AccessGuard<V>)>>,
) -> core::fmt::Result {
    write!(f, "Table [ name: \"{name}\", ")?;
    if let Ok(len) = len {
        if len == 0 {
            write!(f, "No entries")?;
        } else if len == 1 {
            if let Ok(first) = first {
                let (key, value) = first.as_ref().unwrap();
                write!(f, "One key-value: {:?} = {:?}", key.value(), value.value())?;
            } else {
                write!(f, "I/O Error accessing table!")?;
            }
        } else {
            if let Ok(first) = first {
                let (key, value) = first.as_ref().unwrap();
                write!(f, "first: {:?} = {:?}, ", key.value(), value.value())?;
            } else {
                write!(f, "I/O Error accessing table!")?;
            }
            if len > 2 {
                write!(f, "...{} more entries..., ", len - 2)?;
            }
            if let Ok(last) = last {
                let (key, value) = last.as_ref().unwrap();
                write!(f, "last: {:?} = {:?}", key.value(), value.value())?;
            } else {
                write!(f, "I/O Error accessing table!")?;
            }
        }
    } else {
        write!(f, "I/O Error accessing table!")?;
    }
    write!(f, " ]")?;

    Ok(())
}

impl<K: Key + 'static, V: Value + 'static> Debug for Table<'_, K, V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        debug_helper(f, &self.name, self.len(), self.first(), self.last())
    }
}

pub trait ReadableTableMetadata {
    /// Retrieves information about storage usage for the table
    fn stats(&self) -> Result<TableStats>;

    /// Returns the number of entries in the table
    fn len(&self) -> Result<u64>;

    /// Returns `true` if the table is empty
    fn is_empty(&self) -> Result<bool> {
        Ok(self.len()? == 0)
    }
}

pub trait ReadableTable<K: Key + 'static, V: Value + 'static>: ReadableTableMetadata {
    /// Returns the value corresponding to the given key
    fn get<'a>(&self, key: impl Borrow<K::SelfType<'a>>) -> Result<Option<AccessGuard<'_, V>>>;

    /// Returns a double-ended iterator over a range of elements in the table
    ///
    /// # Examples
    ///
    /// Usage:
    /// ```rust
    /// use redb::*;
    /// # use tempfile::NamedTempFile;
    /// const TABLE: TableDefinition<&str, u64> = TableDefinition::new("my_data");
    ///
    /// # fn main() -> Result<(), Error> {
    /// # #[cfg(not(target_os = "wasi"))]
    /// # let tmpfile = NamedTempFile::new().unwrap();
    /// # #[cfg(target_os = "wasi")]
    /// # let tmpfile = NamedTempFile::new_in("/tmp").unwrap();
    /// # let filename = tmpfile.path();
    /// let db = Database::create(filename)?;
    /// let write_txn = db.begin_write()?;
    /// {
    ///     let mut table = write_txn.open_table(TABLE)?;
    ///     table.insert("a", &0)?;
    ///     table.insert("b", &1)?;
    ///     table.insert("c", &2)?;
    /// }
    /// write_txn.commit()?;
    ///
    /// let read_txn = db.begin_read()?;
    /// let table = read_txn.open_table(TABLE)?;
    /// let mut iter = table.range("a".."c")?;
    /// let (key, value) = iter.next().unwrap()?;
    /// assert_eq!("a", key.value());
    /// assert_eq!(0, value.value());
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "experimental-api-5")]
    fn range<'a>(&self, range: impl KeyRange<'a, K>) -> Result<Range<'_, K, V>>;

    /// Returns a double-ended iterator over a range of elements in the table
    ///
    /// # Examples
    ///
    /// Usage:
    /// ```rust
    /// use redb::*;
    /// # use tempfile::NamedTempFile;
    /// const TABLE: TableDefinition<&str, u64> = TableDefinition::new("my_data");
    ///
    /// # fn main() -> Result<(), Error> {
    /// # #[cfg(not(target_os = "wasi"))]
    /// # let tmpfile = NamedTempFile::new().unwrap();
    /// # #[cfg(target_os = "wasi")]
    /// # let tmpfile = NamedTempFile::new_in("/tmp").unwrap();
    /// # let filename = tmpfile.path();
    /// let db = Database::create(filename)?;
    /// let write_txn = db.begin_write()?;
    /// {
    ///     let mut table = write_txn.open_table(TABLE)?;
    ///     table.insert("a", &0)?;
    ///     table.insert("b", &1)?;
    ///     table.insert("c", &2)?;
    /// }
    /// write_txn.commit()?;
    ///
    /// let read_txn = db.begin_read()?;
    /// let table = read_txn.open_table(TABLE)?;
    /// let mut iter = table.range("a".."c")?;
    /// let (key, value) = iter.next().unwrap()?;
    /// assert_eq!("a", key.value());
    /// assert_eq!(0, value.value());
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(not(feature = "experimental-api-5"))]
    fn range<'a, KR>(&self, range: impl RangeBounds<KR> + 'a) -> Result<Range<'_, K, V>>
    where
        KR: Borrow<K::SelfType<'a>> + 'a;

    /// Returns the first key-value pair in the table, if it exists
    fn first(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>>;

    /// Returns the last key-value pair in the table, if it exists
    fn last(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>>;

    /// Returns a read-only [`Cursor`] pointing at the gap before the smallest
    /// key greater than the given bound.
    ///
    /// Passing `Bound::Included(x)` will return a cursor pointing to the gap
    /// before the smallest key greater than or equal to `x`.
    ///
    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the gap
    /// before the smallest key greater than `x`.
    ///
    /// Passing `Bound::Unbounded` will return a cursor pointing to the gap
    /// before the smallest key in the table.
    ///
    /// This is analogous to [`std::collections::BTreeMap::lower_bound`].
    ///
    /// # Examples
    ///
    /// Probing around a key in any table, read-only or not. The cursor's
    /// methods additionally require the `experimental_cursor` feature flag:
    ///
    #[cfg_attr(feature = "experimental_cursor", doc = "```rust")]
    #[cfg_attr(not(feature = "experimental_cursor"), doc = "```rust,ignore")]
    /// use std::ops::Bound;
    /// use redb::{Database, Error, ReadableDatabase, ReadableTable, TableDefinition};
    /// # use tempfile::NamedTempFile;
    /// const TABLE: TableDefinition<u64, u64> = TableDefinition::new("my_data");
    ///
    /// fn entry_at_or_after(
    ///     table: &impl ReadableTable<u64, u64>,
    ///     key: u64,
    /// ) -> Result<Option<u64>, Error> {
    ///     let mut cursor = table.lower_bound(Bound::Included(&key))?;
    ///     Ok(cursor.peek_next()?.map(|(key, _)| key.value()))
    /// }
    ///
    /// # fn main() -> Result<(), Error> {
    /// # #[cfg(not(target_os = "wasi"))]
    /// # let tmpfile = NamedTempFile::new().unwrap();
    /// # #[cfg(target_os = "wasi")]
    /// # let tmpfile = NamedTempFile::new_in("/tmp").unwrap();
    /// # let filename = tmpfile.path();
    /// let db = Database::create(filename)?;
    /// let write_txn = db.begin_write()?;
    /// {
    ///     let mut table = write_txn.open_table(TABLE)?;
    ///     for key in 0..10 {
    ///         table.insert(key, &(key * 2))?;
    ///     }
    ///     assert_eq!(entry_at_or_after(&table, 5)?, Some(5));
    /// }
    /// write_txn.commit()?;
    ///
    /// let read_txn = db.begin_read()?;
    /// let table = read_txn.open_table(TABLE)?;
    /// assert_eq!(entry_at_or_after(&table, 5)?, Some(5));
    /// assert_eq!(entry_at_or_after(&table, 100)?, None);
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "experimental-api-5")]
    fn lower_bound<'a>(
        &self,
        bound: Bound<impl Borrow<K::SelfType<'a>>>,
    ) -> Result<Cursor<'_, K, V>>;

    /// Returns a read-only [`Cursor`] pointing at the gap after the greatest
    /// key smaller than the given bound.
    ///
    /// Passing `Bound::Included(x)` will return a cursor pointing to the gap
    /// after the greatest key smaller than or equal to `x`.
    ///
    /// Passing `Bound::Excluded(x)` will return a cursor pointing to the gap
    /// after the greatest key smaller than `x`.
    ///
    /// Passing `Bound::Unbounded` will return a cursor pointing to the gap
    /// after the greatest key in the table.
    ///
    /// This is analogous to [`std::collections::BTreeMap::upper_bound`].
    #[cfg(feature = "experimental-api-5")]
    fn upper_bound<'a>(
        &self,
        bound: Bound<impl Borrow<K::SelfType<'a>>>,
    ) -> Result<Cursor<'_, K, V>>;

    /// Returns a double-ended iterator over all elements in the table
    fn iter(&self) -> Result<Range<'_, K, V>> {
        #[cfg(feature = "experimental-api-5")]
        let range = self.range(..);
        #[cfg(not(feature = "experimental-api-5"))]
        let range = self.range::<K::SelfType<'_>>(..);
        range
    }
}

/// A read-only untyped table
pub struct ReadOnlyUntypedTable {
    name: String,
    tree: RawBtree,
}

impl Sealed for ReadOnlyUntypedTable {}

impl TableHandle for ReadOnlyUntypedTable {
    fn name(&self) -> &str {
        &self.name
    }
}

impl ReadableTableMetadata for ReadOnlyUntypedTable {
    /// Retrieves information about storage usage for the table
    fn stats(&self) -> Result<TableStats> {
        let tree_stats = self.tree.stats()?;

        Ok(TableStats {
            tree_height: tree_stats.tree_height,
            leaf_pages: tree_stats.leaf_pages,
            branch_pages: tree_stats.branch_pages,
            stored_leaf_bytes: tree_stats.stored_leaf_bytes,
            metadata_bytes: tree_stats.metadata_bytes,
            fragmented_bytes: tree_stats.fragmented_bytes,
        })
    }

    fn len(&self) -> Result<u64> {
        self.tree.len()
    }
}

impl ReadOnlyUntypedTable {
    pub(crate) fn new(
        name: &str,
        root_page: Option<BtreeHeader>,
        hint: PageHint,
        fixed_key_size: Option<usize>,
        fixed_value_size: Option<usize>,
        mem: PageResolver,
    ) -> Self {
        Self {
            name: name.to_string(),
            tree: RawBtree::new(root_page, fixed_key_size, fixed_value_size, mem, hint),
        }
    }
}

/// A read-only table
pub struct ReadOnlyTable<K: Key + 'static, V: Value + 'static> {
    name: String,
    tree: Btree<K, V>,
    transaction_guard: Arc<TransactionGuard>,
}

impl<K: Key + 'static, V: Value + 'static> TableHandle for ReadOnlyTable<K, V> {
    fn name(&self) -> &str {
        &self.name
    }
}

impl<K: Key + 'static, V: Value + 'static> ReadOnlyTable<K, V> {
    pub(crate) fn new(
        name: String,
        root_page: Option<BtreeHeader>,
        hint: PageHint,
        guard: Arc<TransactionGuard>,
        mem: PageResolver,
    ) -> Result<ReadOnlyTable<K, V>> {
        Ok(ReadOnlyTable {
            name,
            tree: Btree::new(root_page, hint, guard.clone(), mem)?,
            transaction_guard: guard,
        })
    }

    /// This method is like [`ReadableTable::get()`], but the [`AccessGuard`] is reference counted
    /// and keeps the transaction alive until it is dropped.
    #[cfg(not(feature = "experimental-api-5"))]
    pub fn get<'a>(
        &self,
        key: impl Borrow<K::SelfType<'a>>,
    ) -> Result<Option<AccessGuard<'static, V>>> {
        self.tree.get(key.borrow())
    }

    /// This method is like [`ReadableTable::get()`], but the returned [`OwnedAccessGuard`] is
    /// reference counted and keeps the transaction alive until it is dropped.
    pub fn get_owned<'a>(
        &self,
        key: impl Borrow<K::SelfType<'a>>,
    ) -> Result<Option<OwnedAccessGuard<V>>> {
        Ok(self
            .tree
            .get(key.borrow())?
            .map(|x| OwnedAccessGuard::new(x, self.transaction_guard.clone())))
    }

    /// This method is like [`ReadableTable::range()`], but the iterator is reference counted and keeps the transaction
    /// alive until it is dropped.
    #[cfg(not(feature = "experimental-api-5"))]
    pub fn range<'a, KR>(&self, range: impl RangeBounds<KR>) -> Result<Range<'static, K, V>>
    where
        KR: Borrow<K::SelfType<'a>>,
    {
        let (lower, upper) = encode_bounds::<K, KR, _>(&range);
        self.range_in_bounds(lower, upper)
    }

    fn range_in_bounds(
        &self,
        lower: Bound<Vec<u8>>,
        upper: Bound<Vec<u8>>,
    ) -> Result<Range<'static, K, V>> {
        self.tree
            .range_bounds(lower, upper)
            .map(|x| Range::new(x, self.transaction_guard.clone()))
    }

    /// This method is like [`ReadableTable::range()`], but the returned iterator is reference
    /// counted and keeps the transaction alive until it is dropped, as do the
    /// [`OwnedAccessGuard`]s it yields.
    #[cfg(feature = "experimental-api-5")]
    pub fn range_owned<'a>(&self, range: impl KeyRange<'a, K>) -> Result<OwnedRange<K, V>> {
        let (lower, upper) = range.key_bounds();
        Ok(OwnedRange::new(
            self.range_in_bounds(lower, upper)?,
            self.transaction_guard.clone(),
        ))
    }

    /// This method is like [`ReadableTable::range()`], but the returned iterator is reference
    /// counted and keeps the transaction alive until it is dropped, as do the
    /// [`OwnedAccessGuard`]s it yields.
    #[cfg(not(feature = "experimental-api-5"))]
    pub fn range_owned<'a, KR>(&self, range: impl RangeBounds<KR>) -> Result<OwnedRange<K, V>>
    where
        KR: Borrow<K::SelfType<'a>>,
    {
        let (lower, upper) = encode_bounds::<K, KR, _>(&range);
        Ok(OwnedRange::new(
            self.range_in_bounds(lower, upper)?,
            self.transaction_guard.clone(),
        ))
    }
}

impl<K: Key + 'static, V: Value + 'static> ReadableTableMetadata for ReadOnlyTable<K, V> {
    fn stats(&self) -> Result<TableStats> {
        let tree_stats = self.tree.stats()?;

        Ok(TableStats {
            tree_height: tree_stats.tree_height,
            leaf_pages: tree_stats.leaf_pages,
            branch_pages: tree_stats.branch_pages,
            stored_leaf_bytes: tree_stats.stored_leaf_bytes,
            metadata_bytes: tree_stats.metadata_bytes,
            fragmented_bytes: tree_stats.fragmented_bytes,
        })
    }

    fn len(&self) -> Result<u64> {
        self.tree.len()
    }
}

impl<K: Key + 'static, V: Value + 'static> ReadableTable<K, V> for ReadOnlyTable<K, V> {
    fn get<'a>(&self, key: impl Borrow<K::SelfType<'a>>) -> Result<Option<AccessGuard<'_, V>>> {
        self.tree.get(key.borrow())
    }

    #[cfg(feature = "experimental-api-5")]
    fn range<'a>(&self, range: impl KeyRange<'a, K>) -> Result<Range<'_, K, V>> {
        let (lower, upper) = range.key_bounds();
        self.range_in_bounds(lower, upper)
    }

    #[cfg(not(feature = "experimental-api-5"))]
    fn range<'a, KR>(&self, range: impl RangeBounds<KR> + 'a) -> Result<Range<'_, K, V>>
    where
        KR: Borrow<K::SelfType<'a>> + 'a,
    {
        let (lower, upper) = encode_bounds::<K, KR, _>(&range);
        self.range_in_bounds(lower, upper)
    }

    fn first(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.tree.first()
    }

    fn last(&self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.tree.last()
    }

    #[cfg(feature = "experimental-api-5")]
    fn lower_bound<'a>(
        &self,
        bound: Bound<impl Borrow<K::SelfType<'a>>>,
    ) -> Result<Cursor<'_, K, V>> {
        let bound = bound_to_bytes::<K, _>(&bound);
        let mut inner = self.tree.cursor();
        inner.seek_lower_bound(bound.as_ref().map(|bytes| bytes.as_slice()))?;
        Ok(Cursor::new(inner, self.transaction_guard.clone()))
    }

    #[cfg(feature = "experimental-api-5")]
    fn upper_bound<'a>(
        &self,
        bound: Bound<impl Borrow<K::SelfType<'a>>>,
    ) -> Result<Cursor<'_, K, V>> {
        let bound = bound_to_bytes::<K, _>(&bound);
        let mut inner = self.tree.cursor();
        inner.seek_upper_bound(bound.as_ref().map(|bytes| bytes.as_slice()))?;
        Ok(Cursor::new(inner, self.transaction_guard.clone()))
    }
}

impl<K: Key, V: Value> Sealed for ReadOnlyTable<K, V> {}

impl<K: Key + 'static, V: Value + 'static> Debug for ReadOnlyTable<K, V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        debug_helper(f, &self.name, self.len(), self.first(), self.last())
    }
}

pub struct ExtractIf<
    'a,
    K: Key + 'static,
    V: Value + 'static,
    F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool,
> {
    inner: BtreeExtractIf<'a, K, V, F>,
    poison_target: Option<&'a WriteTransaction>,
}

impl<
    'a,
    K: Key + 'static,
    V: Value + 'static,
    F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool,
> ExtractIf<'a, K, V, F>
{
    pub(crate) fn new(
        inner: BtreeExtractIf<'a, K, V, F>,
        poison_target: Option<&'a WriteTransaction>,
    ) -> Self {
        Self {
            inner,
            poison_target,
        }
    }

    /// Closes the iterator.
    ///
    /// Entries already returned by the iterator remain removed, and unread
    /// entries are not tested by the predicate or removed. Dropping the iterator
    /// also closes it, but this method returns any error encountered while
    /// finalizing the iterator, including when the iterator already closed
    /// itself after an iteration error.
    pub fn close(mut self) -> Result {
        self.inner.close()
    }
}

impl<
    K: Key + 'static,
    V: Value + 'static,
    F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool,
> Drop for ExtractIf<'_, K, V, F>
{
    fn drop(&mut self) {
        // Entries already yielded may have removals pending; if a flush
        // failed the table would silently keep them, so poison the
        // transaction instead of letting it commit. An iteration error
        // alone must not poison: close_failed reports lost removals, and
        // close() also re-raises after a cleanly finalized error.
        let _ = self.inner.close();
        if (self.inner.close_failed() || self.inner.predicate_panicked())
            && let Some(transaction) = self.poison_target
        {
            transaction.poison();
        }
    }
}

impl<
    'a,
    K: Key + 'static,
    V: Value + 'static,
    F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool,
> Iterator for ExtractIf<'a, K, V, F>
{
    type Item = Result<(AccessGuard<'a, K>, AccessGuard<'a, V>)>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl<
    K: Key + 'static,
    V: Value + 'static,
    F: for<'f> FnMut(K::SelfType<'f>, V::SelfType<'f>) -> bool,
> DoubleEndedIterator for ExtractIf<'_, K, V, F>
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back()
    }
}

#[derive(Clone)]
pub struct Range<'a, K: Key + 'static, V: Value + 'static> {
    inner: BtreeCursorRange<K, V>,
    _transaction_guard: Arc<TransactionGuard>,
    // This lifetime is here so that `&` can be held on `Table` preventing concurrent mutation
    _lifetime: PhantomData<&'a ()>,
}

impl<K: Key + 'static, V: Value + 'static> Range<'_, K, V> {
    pub(super) fn new(inner: BtreeCursorRange<K, V>, guard: Arc<TransactionGuard>) -> Self {
        Self {
            inner,
            _transaction_guard: guard,
            _lifetime: PhantomData,
        }
    }
}

impl<'a, K: Key + 'static, V: Value + 'static> Iterator for Range<'a, K, V> {
    type Item = Result<(AccessGuard<'a, K>, AccessGuard<'a, V>)>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|x| {
            x.map(|entry| {
                let (page, key_range, value_range) = entry.into_raw();
                let key = AccessGuard::with_page(page.clone(), key_range);
                let value = AccessGuard::with_page(page, value_range);
                (key, value)
            })
        })
    }
}

impl<K: Key + 'static, V: Value + 'static> DoubleEndedIterator for Range<'_, K, V> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|x| {
            x.map(|entry| {
                let (page, key_range, value_range) = entry.into_raw();
                let key = AccessGuard::with_page(page.clone(), key_range);
                let value = AccessGuard::with_page(page, value_range);
                (key, value)
            })
        })
    }
}

/// An [`AccessGuard`] which also keeps the transaction alive
///
/// Returned by the reference-counted accessors of [`ReadOnlyTable`] and
/// [`crate::ReadOnlyMultimapTable`], such as [`ReadOnlyTable::get_owned()`]: in addition to
/// providing access to the data, it keeps the read transaction alive until it is dropped.
pub struct OwnedAccessGuard<V: Value + 'static> {
    // Declared before the transaction guard so the page reference is released before the
    // transaction is deallocated
    inner: AccessGuard<'static, V>,
    _transaction_guard: Arc<TransactionGuard>,
}

impl<V: Value + 'static> OwnedAccessGuard<V> {
    pub(crate) fn new(inner: AccessGuard<'static, V>, guard: Arc<TransactionGuard>) -> Self {
        Self {
            inner,
            _transaction_guard: guard,
        }
    }

    /// Access the stored value
    pub fn value(&self) -> V::SelfType<'_> {
        self.inner.value()
    }
}

/// A [`Range`] which also keeps the transaction alive
///
/// Returned by [`ReadOnlyTable::range_owned()`]. The iterator and the [`OwnedAccessGuard`]s it
/// yields keep the read transaction alive until they are dropped.
#[derive(Clone)]
pub struct OwnedRange<K: Key + 'static, V: Value + 'static> {
    inner: Range<'static, K, V>,
    transaction_guard: Arc<TransactionGuard>,
}

impl<K: Key + 'static, V: Value + 'static> OwnedRange<K, V> {
    pub(super) fn new(inner: Range<'static, K, V>, guard: Arc<TransactionGuard>) -> Self {
        Self {
            inner,
            transaction_guard: guard,
        }
    }
}

impl<K: Key + 'static, V: Value + 'static> Iterator for OwnedRange<K, V> {
    type Item = Result<(OwnedAccessGuard<K>, OwnedAccessGuard<V>)>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|x| {
            x.map(|(key, value)| {
                (
                    OwnedAccessGuard::new(key, self.transaction_guard.clone()),
                    OwnedAccessGuard::new(value, self.transaction_guard.clone()),
                )
            })
        })
    }
}

impl<K: Key + 'static, V: Value + 'static> DoubleEndedIterator for OwnedRange<K, V> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|x| {
            x.map(|(key, value)| {
                (
                    OwnedAccessGuard::new(key, self.transaction_guard.clone()),
                    OwnedAccessGuard::new(value, self.transaction_guard.clone()),
                )
            })
        })
    }
}

/// A view into a single entry in a [`Table`], which may either be vacant or occupied.
///
/// This `enum` is constructed from the [`entry`] method on [`Table`], and mirrors
/// [`std::collections::btree_map::Entry`] as closely as the redb data model allows.
///
/// Unlike the in-memory `BTreeMap`, redb values are stored serialized, so methods that
/// produce a "reference to the value" return an [`AccessGuardMut`] instead of `&mut V`.
///
/// [`entry`]: Table::entry
pub enum Entry<'a, K: Key + 'static, V: Value + 'static> {
    /// An occupied entry.
    Occupied(OccupiedEntry<'a, K, V>),
    /// A vacant entry.
    Vacant(VacantEntry<'a, K, V>),
}

impl<'a, K: Key + 'static, V: Value + 'static> Entry<'a, K, V> {
    /// Returns a view of this entry's key.
    pub fn key(&self) -> &K::SelfType<'a> {
        match self {
            Entry::Occupied(entry) => entry.key(),
            Entry::Vacant(entry) => entry.key(),
        }
    }

    /// Ensures a value is in the entry by inserting the provided `default` if empty,
    /// and returns a mutable accessor to the value in the entry.
    pub fn or_insert<'v>(
        self,
        default: impl Borrow<V::SelfType<'v>>,
    ) -> Result<AccessGuardMut<'a, V>> {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(default),
        }
    }

    /// Ensures a value is in the entry by inserting the result of `default` if empty,
    /// and returns a mutable accessor to the value in the entry.
    ///
    /// Unlike [`or_insert`](Self::or_insert), the default value is only computed if the
    /// entry is vacant.
    pub fn or_insert_with<'v, F, B>(self, default: F) -> Result<AccessGuardMut<'a, V>>
    where
        F: FnOnce() -> B,
        B: Borrow<V::SelfType<'v>>,
    {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => entry.insert(default()),
        }
    }

    /// Ensures a value is in the entry by inserting, if empty, the result of the `default`
    /// function, which is given a view of the key.
    pub fn or_insert_with_key<'v, F, B>(self, default: F) -> Result<AccessGuardMut<'a, V>>
    where
        F: FnOnce(&K::SelfType<'a>) -> B,
        B: Borrow<V::SelfType<'v>>,
    {
        match self {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => {
                let value = default(&entry.key);
                entry.insert(value)
            }
        }
    }

    /// Provides in-place mutable access to an occupied entry before any potential inserts
    /// into the table.
    ///
    /// The closure receives an [`AccessGuardMut`] and may replace the stored value via
    /// [`AccessGuardMut::insert`]. Any errors returned by the closure are propagated.
    pub fn and_modify<F>(self, f: F) -> Result<Self>
    where
        F: FnOnce(&mut AccessGuardMut<'_, V>) -> Result<()>,
    {
        match self {
            Entry::Occupied(mut entry) => {
                {
                    let mut guard = entry.get_mut()?;
                    f(&mut guard)?;
                }
                Ok(Entry::Occupied(entry))
            }
            Entry::Vacant(entry) => Ok(Entry::Vacant(entry)),
        }
    }
}

/// A view into an occupied entry in a [`Table`]. It is part of the [`Entry`] enum.
pub struct OccupiedEntry<'a, K: Key + 'static, V: Value + 'static> {
    tree: &'a mut BtreeMut<K, V>,
    key: K::SelfType<'a>,
}

impl<'a, K: Key + 'static, V: Value + 'static> OccupiedEntry<'a, K, V> {
    /// Returns a view of this entry's key.
    pub fn key(&self) -> &K::SelfType<'a> {
        &self.key
    }

    /// Returns a view of this entry's value.
    pub fn get(&self) -> Result<AccessGuard<'_, V>> {
        self.tree.get(&self.key)?.ok_or_else(|| {
            StorageError::Corrupted(
                "entry for key disappeared while OccupiedEntry was live".to_string(),
            )
        })
    }

    /// Returns a mutable accessor to the value in the entry.
    pub fn get_mut(&mut self) -> Result<AccessGuardMut<'_, V>> {
        self.tree.get_mut(&self.key)?.ok_or_else(|| {
            StorageError::Corrupted(
                "entry for key disappeared while OccupiedEntry was live".to_string(),
            )
        })
    }

    /// Converts the entry into a mutable accessor to the value in the entry with a lifetime
    /// bound to the table itself.
    pub fn into_mut(self) -> Result<AccessGuardMut<'a, V>> {
        self.tree.get_mut(&self.key)?.ok_or_else(|| {
            StorageError::Corrupted(
                "entry for key disappeared while OccupiedEntry was live".to_string(),
            )
        })
    }

    /// Replaces the value of the entry with the supplied value, and returns the old value.
    pub fn insert<'v>(
        &mut self,
        value: impl Borrow<V::SelfType<'v>>,
    ) -> Result<AccessGuard<'_, V>> {
        let value_len = V::as_bytes(value.borrow()).as_ref().len();
        if value_len > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(value_len));
        }
        let key_len = K::as_bytes(&self.key).as_ref().len();
        if value_len + key_len > MAX_PAIR_LENGTH {
            return Err(StorageError::ValueTooLarge(value_len + key_len));
        }
        self.tree.insert(&self.key, value.borrow())?.ok_or_else(|| {
            StorageError::Corrupted(
                "entry for key disappeared while OccupiedEntry was live".to_string(),
            )
        })
    }

    /// Takes the value out of the entry, and returns it.
    pub fn remove(self) -> Result<AccessGuard<'a, V>> {
        self.tree.remove(&self.key)?.ok_or_else(|| {
            StorageError::Corrupted(
                "entry for key disappeared while OccupiedEntry was live".to_string(),
            )
        })
    }

    /// Takes the entry out of the table, returning the key and the value.
    pub fn remove_entry(self) -> Result<(K::SelfType<'a>, AccessGuard<'a, V>)> {
        let OccupiedEntry { tree, key } = self;
        let value = tree.remove(&key)?.ok_or_else(|| {
            StorageError::Corrupted(
                "entry for key disappeared while OccupiedEntry was live".to_string(),
            )
        })?;
        Ok((key, value))
    }
}

/// A view into a vacant entry in a [`Table`]. It is part of the [`Entry`] enum.
pub struct VacantEntry<'a, K: Key + 'static, V: Value + 'static> {
    tree: &'a mut BtreeMut<K, V>,
    key: K::SelfType<'a>,
}

impl<'a, K: Key + 'static, V: Value + 'static> VacantEntry<'a, K, V> {
    /// Returns a view of this entry's key.
    pub fn key(&self) -> &K::SelfType<'a> {
        &self.key
    }

    /// Consumes the entry and returns the key that was used to construct it.
    pub fn into_key(self) -> K::SelfType<'a> {
        self.key
    }

    /// Inserts `value` with the entry's key and returns a mutable accessor to it.
    pub fn insert<'v>(self, value: impl Borrow<V::SelfType<'v>>) -> Result<AccessGuardMut<'a, V>> {
        let value_len = V::as_bytes(value.borrow()).as_ref().len();
        if value_len > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(value_len));
        }
        let key_len = K::as_bytes(&self.key).as_ref().len();
        if value_len + key_len > MAX_PAIR_LENGTH {
            return Err(StorageError::ValueTooLarge(value_len + key_len));
        }
        self.tree.insert(&self.key, value.borrow())?;
        self.tree.get_mut(&self.key)?.ok_or_else(|| {
            StorageError::Corrupted(
                "inserted entry not found after VacantEntry::insert".to_string(),
            )
        })
    }
}

#[cfg(feature = "experimental-api-5")]
pub(crate) fn bound_to_bytes<'a, K: Key + 'a, KR: Borrow<K::SelfType<'a>>>(
    bound: &Bound<KR>,
) -> Bound<Vec<u8>> {
    match bound {
        Bound::Included(key) => Bound::Included(K::as_bytes(key.borrow()).as_ref().to_vec()),
        Bound::Excluded(key) => Bound::Excluded(K::as_bytes(key.borrow()).as_ref().to_vec()),
        Bound::Unbounded => Bound::Unbounded,
    }
}

/// A read-only cursor over a table, pointing at a gap between two entries.
///
/// Cursors are constructed with [`ReadableTable::lower_bound`] and
/// [`ReadableTable::upper_bound`], and mirror the nightly
/// [`std::collections::btree_map::Cursor`] as closely as the redb data model
/// allows: values are stored serialized, so the entries around the gap are
/// returned as [`AccessGuard`]s instead of references, and every operation
/// can report a storage error.
///
/// The cursor's methods are behind the `experimental_cursor` feature flag,
/// separately from its constructors, so that the constructors' signatures
/// can stabilize first.
#[cfg(feature = "experimental-api-5")]
pub struct Cursor<'a, K: Key + 'static, V: Value + 'static> {
    // Only the cursor's own methods read the position; without them the
    // constructors still store it, ready for the methods' flag to be enabled.
    #[cfg_attr(not(feature = "experimental_cursor"), allow(dead_code))]
    inner: BtreeCursor<K, V>,
    // The cursor owns page handles, so it must keep the transaction registered for as long as it
    // is alive. The lifetime below cannot do that job: the cursor has no `Drop` impl, so the
    // borrow it represents ends at the cursor's last use, leaving the table free to be dropped
    // and the transaction free to be closed while the cursor still holds its pages
    _transaction_guard: Arc<TransactionGuard>,
    // This lifetime is here so that `&` can be held on `Table` preventing concurrent mutation.
    // It also bounds the guards the cursor yields, which is why there is no `'static` cursor:
    // such a guard could outlive both the cursor and the transaction, letting a writer reclaim
    // the pages it points at
    _lifetime: PhantomData<&'a ()>,
}

#[cfg(feature = "experimental-api-5")]
impl<K: Key + 'static, V: Value + 'static> Cursor<'_, K, V> {
    pub(crate) fn new(inner: BtreeCursor<K, V>, guard: Arc<TransactionGuard>) -> Self {
        Self {
            inner,
            _transaction_guard: guard,
            _lifetime: PhantomData,
        }
    }
}

#[cfg(feature = "experimental_cursor")]
impl<'a, K: Key + 'static, V: Value + 'static> Cursor<'a, K, V> {
    /// Returns the entry after the cursor's gap without moving the cursor.
    ///
    /// Returns `None` if the gap is at the end of the table.
    #[allow(clippy::type_complexity)]
    pub fn peek_next(&mut self) -> Result<Option<(AccessGuard<'a, K>, AccessGuard<'a, V>)>> {
        self.inner.peek_next()
    }

    /// Returns the entry before the cursor's gap without moving the cursor.
    ///
    /// Returns `None` if the gap is at the start of the table.
    #[allow(clippy::type_complexity)]
    pub fn peek_prev(&mut self) -> Result<Option<(AccessGuard<'a, K>, AccessGuard<'a, V>)>> {
        self.inner.peek_prev()
    }

    /// Moves the cursor past the entry after the gap, returning that entry.
    ///
    /// Returns `None`, and does not move, if the gap is at the end of the
    /// table.
    ///
    /// This is analogous to the nightly
    /// [`std::collections::btree_map::Cursor::next`]. The cursor is not an
    /// [`Iterator`], since every step can report a storage error; use
    /// [`ReadableTable::range`] for iteration.
    #[allow(clippy::should_implement_trait, clippy::type_complexity)]
    pub fn next(&mut self) -> Result<Option<(AccessGuard<'a, K>, AccessGuard<'a, V>)>> {
        self.inner.next()
    }

    /// Moves the cursor before the entry preceding the gap, returning that
    /// entry.
    ///
    /// Returns `None`, and does not move, if the gap is at the start of the
    /// table.
    ///
    /// This is analogous to the nightly
    /// [`std::collections::btree_map::Cursor::prev`].
    #[allow(clippy::type_complexity)]
    pub fn prev(&mut self) -> Result<Option<(AccessGuard<'a, K>, AccessGuard<'a, V>)>> {
        self.inner.prev()
    }
}

/// A cursor over a [`Table`], pointing at a gap between two entries, with
/// support for inserting new entries into that gap and removing the entries
/// around it.
///
/// Cursors are constructed with [`Table::lower_bound_mut`] and
/// [`Table::upper_bound_mut`], and mirror the nightly
/// [`std::collections::btree_map::CursorMut`] as closely as the redb data
/// model allows: values are stored serialized, so inspecting the entries
/// around the gap returns [`AccessGuard`]s instead of references, and every
/// operation can report a storage error.
///
/// Call [`close`](Self::close) when finished with the cursor: errors from
/// applying its inserts can be deferred, and only `close` reports them.
///
/// The cursor mutably borrows the [`Table`]: the table cannot be used while
/// a cursor into it exists.
#[cfg(feature = "experimental_cursor")]
pub struct CursorMut<'a, K: Key + 'static, V: Value + 'static> {
    inner: BtreeCursorMut<'a, K, V>,
    transaction: &'a WriteTransaction,
    // An I/O error leaves the cursor position unreliable, so later operations
    // re-raise instead of continuing. Pending inserts are still flushed (or
    // the transaction poisoned) on close: an error never latches while both
    // pending inserts and a damaged position exist.
    errored: bool,
    closed: bool,
}

#[cfg(feature = "experimental_cursor")]
impl<'a, K: Key + 'static, V: Value + 'static> CursorMut<'a, K, V> {
    pub(crate) fn new(inner: BtreeCursorMut<'a, K, V>, transaction: &'a WriteTransaction) -> Self {
        Self {
            inner,
            transaction,
            errored: false,
            closed: false,
        }
    }

    /// Returns the entry after the cursor's gap without moving the cursor.
    ///
    /// Returns `None` if the gap is at the end of the table.
    #[allow(clippy::type_complexity)]
    pub fn peek_next(&mut self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.check_usable()?;
        match self.inner.peek_next() {
            Ok(entry) => Ok(entry),
            Err(err) => {
                // Peeking never consumes pending inserts, so unlike a failed
                // splice this cannot lose reported inserts; the position is
                // merely unreliable.
                self.errored = true;
                Err(err)
            }
        }
    }

    /// Returns the entry before the cursor's gap without moving the cursor.
    ///
    /// Returns `None` if the gap is at the start of the table.
    #[allow(clippy::type_complexity)]
    pub fn peek_prev(&mut self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.check_usable()?;
        match self.inner.peek_prev() {
            Ok(entry) => Ok(entry),
            Err(err) => {
                self.errored = true;
                Err(err)
            }
        }
    }

    /// Moves the cursor past the entry after the gap, returning that entry.
    ///
    /// Returns `None`, and does not move, if the gap is at the end of the
    /// table. Any pending inserts are applied first: moving the cursor
    /// closes the buffered run.
    ///
    /// This is analogous to the nightly
    /// [`std::collections::btree_map::CursorMut::next`]. The cursor is not
    /// an [`Iterator`], since every step can report a storage error; use
    /// [`ReadableTable::range`] for iteration.
    #[allow(clippy::should_implement_trait, clippy::type_complexity)]
    pub fn next(&mut self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.check_usable()?;
        // Applied separately from the move so that a splice failure, which
        // can poison, is told apart from a failed move, which only leaves
        // the position unreliable.
        if let Err(err) = self.inner.apply_pending_inserts() {
            return Err(self.latch_error(err));
        }
        match self.inner.next() {
            Ok(entry) => Ok(entry),
            Err(err) => {
                self.errored = true;
                Err(err)
            }
        }
    }

    /// Moves the cursor before the entry preceding the gap, returning that
    /// entry.
    ///
    /// Returns `None`, and does not move, if the gap is at the start of the
    /// table. Any pending inserts are applied first: moving the cursor
    /// closes the buffered run.
    ///
    /// This is analogous to the nightly
    /// [`std::collections::btree_map::CursorMut::prev`].
    #[allow(clippy::type_complexity)]
    pub fn prev(&mut self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.check_usable()?;
        // Applied separately from the move so that a splice failure, which
        // can poison, is told apart from a failed move, which only leaves
        // the position unreliable.
        if let Err(err) = self.inner.apply_pending_inserts() {
            return Err(self.latch_error(err));
        }
        match self.inner.prev() {
            Ok(entry) => Ok(entry),
            Err(err) => {
                self.errored = true;
                Err(err)
            }
        }
    }

    /// Inserts a new entry into the gap that the cursor is pointing at. After
    /// the insertion, the cursor points at the gap after the newly inserted
    /// entry.
    ///
    /// If the key does not sort strictly greater than the entry before the
    /// gap and strictly smaller than the entry after it,
    /// [`StorageError::UnorderedKey`] is returned and nothing is changed.
    /// Unlike [`Table::insert`], an existing key is never overwritten:
    /// inserting a key equal to either neighbor is unordered.
    ///
    /// Runs of calls in one direction are buffered together; switching
    /// between `insert_before` and [`insert_after`](Self::insert_after)
    /// applies the other direction's pending inserts first.
    ///
    /// This is analogous to the nightly
    /// [`std::collections::btree_map::CursorMut::insert_before`].
    pub fn insert_before<'k, 'v>(
        &mut self,
        key: impl Borrow<K::SelfType<'k>>,
        value: impl Borrow<V::SelfType<'v>>,
    ) -> Result<()> {
        self.check_usable()?;
        let key_bytes = K::as_bytes(key.borrow());
        let value_bytes = V::as_bytes(value.borrow());
        Self::check_lengths(key_bytes.as_ref(), value_bytes.as_ref())?;
        match self
            .inner
            .insert_before(key_bytes.as_ref(), value_bytes.as_ref())
        {
            Ok(true) => Ok(()),
            Ok(false) => Err(StorageError::UnorderedKey),
            Err(err) => Err(self.latch_error(err)),
        }
    }

    /// Inserts a new entry into the gap that the cursor is pointing at. After
    /// the insertion, the cursor points at the gap before the newly inserted
    /// entry.
    ///
    /// If the key does not sort strictly greater than the entry before the
    /// gap and strictly smaller than the entry after it,
    /// [`StorageError::UnorderedKey`] is returned and nothing is changed.
    /// Unlike [`Table::insert`], an existing key is never overwritten:
    /// inserting a key equal to either neighbor is unordered.
    ///
    /// Runs of calls in one direction are buffered together; switching
    /// between `insert_after` and [`insert_before`](Self::insert_before)
    /// applies the other direction's pending inserts first.
    ///
    /// This is analogous to the nightly
    /// [`std::collections::btree_map::CursorMut::insert_after`].
    pub fn insert_after<'k, 'v>(
        &mut self,
        key: impl Borrow<K::SelfType<'k>>,
        value: impl Borrow<V::SelfType<'v>>,
    ) -> Result<()> {
        self.check_usable()?;
        let key_bytes = K::as_bytes(key.borrow());
        let value_bytes = V::as_bytes(value.borrow());
        Self::check_lengths(key_bytes.as_ref(), value_bytes.as_ref())?;
        match self
            .inner
            .insert_after(key_bytes.as_ref(), value_bytes.as_ref())
        {
            Ok(true) => Ok(()),
            Ok(false) => Err(StorageError::UnorderedKey),
            Err(err) => Err(self.latch_error(err)),
        }
    }

    /// Removes the entry after the cursor's gap, returning it.
    ///
    /// The cursor does not move: the gap ends up between the removed entry's
    /// old neighbors. Returns `None`, and removes nothing, if the gap is at
    /// the end of the table. Any pending inserts are applied first, so an
    /// entry just inserted through the cursor is removed like an entry the
    /// table already had.
    ///
    /// This is analogous to the nightly
    /// [`std::collections::btree_map::CursorMut::remove_next`].
    #[allow(clippy::type_complexity)]
    pub fn remove_next(&mut self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.check_usable()?;
        // Applied separately from the removal so that a splice failure,
        // which can poison, is told apart from a failed removal, which only
        // leaves the position unreliable.
        if let Err(err) = self.inner.apply_pending_inserts() {
            return Err(self.latch_error(err));
        }
        match self.inner.remove_next() {
            Ok(entry) => Ok(entry),
            Err(err) => {
                self.errored = true;
                Err(err)
            }
        }
    }

    /// Removes the entry before the cursor's gap, returning it.
    ///
    /// The cursor does not move: the gap ends up between the removed entry's
    /// old neighbors. Returns `None`, and removes nothing, if the gap is at
    /// the start of the table. Any pending inserts are applied first, so an
    /// entry just inserted through the cursor is removed like an entry the
    /// table already had.
    ///
    /// This is analogous to the nightly
    /// [`std::collections::btree_map::CursorMut::remove_prev`].
    #[allow(clippy::type_complexity)]
    pub fn remove_prev(&mut self) -> Result<Option<(AccessGuard<'_, K>, AccessGuard<'_, V>)>> {
        self.check_usable()?;
        // Applied separately from the removal so that a splice failure,
        // which can poison, is told apart from a failed removal, which only
        // leaves the position unreliable.
        if let Err(err) = self.inner.apply_pending_inserts() {
            return Err(self.latch_error(err));
        }
        match self.inner.remove_prev() {
            Ok(entry) => Ok(entry),
            Err(err) => {
                self.errored = true;
                Err(err)
            }
        }
    }

    fn check_lengths(key: &[u8], value: &[u8]) -> Result {
        if value.len() > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(value.len()));
        }
        if key.len() > MAX_VALUE_LENGTH {
            return Err(StorageError::ValueTooLarge(key.len()));
        }
        if value.len() + key.len() > MAX_PAIR_LENGTH {
            return Err(StorageError::ValueTooLarge(value.len() + key.len()));
        }
        Ok(())
    }

    /// Closes the cursor, applying any of its inserts that have not yet
    /// reached the table.
    ///
    /// `Ok` means every insert this cursor accepted is in the table. Dropping
    /// the cursor closes it too, but cannot report errors; if applying the
    /// inserts fails then, the write transaction is poisoned and
    /// [`crate::WriteTransaction::commit`] will return
    /// [`crate::CommitError::TransactionPoisoned`], so the loss cannot be
    /// committed.
    pub fn close(mut self) -> Result {
        self.closed = true;
        self.finish()
    }

    fn check_usable(&self) -> Result {
        if self.errored {
            return Err(StorageError::PreviousIo);
        }
        Ok(())
    }

    fn latch_error(&mut self, err: StorageError) -> StorageError {
        self.errored = true;
        if self.inner.poisoned() {
            // Inserts already reported as applied were lost; the transaction
            // must not commit without them.
            self.transaction.poison();
        }
        err
    }

    fn finish(&mut self) -> Result {
        let result = self.inner.finish();
        if result.is_err() || self.inner.poisoned() {
            self.transaction.poison();
        }
        result
    }
}

#[cfg(feature = "experimental_cursor")]
impl<K: Key + 'static, V: Value + 'static> Drop for CursorMut<'_, K, V> {
    fn drop(&mut self) {
        if self.closed {
            return;
        }
        // Drop cannot surface a splice failure; finish() poisons the
        // transaction instead, so the loss cannot be committed.
        let _ = self.finish();
    }
}