libdictenstein 4.0.0-rc.1

High-performance dictionary data structures (trie, DAWG, double-array trie, suffix automaton, lock-free durable persistent ART) behind one trait API; pairs with liblevenshtein for fuzzy matching
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
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
//! Stable C ABI for libdictenstein-owned dictionaries and CRUD.

#[cfg(feature = "persistent-artrie")]
use crate::bindings::PersistentARTrieBinding;
use crate::bindings::{
    BindingError, BindingUnitDomain, DoubleArrayTrieBinding, DynamicDawgBinding,
    OwnedDictionaryResource, ScdawgBinding,
};
use std::cell::RefCell;
use std::ffi::{c_char, CString};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::ptr;
use vinary_tree_interop::{
    dictionary_entries_info_flags, VtDictionaryEntriesCursor, VtDictionaryEntriesInfo,
    VtDictionaryEntriesVTable, VtDictionaryEntry, VtDictionaryEntryBatchLimits,
    VtDictionaryEntryBatchView, VtDictionaryEntryOrder, VtResource, VtStatus, VtUnitDomain,
    VtValueDomain, VT_DICTIONARY_ENTRIES_INTERFACE_ID, VT_DICTIONARY_ENTRIES_INTERFACE_VERSION,
};

/// ABI version for the libdictenstein project API.
pub const LDICT_ABI_VERSION: u32 = 1;
/// Additive project API revision.
pub const LDICT_API_REVISION: u32 = 5;

/// DynamicDAWG backend identifier.
pub const LDICT_KIND_DYNAMIC_DAWG: u32 = 1;
/// DoubleArrayTrie backend identifier.
pub const LDICT_KIND_DOUBLE_ARRAY_TRIE: u32 = 2;
/// SCDAWG backend identifier.
pub const LDICT_KIND_SCDAWG: u32 = 3;
/// Persistent ARTrie backend identifier.
pub const LDICT_KIND_PERSISTENT_ARTRIE: u32 = 4;
/// Persistent term/index vocabulary ARTrie identifier.
pub const LDICT_KIND_PERSISTENT_VOCAB_ARTRIE: u32 = 5;

/// Exact membership and value lookup capability.
pub const LDICT_CAP_READ: u64 = 1 << 0;
/// Insert/update capability.
pub const LDICT_CAP_INSERT: u64 = 1 << 1;
/// Removal capability.
pub const LDICT_CAP_REMOVE: u64 = 1 << 2;
/// Clear capability.
pub const LDICT_CAP_CLEAR: u64 = 1 << 3;
/// Structural compaction capability.
pub const LDICT_CAP_COMPACT: u64 = 1 << 4;
/// Substring search capability.
pub const LDICT_CAP_SUBSTRING: u64 = 1 << 5;
/// Durable checkpoint capability.
pub const LDICT_CAP_CHECKPOINT: u64 = 1 << 6;

/// Status returned by libdictenstein C functions.
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LdictStatus {
    /// Operation completed successfully.
    Ok = 0,
    /// An iterator or paged operation is exhausted.
    End = 1,
    /// An argument was invalid.
    InvalidArgument = 2,
    /// UTF-8 input was malformed.
    InvalidUtf8 = 3,
    /// A required pointer was null.
    NullPointer = 4,
    /// A panic was caught at the ABI boundary.
    Panic = 5,
    /// The operation is not defined for this backend/domain.
    Unsupported = 6,
    /// A persistent operation failed.
    IoError = 7,
    /// A handle is already closed.
    Closed = 8,
    /// The supplied term domain does not match the dictionary.
    DomainMismatch = 9,
    /// A configured resource bound was exceeded.
    LimitExceeded = 10,
    /// The underlying resource provider failed without a more specific status.
    ProviderError = 11,
    /// A cursor operation requires the current borrowed batch to be released.
    BatchInUse = 12,
}

/// Optional u64 used by CRUD requests and responses.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct LdictOptionalU64 {
    /// Value payload, meaningful when `has_value == 1`.
    pub value: u64,
    /// Zero or one.
    pub has_value: u8,
    /// Reserved; must be zero.
    pub reserved: [u8; 7],
}

impl LdictOptionalU64 {
    fn decode(self) -> Result<Option<u64>, (LdictStatus, String)> {
        if self.reserved != [0; 7] {
            return Err((
                LdictStatus::InvalidArgument,
                "reserved bytes must be zero".into(),
            ));
        }
        match self.has_value {
            0 => Ok(None),
            1 => Ok(Some(self.value)),
            _ => Err((
                LdictStatus::InvalidArgument,
                "has_value must be zero or one".into(),
            )),
        }
    }

    fn encode(value: Option<u64>) -> Self {
        Self {
            value: value.unwrap_or_default(),
            has_value: u8::from(value.is_some()),
            reserved: [0; 7],
        }
    }
}

/// One text/byte term in a batched mutation.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct LdictTextEntry {
    /// UTF-8 or raw-byte term data.
    pub data: *const u8,
    /// Number of bytes at `data`.
    pub len: usize,
    /// Optional mapped value.
    pub value: LdictOptionalU64,
}

/// One u64-token term in a batched mutation.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct LdictU64Entry {
    /// Token data.
    pub data: *const u64,
    /// Number of tokens at `data`.
    pub len: usize,
    /// Optional mapped value.
    pub value: LdictOptionalU64,
}

/// One streamed entry descriptor into a leased batch's parallel arenas.
pub type LdictEntry = VtDictionaryEntry;

/// Hard upper bounds for one streamed entry batch.
pub type LdictEntryBatchLimits = VtDictionaryEntryBatchLimits;

/// Borrowed cursor-owned entry batch, valid until its generation is released.
pub type LdictEntryBatch = VtDictionaryEntryBatchView;

/// Immutable snapshot metadata captured when an entry cursor is opened.
pub type LdictEntriesInfo = VtDictionaryEntriesInfo;

/// Callback used by [`ldict_entry_cursor_reduce`].
///
/// The raw return value must encode one published [`LdictStatus`] discriminant.
pub type LdictEntryReducer = unsafe extern "C" fn(
    reducer_context: *mut std::ffi::c_void,
    batch: *const LdictEntryBatch,
) -> u32;

/// Opaque owned cursor over one immutable dictionary revision.
pub struct LdictEntryCursor {
    raw: VtDictionaryEntriesCursor,
    vtable: *const VtDictionaryEntriesVTable,
    leased_generation: Option<u64>,
}

/// Opaque mutable dictionary handle.
pub struct LdictDictionary {
    binding: LdictBinding,
    resource: OwnedDictionaryResource,
}

enum LdictBinding {
    Dynamic(DynamicDawgBinding),
    DoubleArray(DoubleArrayTrieBinding),
    Scdawg(ScdawgBinding),
    #[cfg(feature = "persistent-artrie")]
    Persistent(PersistentARTrieBinding),
}

impl LdictBinding {
    fn kind(&self) -> u32 {
        match self {
            Self::Dynamic(_) => LDICT_KIND_DYNAMIC_DAWG,
            Self::DoubleArray(_) => LDICT_KIND_DOUBLE_ARRAY_TRIE,
            Self::Scdawg(_) => LDICT_KIND_SCDAWG,
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => {
                if binding.is_vocab() {
                    LDICT_KIND_PERSISTENT_VOCAB_ARTRIE
                } else {
                    LDICT_KIND_PERSISTENT_ARTRIE
                }
            }
        }
    }

    fn capabilities(&self) -> u64 {
        match self {
            Self::Dynamic(_) => {
                LDICT_CAP_READ
                    | LDICT_CAP_INSERT
                    | LDICT_CAP_REMOVE
                    | LDICT_CAP_CLEAR
                    | LDICT_CAP_COMPACT
            }
            Self::DoubleArray(_) => LDICT_CAP_READ,
            Self::Scdawg(_) => LDICT_CAP_READ | LDICT_CAP_INSERT | LDICT_CAP_SUBSTRING,
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => {
                let mut capabilities = LDICT_CAP_READ | LDICT_CAP_INSERT | LDICT_CAP_CHECKPOINT;
                if !binding.is_vocab() {
                    capabilities |= LDICT_CAP_REMOVE;
                }
                capabilities
            }
        }
    }

    fn len(&self) -> usize {
        match self {
            Self::Dynamic(binding) => binding.len(),
            Self::DoubleArray(binding) => binding.len(),
            Self::Scdawg(binding) => binding.len(),
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => binding.len(),
        }
    }

    fn resource(&self) -> OwnedDictionaryResource {
        match self {
            Self::Dynamic(binding) => binding.resource(),
            Self::DoubleArray(binding) => binding.resource(),
            Self::Scdawg(binding) => binding.resource(),
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => binding.resource(),
        }
    }

    fn clear(&self) -> Result<(), BindingError> {
        match self {
            Self::Dynamic(binding) => {
                binding.clear();
                Ok(())
            }
            _ => Err(BindingError::Unsupported),
        }
    }

    fn compact(&self) -> Result<usize, BindingError> {
        match self {
            Self::Dynamic(binding) => Ok(binding.compact()),
            _ => Err(BindingError::Unsupported),
        }
    }

    fn insert_text(&self, term: &[u8], value: Option<u64>) -> Result<bool, BindingError> {
        match self {
            Self::Dynamic(binding) => binding.insert_text(term, value),
            Self::DoubleArray(_) => Err(BindingError::Unsupported),
            Self::Scdawg(binding) => {
                let term = std::str::from_utf8(term).map_err(|_| BindingError::InvalidUtf8)?;
                Ok(binding.insert(term, value))
            }
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => binding.insert_text(term, value),
        }
    }

    fn remove_text(&self, term: &[u8]) -> Result<bool, BindingError> {
        match self {
            Self::Dynamic(binding) => binding.remove_text(term),
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => binding.remove_text(term),
            _ => Err(BindingError::Unsupported),
        }
    }

    fn contains_text(&self, term: &[u8]) -> Result<bool, BindingError> {
        match self {
            Self::Dynamic(binding) => binding.contains_text(term),
            Self::DoubleArray(binding) => {
                let term = std::str::from_utf8(term).map_err(|_| BindingError::InvalidUtf8)?;
                Ok(binding.contains(term))
            }
            Self::Scdawg(binding) => {
                let term = std::str::from_utf8(term).map_err(|_| BindingError::InvalidUtf8)?;
                Ok(binding.contains(term))
            }
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => binding.contains_text(term),
        }
    }

    fn value_text(&self, term: &[u8]) -> Result<Option<Option<u64>>, BindingError> {
        match self {
            Self::Dynamic(binding) => binding.value_text(term),
            Self::DoubleArray(binding) => {
                let term = std::str::from_utf8(term).map_err(|_| BindingError::InvalidUtf8)?;
                Ok(binding.value(term))
            }
            Self::Scdawg(binding) => {
                let term = std::str::from_utf8(term).map_err(|_| BindingError::InvalidUtf8)?;
                Ok(binding.value(term))
            }
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => binding.value_text(term),
        }
    }

    fn insert_u64(&self, term: &[u64], value: Option<u64>) -> Result<bool, BindingError> {
        match self {
            Self::Dynamic(binding) => binding.insert_u64(term, value),
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => binding.insert_u64(term, value),
            _ => Err(BindingError::DomainMismatch),
        }
    }

    fn remove_u64(&self, term: &[u64]) -> Result<bool, BindingError> {
        match self {
            Self::Dynamic(binding) => binding.remove_u64(term),
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => binding.remove_u64(term),
            _ => Err(BindingError::DomainMismatch),
        }
    }

    fn contains_u64(&self, term: &[u64]) -> Result<bool, BindingError> {
        match self {
            Self::Dynamic(binding) => binding.contains_u64(term),
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => binding.contains_u64(term),
            _ => Err(BindingError::DomainMismatch),
        }
    }

    fn value_u64(&self, term: &[u64]) -> Result<Option<Option<u64>>, BindingError> {
        match self {
            Self::Dynamic(binding) => binding.value_u64(term),
            #[cfg(feature = "persistent-artrie")]
            Self::Persistent(binding) => binding.value_u64(term),
            _ => Err(BindingError::DomainMismatch),
        }
    }

    fn contains_substring(&self, pattern: &str) -> Result<bool, BindingError> {
        match self {
            Self::Scdawg(binding) => Ok(binding.contains_substring(pattern)),
            _ => Err(BindingError::Unsupported),
        }
    }

    fn substring_frequency(&self, pattern: &str) -> Result<usize, BindingError> {
        match self {
            Self::Scdawg(binding) => Ok(binding.frequency(pattern)),
            _ => Err(BindingError::Unsupported),
        }
    }

    #[cfg(feature = "persistent-artrie")]
    fn checkpoint(&self) -> Result<(), BindingError> {
        match self {
            Self::Persistent(binding) => binding.checkpoint(),
            _ => Err(BindingError::Unsupported),
        }
    }

    #[cfg(feature = "persistent-artrie")]
    fn vocab_term(&self, index: u64) -> Result<Option<String>, BindingError> {
        match self {
            Self::Persistent(binding) => binding.vocab_term(index),
            _ => Err(BindingError::Unsupported),
        }
    }
}

thread_local! {
    static LAST_ERROR: RefCell<CString> = RefCell::new(CString::default());
}

fn set_error(message: impl AsRef<str>) {
    let message = message.as_ref().replace('\0', "\\0");
    LAST_ERROR.with(|slot| *slot.borrow_mut() = CString::new(message).unwrap_or_default());
}

fn boundary(operation: impl FnOnce() -> Result<LdictStatus, (LdictStatus, String)>) -> LdictStatus {
    match catch_unwind(AssertUnwindSafe(operation)) {
        Ok(Ok(status)) => {
            if matches!(status, LdictStatus::Ok | LdictStatus::End) {
                set_error("");
            }
            status
        }
        Ok(Err((status, message))) => {
            set_error(message);
            status
        }
        Err(payload) => {
            let message = payload
                .downcast_ref::<&str>()
                .copied()
                .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
                .unwrap_or("panic in libdictenstein");
            set_error(message);
            LdictStatus::Panic
        }
    }
}

fn binding<T>(result: Result<T, BindingError>) -> Result<T, (LdictStatus, String)> {
    result.map_err(|error| {
        let status = match error {
            BindingError::DomainMismatch => LdictStatus::DomainMismatch,
            BindingError::InvalidUtf8 => LdictStatus::InvalidUtf8,
            BindingError::Unsupported => LdictStatus::Unsupported,
            BindingError::Io(_) => LdictStatus::IoError,
        };
        (status, error.to_string())
    })
}

unsafe fn slice<'a, T>(
    data: *const T,
    len: usize,
    name: &str,
) -> Result<&'a [T], (LdictStatus, String)> {
    if len == 0 {
        return Ok(&[]);
    }
    if data.is_null() {
        return Err((LdictStatus::NullPointer, format!("{name} is null")));
    }
    Ok(std::slice::from_raw_parts(data, len))
}

fn domain(value: u32) -> Result<BindingUnitDomain, (LdictStatus, String)> {
    match value {
        1 => Ok(BindingUnitDomain::Byte),
        2 => Ok(BindingUnitDomain::UnicodeScalar),
        3 => Ok(BindingUnitDomain::U64),
        _ => Err((
            LdictStatus::InvalidArgument,
            format!("unknown dictionary unit domain {value}"),
        )),
    }
}

fn ldict_status_from_raw(raw: u32) -> Option<LdictStatus> {
    match raw {
        0 => Some(LdictStatus::Ok),
        1 => Some(LdictStatus::End),
        2 => Some(LdictStatus::InvalidArgument),
        3 => Some(LdictStatus::InvalidUtf8),
        4 => Some(LdictStatus::NullPointer),
        5 => Some(LdictStatus::Panic),
        6 => Some(LdictStatus::Unsupported),
        7 => Some(LdictStatus::IoError),
        8 => Some(LdictStatus::Closed),
        9 => Some(LdictStatus::DomainMismatch),
        10 => Some(LdictStatus::LimitExceeded),
        11 => Some(LdictStatus::ProviderError),
        12 => Some(LdictStatus::BatchInUse),
        _ => None,
    }
}

fn provider_status(raw: u32, operation: &str) -> Result<VtStatus, (LdictStatus, String)> {
    let Some(status) = VtStatus::from_raw(raw) else {
        return Err((
            LdictStatus::ProviderError,
            format!("{operation} returned unknown provider status {raw}"),
        ));
    };
    let mapped = match status {
        VtStatus::Ok | VtStatus::End => return Ok(status),
        VtStatus::InvalidArgument => LdictStatus::InvalidArgument,
        VtStatus::NullPointer => LdictStatus::NullPointer,
        VtStatus::Unsupported => LdictStatus::Unsupported,
        VtStatus::IoError => LdictStatus::IoError,
        VtStatus::Closed => LdictStatus::Closed,
        VtStatus::LimitExceeded => LdictStatus::LimitExceeded,
        VtStatus::ProviderError => LdictStatus::ProviderError,
        VtStatus::BatchInUse => LdictStatus::BatchInUse,
    };
    Err((
        mapped,
        format!("{operation} failed with provider status {status:?}"),
    ))
}

fn validate_entries_info(info: &LdictEntriesInfo) -> Result<(), (LdictStatus, String)> {
    if !matches!(
        info.unit_domain,
        value if value == VtUnitDomain::Byte as u32
            || value == VtUnitDomain::UnicodeScalar as u32
            || value == VtUnitDomain::U64 as u32
    ) {
        return Err((
            LdictStatus::ProviderError,
            format!(
                "entry provider returned unknown unit domain {}",
                info.unit_domain
            ),
        ));
    }
    if info.value_domain != VtValueDomain::OptionalU64 as u32 {
        return Err((
            LdictStatus::ProviderError,
            format!(
                "entry provider returned unsupported value domain {}",
                info.value_domain
            ),
        ));
    }
    if info.order != VtDictionaryEntryOrder::Lexicographic as u32 {
        return Err((
            LdictStatus::ProviderError,
            format!("entry provider returned unknown order {}", info.order),
        ));
    }
    let known_flags =
        dictionary_entries_info_flags::EXACT_LEN | dictionary_entries_info_flags::SNAPSHOT_IDENTITY;
    if info.reserved0 != 0 || info.flags & !known_flags != 0 || info.reserved != [0; 2] {
        return Err((
            LdictStatus::ProviderError,
            "entry provider returned nonzero reserved metadata".into(),
        ));
    }
    Ok(())
}

unsafe fn entry_cursor_mut<'a>(
    cursor: *mut LdictEntryCursor,
) -> Result<&'a mut LdictEntryCursor, (LdictStatus, String)> {
    cursor
        .as_mut()
        .ok_or((LdictStatus::NullPointer, "entry cursor is null".into()))
}

struct EntryReducerContext {
    reducer: LdictEntryReducer,
    reducer_context: *mut std::ffi::c_void,
    callback_error: Option<LdictStatus>,
}

unsafe extern "C" fn entry_reducer_trampoline(
    context: *mut std::ffi::c_void,
    batch: *const VtDictionaryEntryBatchView,
) -> u32 {
    if context.is_null() {
        return VtStatus::NullPointer.to_raw();
    }
    let context = &mut *context.cast::<EntryReducerContext>();
    let raw = (context.reducer)(context.reducer_context, batch);
    match ldict_status_from_raw(raw) {
        Some(LdictStatus::Ok) => VtStatus::Ok.to_raw(),
        Some(LdictStatus::End) => VtStatus::End.to_raw(),
        Some(status) => {
            context.callback_error = Some(status);
            VtStatus::ProviderError.to_raw()
        }
        None => {
            context.callback_error = Some(LdictStatus::InvalidArgument);
            VtStatus::ProviderError.to_raw()
        }
    }
}

/// Return the stable project ABI version.
#[no_mangle]
pub extern "C" fn ldict_abi_version() -> u32 {
    LDICT_ABI_VERSION
}

/// Return the additive API revision.
#[no_mangle]
pub extern "C" fn ldict_api_revision() -> u32 {
    LDICT_API_REVISION
}

/// Return the current thread's last ABI error message.
#[no_mangle]
pub extern "C" fn ldict_last_error_message() -> *const c_char {
    LAST_ERROR.with(|slot| slot.borrow().as_ptr())
}

/// Construct an empty mutable DynamicDAWG.
///
/// # Safety
/// `out_dictionary` must be writable.
#[no_mangle]
pub unsafe extern "C" fn ldict_dynamic_dawg_new(
    unit_domain: u32,
    out_dictionary: *mut *mut LdictDictionary,
) -> LdictStatus {
    boundary(|| {
        if out_dictionary.is_null() {
            return Err((LdictStatus::NullPointer, "out_dictionary is null".into()));
        }
        out_dictionary.write(ptr::null_mut());
        let binding = LdictBinding::Dynamic(DynamicDawgBinding::new(domain(unit_domain)?));
        let resource = binding.resource();
        out_dictionary.write(Box::into_raw(Box::new(LdictDictionary {
            binding,
            resource,
        })));
        Ok(LdictStatus::Ok)
    })
}

/// Build an immutable DoubleArrayTrie from a contiguous term descriptor array.
///
/// Byte and Unicode-scalar domains are supported. Terms must be valid UTF-8;
/// the byte form controls transition semantics rather than permitting malformed
/// string encodings.
///
/// # Safety
/// `entries` and `out_dictionary` must be valid for their declared lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_double_array_trie_new(
    unit_domain: u32,
    entries: *const LdictTextEntry,
    entry_count: usize,
    out_dictionary: *mut *mut LdictDictionary,
) -> LdictStatus {
    boundary(|| {
        if out_dictionary.is_null() {
            return Err((LdictStatus::NullPointer, "out_dictionary is null".into()));
        }
        out_dictionary.write(ptr::null_mut());
        let domain = domain(unit_domain)?;
        if domain == BindingUnitDomain::U64 {
            return Err((
                LdictStatus::Unsupported,
                "DoubleArrayTrie supports byte and Unicode-scalar terms".into(),
            ));
        }
        let mut owned_entries = Vec::with_capacity(entry_count);
        for entry in slice(entries, entry_count, "entries")? {
            let term = std::str::from_utf8(slice(entry.data, entry.len, "entry.data")?)
                .map_err(|error| (LdictStatus::InvalidUtf8, error.to_string()))?
                .to_owned();
            owned_entries.push((term, entry.value.decode()?));
        }
        let trie = match domain {
            BindingUnitDomain::Byte => DoubleArrayTrieBinding::from_byte_terms(owned_entries),
            BindingUnitDomain::UnicodeScalar => {
                DoubleArrayTrieBinding::from_unicode_terms(owned_entries)
            }
            BindingUnitDomain::U64 => unreachable!(),
        };
        let binding = LdictBinding::DoubleArray(trie);
        let resource = binding.resource();
        out_dictionary.write(Box::into_raw(Box::new(LdictDictionary {
            binding,
            resource,
        })));
        Ok(LdictStatus::Ok)
    })
}

/// Construct an empty mutable SCDAWG.
///
/// # Safety
/// `out_dictionary` must be writable.
#[no_mangle]
pub unsafe extern "C" fn ldict_scdawg_new(
    unit_domain: u32,
    out_dictionary: *mut *mut LdictDictionary,
) -> LdictStatus {
    boundary(|| {
        if out_dictionary.is_null() {
            return Err((LdictStatus::NullPointer, "out_dictionary is null".into()));
        }
        out_dictionary.write(ptr::null_mut());
        let binding = match domain(unit_domain)? {
            BindingUnitDomain::Byte => LdictBinding::Scdawg(ScdawgBinding::new_byte()),
            BindingUnitDomain::UnicodeScalar => LdictBinding::Scdawg(ScdawgBinding::new_unicode()),
            BindingUnitDomain::U64 => {
                return Err((
                    LdictStatus::Unsupported,
                    "SCDAWG supports byte and Unicode-scalar terms".into(),
                ))
            }
        };
        let resource = binding.resource();
        out_dictionary.write(Box::into_raw(Box::new(LdictDictionary {
            binding,
            resource,
        })));
        Ok(LdictStatus::Ok)
    })
}

#[cfg(feature = "persistent-artrie")]
unsafe fn persistent_path<'a>(
    data: *const u8,
    len: usize,
) -> Result<&'a std::path::Path, (LdictStatus, String)> {
    let path = std::str::from_utf8(slice(data, len, "path")?)
        .map_err(|error| (LdictStatus::InvalidUtf8, error.to_string()))?;
    if path.is_empty() {
        return Err((LdictStatus::InvalidArgument, "path is empty".into()));
    }
    Ok(std::path::Path::new(path))
}

#[cfg(feature = "persistent-artrie")]
unsafe fn persistent_open_or_create(
    unit_domain: u32,
    path_data: *const u8,
    path_len: usize,
    create: bool,
    vocab: bool,
    out_dictionary: *mut *mut LdictDictionary,
) -> LdictStatus {
    boundary(|| {
        if out_dictionary.is_null() {
            return Err((LdictStatus::NullPointer, "out_dictionary is null".into()));
        }
        out_dictionary.write(ptr::null_mut());
        let path = persistent_path(path_data, path_len)?;
        let persistent = if vocab {
            if create {
                PersistentARTrieBinding::create_vocab(path)
            } else {
                PersistentARTrieBinding::open_vocab(path)
            }
        } else {
            let domain = domain(unit_domain)?;
            if create {
                PersistentARTrieBinding::create(path, domain)
            } else {
                PersistentARTrieBinding::open(path, domain)
            }
        };
        let binding = LdictBinding::Persistent(binding(persistent)?);
        let resource = binding.resource();
        out_dictionary.write(Box::into_raw(Box::new(LdictDictionary {
            binding,
            resource,
        })));
        Ok(LdictStatus::Ok)
    })
}

/// Create a filesystem-backed byte, Unicode, or u64 persistent ARTrie.
///
/// # Safety
/// The UTF-8 path and output pointer must be valid.
#[cfg(feature = "persistent-artrie")]
#[no_mangle]
pub unsafe extern "C" fn ldict_persistent_artrie_create(
    unit_domain: u32,
    path_data: *const u8,
    path_len: usize,
    out_dictionary: *mut *mut LdictDictionary,
) -> LdictStatus {
    persistent_open_or_create(
        unit_domain,
        path_data,
        path_len,
        true,
        false,
        out_dictionary,
    )
}

/// Open a filesystem-backed byte, Unicode, or u64 persistent ARTrie.
///
/// # Safety
/// The UTF-8 path and output pointer must be valid.
#[cfg(feature = "persistent-artrie")]
#[no_mangle]
pub unsafe extern "C" fn ldict_persistent_artrie_open(
    unit_domain: u32,
    path_data: *const u8,
    path_len: usize,
    out_dictionary: *mut *mut LdictDictionary,
) -> LdictStatus {
    persistent_open_or_create(
        unit_domain,
        path_data,
        path_len,
        false,
        false,
        out_dictionary,
    )
}

/// Create a filesystem-backed bidirectional vocabulary ARTrie.
///
/// # Safety
/// The UTF-8 path and output pointer must be valid.
#[cfg(feature = "persistent-artrie")]
#[no_mangle]
pub unsafe extern "C" fn ldict_persistent_vocab_create(
    path_data: *const u8,
    path_len: usize,
    out_dictionary: *mut *mut LdictDictionary,
) -> LdictStatus {
    persistent_open_or_create(
        BindingUnitDomain::UnicodeScalar as u32,
        path_data,
        path_len,
        true,
        true,
        out_dictionary,
    )
}

/// Open a filesystem-backed bidirectional vocabulary ARTrie.
///
/// # Safety
/// The UTF-8 path and output pointer must be valid.
#[cfg(feature = "persistent-artrie")]
#[no_mangle]
pub unsafe extern "C" fn ldict_persistent_vocab_open(
    path_data: *const u8,
    path_len: usize,
    out_dictionary: *mut *mut LdictDictionary,
) -> LdictStatus {
    persistent_open_or_create(
        BindingUnitDomain::UnicodeScalar as u32,
        path_data,
        path_len,
        false,
        true,
        out_dictionary,
    )
}

/// Return the concrete backend identifier.
///
/// # Safety
/// Both pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_kind(
    dictionary: *const LdictDictionary,
    out_kind: *mut u32,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_kind.is_null() {
            return Err((LdictStatus::NullPointer, "out_kind is null".into()));
        }
        out_kind.write(dictionary.binding.kind());
        Ok(LdictStatus::Ok)
    })
}

/// Return the backend's supported operation bitset.
///
/// # Safety
/// Both pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_capabilities(
    dictionary: *const LdictDictionary,
    out_capabilities: *mut u64,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_capabilities.is_null() {
            return Err((LdictStatus::NullPointer, "out_capabilities is null".into()));
        }
        out_capabilities.write(dictionary.binding.capabilities());
        Ok(LdictStatus::Ok)
    })
}

/// Destroy a dictionary handle. Resources already retained by consumers remain valid.
///
/// # Safety
/// A non-null pointer must be a live handle returned by this library.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_free(dictionary: *mut LdictDictionary) {
    if !dictionary.is_null() {
        drop(Box::from_raw(dictionary));
    }
}

/// Borrow the dictionary resource for an immediate retaining consumer call.
///
/// The returned words remain valid while `dictionary` is alive. A consumer that
/// stores them must invoke the resource vtable's `retain` operation first.
///
/// # Safety
/// Both pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_resource(
    dictionary: *const LdictDictionary,
    out_resource: *mut VtResource,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_resource.is_null() {
            return Err((LdictStatus::NullPointer, "out_resource is null".into()));
        }
        out_resource.write(dictionary.resource.as_raw());
        Ok(LdictStatus::Ok)
    })
}

/// Open a bounded, lexicographic entry stream over one immutable revision.
///
/// The returned cursor owns its captured snapshot and may outlive `dictionary`.
/// Each successful [`ldict_entry_cursor_next`] leases exactly one batch until
/// its generation is passed to [`ldict_entry_cursor_release`].
///
/// # Safety
/// `dictionary`, `out_cursor`, and `out_info` must be valid pointers.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_entries_open(
    dictionary: *const LdictDictionary,
    out_cursor: *mut *mut LdictEntryCursor,
    out_info: *mut LdictEntriesInfo,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_cursor.is_null() {
            return Err((LdictStatus::NullPointer, "out_cursor is null".into()));
        }
        out_cursor.write(ptr::null_mut());
        if out_info.is_null() {
            return Err((LdictStatus::NullPointer, "out_info is null".into()));
        }
        out_info.write(LdictEntriesInfo::default());

        let resource = dictionary.resource.as_raw();
        let resource_vtable = resource
            .vtable
            .as_ref()
            .ok_or((LdictStatus::ProviderError, "resource vtable is null".into()))?;
        let query_interface = resource_vtable.query_interface.ok_or((
            LdictStatus::Unsupported,
            "resource does not support interface discovery".into(),
        ))?;
        let mut interface: *const std::ffi::c_void = ptr::null();
        let status = provider_status(
            query_interface(
                resource.context,
                &VT_DICTIONARY_ENTRIES_INTERFACE_ID,
                VT_DICTIONARY_ENTRIES_INTERFACE_VERSION,
                &mut interface,
            ),
            "entry interface discovery",
        )?;
        if status != VtStatus::Ok || interface.is_null() {
            return Err((
                LdictStatus::ProviderError,
                "entry interface discovery returned no interface".into(),
            ));
        }

        let vtable = interface.cast::<VtDictionaryEntriesVTable>();
        let entries_vtable = vtable.as_ref().ok_or((
            LdictStatus::ProviderError,
            "entry interface vtable is null".into(),
        ))?;
        if entries_vtable.struct_size < std::mem::size_of::<VtDictionaryEntriesVTable>()
            || entries_vtable.interface_version < VT_DICTIONARY_ENTRIES_INTERFACE_VERSION
            || entries_vtable.reserved != 0
            || entries_vtable.open.is_none()
            || entries_vtable.next_batch.is_none()
            || entries_vtable.release_batch.is_none()
            || entries_vtable.reduce.is_none()
            || entries_vtable.cancel.is_none()
            || entries_vtable.close.is_none()
        {
            return Err((
                LdictStatus::ProviderError,
                "entry interface vtable is incomplete".into(),
            ));
        }

        let mut cursor = Box::new(LdictEntryCursor {
            raw: VtDictionaryEntriesCursor::NULL,
            vtable,
            leased_generation: None,
        });
        let mut info = LdictEntriesInfo::default();
        let status = provider_status(
            entries_vtable.open.expect("validated entry open")(
                resource.context,
                &mut cursor.raw,
                &mut info,
            ),
            "entry cursor open",
        )?;
        if status != VtStatus::Ok || cursor.raw.is_null() {
            return Err((
                LdictStatus::ProviderError,
                "entry cursor open returned no cursor".into(),
            ));
        }
        if let Err(error) = validate_entries_info(&info) {
            let _ = entries_vtable.close.expect("validated entry close")(&mut cursor.raw);
            return Err(error);
        }
        out_info.write(info);
        out_cursor.write(Box::into_raw(cursor));
        Ok(LdictStatus::Ok)
    })
}

/// Lease the next nonempty bounded entry batch.
///
/// # Safety
/// All pointers must be valid. The returned pointers remain valid only until
/// `batch.generation` is released or the cursor is freed.
#[no_mangle]
pub unsafe extern "C" fn ldict_entry_cursor_next(
    cursor: *mut LdictEntryCursor,
    limits: *const LdictEntryBatchLimits,
    out_batch: *mut LdictEntryBatch,
) -> LdictStatus {
    boundary(|| {
        if limits.is_null() {
            return Err((LdictStatus::NullPointer, "limits is null".into()));
        }
        if out_batch.is_null() {
            return Err((LdictStatus::NullPointer, "out_batch is null".into()));
        }
        out_batch.write(LdictEntryBatch::default());
        let limits_value = *limits;
        if limits_value.max_entries == 0 || limits_value.reserved != 0 {
            return Err((
                LdictStatus::InvalidArgument,
                "max_entries must be nonzero and limits.reserved must be zero".into(),
            ));
        }
        let cursor = entry_cursor_mut(cursor)?;
        if cursor.leased_generation.is_some() {
            return Err((
                LdictStatus::BatchInUse,
                "entry cursor already has a live batch lease".into(),
            ));
        }
        let next = (*cursor.vtable).next_batch.ok_or((
            LdictStatus::ProviderError,
            "entry next callback is null".into(),
        ))?;
        let status = provider_status(next(&mut cursor.raw, limits, out_batch), "entry next")?;
        match status {
            VtStatus::Ok => {
                let batch = &*out_batch;
                if batch.entry_count == 0
                    || batch.entry_count > limits_value.max_entries
                    || batch.unit_count > limits_value.max_units
                    || batch.value_count > limits_value.max_values
                    || batch.generation == 0
                    || batch.reserved != 0
                    || batch.entries.is_null()
                    || (batch.unit_count != 0 && batch.units.is_null())
                    || (batch.value_count != 0 && batch.values.is_null())
                {
                    let release = (*cursor.vtable)
                        .release_batch
                        .expect("validated entry release");
                    if batch.generation != 0 {
                        let _ = release(&mut cursor.raw, batch.generation);
                    }
                    out_batch.write(LdictEntryBatch::default());
                    return Err((
                        LdictStatus::ProviderError,
                        "entry provider returned an invalid batch".into(),
                    ));
                }
                cursor.leased_generation = Some(batch.generation);
                Ok(LdictStatus::Ok)
            }
            VtStatus::End => Ok(LdictStatus::End),
            _ => unreachable!("provider_status returns only success statuses"),
        }
    })
}

/// Release the live batch lease identified by `generation`.
///
/// # Safety
/// `cursor` must point to a live entry cursor.
#[no_mangle]
pub unsafe extern "C" fn ldict_entry_cursor_release(
    cursor: *mut LdictEntryCursor,
    generation: u64,
) -> LdictStatus {
    boundary(|| {
        let cursor = entry_cursor_mut(cursor)?;
        if generation == 0 || cursor.leased_generation != Some(generation) {
            return Err((
                LdictStatus::InvalidArgument,
                "entry batch generation is not the live lease".into(),
            ));
        }
        let release = (*cursor.vtable).release_batch.ok_or((
            LdictStatus::ProviderError,
            "entry release callback is null".into(),
        ))?;
        let status = provider_status(release(&mut cursor.raw, generation), "entry batch release")?;
        debug_assert_eq!(status, VtStatus::Ok);
        cursor.leased_generation = None;
        Ok(LdictStatus::Ok)
    })
}

/// Drain bounded batches through `reducer` without exposing a long-lived lease.
///
/// Returning `LDICT_STATUS_END` from the reducer stops successfully. Other
/// published statuses abort and propagate after the provider settles its lease.
///
/// # Safety
/// All pointers and the callback must remain valid for this synchronous call.
#[no_mangle]
pub unsafe extern "C" fn ldict_entry_cursor_reduce(
    cursor: *mut LdictEntryCursor,
    limits: *const LdictEntryBatchLimits,
    reducer: Option<LdictEntryReducer>,
    reducer_context: *mut std::ffi::c_void,
    out_count: *mut usize,
) -> LdictStatus {
    boundary(|| {
        if limits.is_null() {
            return Err((LdictStatus::NullPointer, "limits is null".into()));
        }
        if out_count.is_null() {
            return Err((LdictStatus::NullPointer, "out_count is null".into()));
        }
        out_count.write(0);
        let reducer = reducer.ok_or((LdictStatus::NullPointer, "reducer is null".into()))?;
        let limits_value = *limits;
        if limits_value.max_entries == 0 || limits_value.reserved != 0 {
            return Err((
                LdictStatus::InvalidArgument,
                "max_entries must be nonzero and limits.reserved must be zero".into(),
            ));
        }
        let cursor = entry_cursor_mut(cursor)?;
        if cursor.leased_generation.is_some() {
            return Err((
                LdictStatus::BatchInUse,
                "entry cursor already has a live batch lease".into(),
            ));
        }
        let reduce = (*cursor.vtable).reduce.ok_or((
            LdictStatus::ProviderError,
            "entry reduce callback is null".into(),
        ))?;
        let mut context = EntryReducerContext {
            reducer,
            reducer_context,
            callback_error: None,
        };
        let raw = reduce(
            &mut cursor.raw,
            limits,
            Some(entry_reducer_trampoline),
            (&mut context as *mut EntryReducerContext).cast(),
            out_count,
        );
        if let Some(status) = context.callback_error {
            return Err((status, format!("entry reducer returned {status:?}")));
        }
        let status = provider_status(raw, "entry reduce")?;
        if status != VtStatus::Ok {
            return Err((
                LdictStatus::ProviderError,
                "entry reduce unexpectedly returned end".into(),
            ));
        }
        Ok(LdictStatus::Ok)
    })
}

/// Request sticky exhaustion. Cancellation is idempotent and does not settle a
/// currently leased batch.
///
/// # Safety
/// `cursor` must point to a live entry cursor.
#[no_mangle]
pub unsafe extern "C" fn ldict_entry_cursor_cancel(cursor: *mut LdictEntryCursor) -> LdictStatus {
    boundary(|| {
        let cursor = entry_cursor_mut(cursor)?;
        let cancel = (*cursor.vtable).cancel.ok_or((
            LdictStatus::ProviderError,
            "entry cancel callback is null".into(),
        ))?;
        let status = provider_status(cancel(&mut cursor.raw), "entry cancel")?;
        debug_assert_eq!(status, VtStatus::Ok);
        Ok(LdictStatus::Ok)
    })
}

/// Close and free a lease-free entry cursor. Null is accepted as a no-op.
///
/// A live lease returns `LDICT_STATUS_BATCH_IN_USE`; release it and retry.
///
/// # Safety
/// `cursor` must be null or the unique live pointer returned by
/// [`ldict_dictionary_entries_open`]. On success it becomes invalid.
#[no_mangle]
pub unsafe extern "C" fn ldict_entry_cursor_free(cursor: *mut LdictEntryCursor) -> LdictStatus {
    boundary(|| {
        if cursor.is_null() {
            return Ok(LdictStatus::Ok);
        }
        let cursor_ref = &mut *cursor;
        if cursor_ref.leased_generation.is_some() {
            return Err((
                LdictStatus::BatchInUse,
                "entry cursor still has a live batch lease".into(),
            ));
        }
        let close = (*cursor_ref.vtable).close.ok_or((
            LdictStatus::ProviderError,
            "entry close callback is null".into(),
        ))?;
        let status = provider_status(close(&mut cursor_ref.raw), "entry cursor close")?;
        debug_assert_eq!(status, VtStatus::Ok);
        drop(Box::from_raw(cursor));
        Ok(LdictStatus::Ok)
    })
}

/// Return the number of visible terms.
///
/// # Safety
/// Both pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_len(
    dictionary: *const LdictDictionary,
    out_len: *mut usize,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_len.is_null() {
            return Err((LdictStatus::NullPointer, "out_len is null".into()));
        }
        out_len.write(dictionary.binding.len());
        Ok(LdictStatus::Ok)
    })
}

/// Persist the current ARTrie revision and its committed WAL frontier.
///
/// # Safety
/// `dictionary` must be a valid live handle.
#[cfg(feature = "persistent-artrie")]
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_checkpoint(
    dictionary: *mut LdictDictionary,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        binding(dictionary.binding.checkpoint())?;
        Ok(LdictStatus::Ok)
    })
}

/// Copy the term associated with a persistent vocabulary index.
///
/// A null `out_data` with zero capacity is a size query. `out_len` always
/// receives the full UTF-8 byte count when the index exists.
///
/// # Safety
/// Output pointers and any non-zero output buffer must be valid.
#[cfg(feature = "persistent-artrie")]
#[no_mangle]
pub unsafe extern "C" fn ldict_vocab_get_term(
    dictionary: *const LdictDictionary,
    index: u64,
    out_data: *mut u8,
    capacity: usize,
    out_len: *mut usize,
    out_found: *mut u8,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_len.is_null() || out_found.is_null() || (capacity != 0 && out_data.is_null()) {
            return Err((LdictStatus::NullPointer, "vocabulary output is null".into()));
        }
        match binding(dictionary.binding.vocab_term(index))? {
            None => {
                out_len.write(0);
                out_found.write(0);
            }
            Some(term) => {
                let bytes = term.as_bytes();
                out_len.write(bytes.len());
                out_found.write(1);
                let size_query = capacity == 0 && out_data.is_null();
                if capacity < bytes.len() && !size_query {
                    if capacity != 0 {
                        ptr::copy_nonoverlapping(bytes.as_ptr(), out_data, capacity);
                    }
                    return Err((
                        LdictStatus::LimitExceeded,
                        format!("vocabulary output requires {} bytes", bytes.len()),
                    ));
                }
                if !size_query && !bytes.is_empty() {
                    ptr::copy_nonoverlapping(bytes.as_ptr(), out_data, bytes.len());
                }
            }
        }
        Ok(LdictStatus::Ok)
    })
}

/// Remove every term by publishing a fresh empty revision.
///
/// # Safety
/// `dictionary` must be a valid live handle.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_clear(dictionary: *mut LdictDictionary) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        binding(dictionary.binding.clear())?;
        Ok(LdictStatus::Ok)
    })
}

/// Compact the currently published DynamicDAWG.
///
/// # Safety
/// Both pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_compact(
    dictionary: *mut LdictDictionary,
    out_reclaimed: *mut usize,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_reclaimed.is_null() {
            return Err((LdictStatus::NullPointer, "out_reclaimed is null".into()));
        }
        out_reclaimed.write(binding(dictionary.binding.compact())?);
        Ok(LdictStatus::Ok)
    })
}

unsafe fn text_operation(
    dictionary: *const LdictDictionary,
    data: *const u8,
    len: usize,
    operation: impl FnOnce(&LdictBinding, &[u8]) -> Result<bool, BindingError>,
    out_changed: *mut u8,
) -> Result<LdictStatus, (LdictStatus, String)> {
    let dictionary = dictionary
        .as_ref()
        .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
    if out_changed.is_null() {
        return Err((LdictStatus::NullPointer, "output boolean is null".into()));
    }
    let changed = binding(operation(&dictionary.binding, slice(data, len, "term")?))?;
    out_changed.write(u8::from(changed));
    Ok(LdictStatus::Ok)
}

/// Insert or update one UTF-8/byte term.
///
/// # Safety
/// Input and output pointers must be valid for their lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_insert_text(
    dictionary: *mut LdictDictionary,
    data: *const u8,
    len: usize,
    value: LdictOptionalU64,
    out_inserted: *mut u8,
) -> LdictStatus {
    boundary(|| {
        let value = value.decode()?;
        text_operation(
            dictionary,
            data,
            len,
            |binding, term| binding.insert_text(term, value),
            out_inserted,
        )
    })
}

/// Insert or update a text term using scalar optional-value fields.
///
/// This additive entry point is equivalent to `ldict_dictionary_insert_text`
/// and avoids aggregate-by-value calling-convention differences in dynamic FFI
/// runtimes.
///
/// # Safety
/// Input and output pointers must be valid for their declared lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_insert_text_value(
    dictionary: *mut LdictDictionary,
    data: *const u8,
    len: usize,
    value: u64,
    has_value: u8,
    out_inserted: *mut u8,
) -> LdictStatus {
    ldict_dictionary_insert_text(
        dictionary,
        data,
        len,
        LdictOptionalU64 {
            value,
            has_value,
            reserved: [0; 7],
        },
        out_inserted,
    )
}

/// Remove one UTF-8/byte term.
///
/// # Safety
/// Input and output pointers must be valid for their lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_remove_text(
    dictionary: *mut LdictDictionary,
    data: *const u8,
    len: usize,
    out_removed: *mut u8,
) -> LdictStatus {
    boundary(|| {
        text_operation(
            dictionary,
            data,
            len,
            LdictBinding::remove_text,
            out_removed,
        )
    })
}

/// Test membership of one UTF-8/byte term.
///
/// # Safety
/// Input and output pointers must be valid for their lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_contains_text(
    dictionary: *const LdictDictionary,
    data: *const u8,
    len: usize,
    out_contains: *mut u8,
) -> LdictStatus {
    boundary(|| {
        text_operation(
            dictionary,
            data,
            len,
            LdictBinding::contains_text,
            out_contains,
        )
    })
}

/// Read the optional value of one UTF-8/byte term.
///
/// `out_found` distinguishes an absent term from a present term without a value.
///
/// # Safety
/// Input and output pointers must be valid for their lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_get_text(
    dictionary: *const LdictDictionary,
    data: *const u8,
    len: usize,
    out_found: *mut u8,
    out_value: *mut LdictOptionalU64,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_found.is_null() || out_value.is_null() {
            return Err((LdictStatus::NullPointer, "output is null".into()));
        }
        match binding(dictionary.binding.value_text(slice(data, len, "term")?))? {
            Some(value) => {
                out_found.write(1);
                out_value.write(LdictOptionalU64::encode(value));
            }
            None => {
                out_found.write(0);
                out_value.write(LdictOptionalU64::default());
            }
        }
        Ok(LdictStatus::Ok)
    })
}

/// Look up a text term using scalar optional-value outputs.
///
/// # Safety
/// All non-empty input and output pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_get_text_value(
    dictionary: *const LdictDictionary,
    data: *const u8,
    len: usize,
    out_found: *mut u8,
    out_value: *mut u64,
    out_has_value: *mut u8,
) -> LdictStatus {
    boundary(|| {
        if out_found.is_null() || out_value.is_null() || out_has_value.is_null() {
            return Err((LdictStatus::NullPointer, "lookup output is null".into()));
        }
        let mut optional = LdictOptionalU64::default();
        let status = ldict_dictionary_get_text(dictionary, data, len, out_found, &mut optional);
        if status == LdictStatus::Ok {
            out_value.write(optional.value);
            out_has_value.write(optional.has_value);
        }
        Ok(status)
    })
}

unsafe fn u64_operation(
    dictionary: *const LdictDictionary,
    data: *const u64,
    len: usize,
    operation: impl FnOnce(&LdictBinding, &[u64]) -> Result<bool, BindingError>,
    out_changed: *mut u8,
) -> Result<LdictStatus, (LdictStatus, String)> {
    let dictionary = dictionary
        .as_ref()
        .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
    if out_changed.is_null() {
        return Err((LdictStatus::NullPointer, "output boolean is null".into()));
    }
    let changed = binding(operation(
        &dictionary.binding,
        slice(data, len, "u64 term")?,
    ))?;
    out_changed.write(u8::from(changed));
    Ok(LdictStatus::Ok)
}

/// Insert or update one u64-token term.
///
/// # Safety
/// Input and output pointers must be valid for their lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_insert_u64(
    dictionary: *mut LdictDictionary,
    data: *const u64,
    len: usize,
    value: LdictOptionalU64,
    out_inserted: *mut u8,
) -> LdictStatus {
    boundary(|| {
        let value = value.decode()?;
        u64_operation(
            dictionary,
            data,
            len,
            |binding, term| binding.insert_u64(term, value),
            out_inserted,
        )
    })
}

/// Insert or update a u64-token term using scalar optional-value fields.
///
/// # Safety
/// Input and output pointers must be valid for their declared lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_insert_u64_value(
    dictionary: *mut LdictDictionary,
    data: *const u64,
    len: usize,
    value: u64,
    has_value: u8,
    out_inserted: *mut u8,
) -> LdictStatus {
    ldict_dictionary_insert_u64(
        dictionary,
        data,
        len,
        LdictOptionalU64 {
            value,
            has_value,
            reserved: [0; 7],
        },
        out_inserted,
    )
}

/// Remove one u64-token term.
///
/// # Safety
/// Input and output pointers must be valid for their lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_remove_u64(
    dictionary: *mut LdictDictionary,
    data: *const u64,
    len: usize,
    out_removed: *mut u8,
) -> LdictStatus {
    boundary(|| u64_operation(dictionary, data, len, LdictBinding::remove_u64, out_removed))
}

/// Test membership of one u64-token term.
///
/// # Safety
/// Input and output pointers must be valid for their lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_contains_u64(
    dictionary: *const LdictDictionary,
    data: *const u64,
    len: usize,
    out_contains: *mut u8,
) -> LdictStatus {
    boundary(|| {
        u64_operation(
            dictionary,
            data,
            len,
            LdictBinding::contains_u64,
            out_contains,
        )
    })
}

/// Read the optional value of one u64-token term.
///
/// # Safety
/// Input and output pointers must be valid for their lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_get_u64(
    dictionary: *const LdictDictionary,
    data: *const u64,
    len: usize,
    out_found: *mut u8,
    out_value: *mut LdictOptionalU64,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_found.is_null() || out_value.is_null() {
            return Err((LdictStatus::NullPointer, "output is null".into()));
        }
        match binding(dictionary.binding.value_u64(slice(data, len, "u64 term")?))? {
            Some(value) => {
                out_found.write(1);
                out_value.write(LdictOptionalU64::encode(value));
            }
            None => {
                out_found.write(0);
                out_value.write(LdictOptionalU64::default());
            }
        }
        Ok(LdictStatus::Ok)
    })
}

/// Look up a u64-token term using scalar optional-value outputs.
///
/// # Safety
/// All non-empty input and output pointers must be valid.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_get_u64_value(
    dictionary: *const LdictDictionary,
    data: *const u64,
    len: usize,
    out_found: *mut u8,
    out_value: *mut u64,
    out_has_value: *mut u8,
) -> LdictStatus {
    boundary(|| {
        if out_found.is_null() || out_value.is_null() || out_has_value.is_null() {
            return Err((LdictStatus::NullPointer, "lookup output is null".into()));
        }
        let mut optional = LdictOptionalU64::default();
        let status = ldict_dictionary_get_u64(dictionary, data, len, out_found, &mut optional);
        if status == LdictStatus::Ok {
            out_value.write(optional.value);
            out_has_value.write(optional.has_value);
        }
        Ok(status)
    })
}

/// Test whether a UTF-8 pattern occurs inside any indexed SCDAWG term.
///
/// # Safety
/// Input and output pointers must be valid for their declared lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_scdawg_contains_substring(
    dictionary: *const LdictDictionary,
    data: *const u8,
    len: usize,
    out_contains: *mut u8,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_contains.is_null() {
            return Err((LdictStatus::NullPointer, "out_contains is null".into()));
        }
        let pattern = std::str::from_utf8(slice(data, len, "pattern")?)
            .map_err(|error| (LdictStatus::InvalidUtf8, error.to_string()))?;
        out_contains.write(u8::from(binding(
            dictionary.binding.contains_substring(pattern),
        )?));
        Ok(LdictStatus::Ok)
    })
}

/// Count a UTF-8 substring's occurrences across indexed SCDAWG terms.
///
/// # Safety
/// Input and output pointers must be valid for their declared lengths.
#[no_mangle]
pub unsafe extern "C" fn ldict_scdawg_substring_frequency(
    dictionary: *const LdictDictionary,
    data: *const u8,
    len: usize,
    out_frequency: *mut usize,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_frequency.is_null() {
            return Err((LdictStatus::NullPointer, "out_frequency is null".into()));
        }
        let pattern = std::str::from_utf8(slice(data, len, "pattern")?)
            .map_err(|error| (LdictStatus::InvalidUtf8, error.to_string()))?;
        out_frequency.write(binding(dictionary.binding.substring_frequency(pattern))?);
        Ok(LdictStatus::Ok)
    })
}

/// Insert/update many UTF-8/byte terms with one FFI crossing.
///
/// # Safety
/// `entries` must address `entry_count` valid descriptors and `out_inserted`
/// must be writable.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_insert_text_batch(
    dictionary: *mut LdictDictionary,
    entries: *const LdictTextEntry,
    entry_count: usize,
    out_inserted: *mut usize,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_inserted.is_null() {
            return Err((LdictStatus::NullPointer, "out_inserted is null".into()));
        }
        let entries = slice(entries, entry_count, "entries")?;
        let inserted = if let LdictBinding::Dynamic(dynamic) = &dictionary.binding {
            if entries.is_empty() {
                out_inserted.write(0);
                return Ok(LdictStatus::Ok);
            }
            let domain = dynamic.domain();
            if domain == BindingUnitDomain::U64 {
                return Err((
                    LdictStatus::DomainMismatch,
                    BindingError::DomainMismatch.to_string(),
                ));
            }
            let mut decoded = Vec::with_capacity(entries.len());
            for entry in entries {
                let decoded_entry = (|| {
                    let term = slice(entry.data, entry.len, "entry data")?;
                    if domain == BindingUnitDomain::UnicodeScalar
                        && std::str::from_utf8(term).is_err()
                    {
                        return Err((
                            LdictStatus::InvalidUtf8,
                            BindingError::InvalidUtf8.to_string(),
                        ));
                    }
                    Ok((term, entry.value.decode()?))
                })();
                match decoded_entry {
                    Ok(entry) => decoded.push(entry),
                    Err(error) => {
                        if !decoded.is_empty() {
                            binding(dynamic.insert_text_batch(decoded))?;
                        }
                        return Err(error);
                    }
                }
            }
            binding(dynamic.insert_text_batch(decoded))?
        } else {
            let mut inserted = 0usize;
            for entry in entries {
                let term = slice(entry.data, entry.len, "entry data")?;
                inserted += usize::from(binding(
                    dictionary.binding.insert_text(term, entry.value.decode()?),
                )?);
            }
            inserted
        };
        out_inserted.write(inserted);
        Ok(LdictStatus::Ok)
    })
}

/// Insert/update many u64-token terms with one FFI crossing.
///
/// # Safety
/// `entries` must address `entry_count` valid descriptors and `out_inserted`
/// must be writable.
#[no_mangle]
pub unsafe extern "C" fn ldict_dictionary_insert_u64_batch(
    dictionary: *mut LdictDictionary,
    entries: *const LdictU64Entry,
    entry_count: usize,
    out_inserted: *mut usize,
) -> LdictStatus {
    boundary(|| {
        let dictionary = dictionary
            .as_ref()
            .ok_or((LdictStatus::NullPointer, "dictionary is null".into()))?;
        if out_inserted.is_null() {
            return Err((LdictStatus::NullPointer, "out_inserted is null".into()));
        }
        let entries = slice(entries, entry_count, "entries")?;
        let inserted = if let LdictBinding::Dynamic(dynamic) = &dictionary.binding {
            if entries.is_empty() {
                out_inserted.write(0);
                return Ok(LdictStatus::Ok);
            }
            if dynamic.domain() != BindingUnitDomain::U64 {
                return Err((
                    LdictStatus::DomainMismatch,
                    BindingError::DomainMismatch.to_string(),
                ));
            }
            let mut decoded = Vec::with_capacity(entries.len());
            for entry in entries {
                let decoded_entry = (|| {
                    Ok((
                        slice(entry.data, entry.len, "entry data")?,
                        entry.value.decode()?,
                    ))
                })();
                match decoded_entry {
                    Ok(entry) => decoded.push(entry),
                    Err(error) => {
                        if !decoded.is_empty() {
                            binding(dynamic.insert_u64_batch(decoded))?;
                        }
                        return Err(error);
                    }
                }
            }
            binding(dynamic.insert_u64_batch(decoded))?
        } else {
            let mut inserted = 0usize;
            for entry in entries {
                let term = slice(entry.data, entry.len, "entry data")?;
                inserted += usize::from(binding(
                    dictionary.binding.insert_u64(term, entry.value.decode()?),
                )?);
            }
            inserted
        };
        out_inserted.write(inserted);
        Ok(LdictStatus::Ok)
    })
}