armdb 0.11.0

sharded bitcask key-value storage optimized for NVMe
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
//! Embedded key-value storage engine optimized for NVMe.
//!
//! Single process, multi-threaded. Sync read/write API.
//! Each tree/map owns its storage — one tree = one database directory.
//!
//! # Durability backends
//!
//! Collections are generic over `D: Durability` (default: [`Bitcask`](durability::Bitcask)):
//!
//! - **Bitcask** — append-only log + compaction. Good for general workloads.
//! - **FixedStore** ([`Fixed`](durability::Fixed)) — fixed-slot pwrite, no compaction.
//!   Optimized for frequent updates of fixed-size values (counters, metrics, sessions).
//!
//! [`FixedTree`] and [`FixedMap`] are type aliases for `ConstTree<K, V, Fixed>` and
//! `ConstMap<K, V, Fixed>`. [`ZeroTree`] and [`ZeroMap`] also accept `Fixed` as backend.
//!
//! # Collection types
//!
//! | Type | Index | Values | Ordered | FixedStore | Feature |
//! |------|-------|--------|---------|:----------:|---------|
//! | [`ConstTree`] | SkipList | inline `[u8; V]` | yes | yes | *(default)* |
//! | [`ConstMap`] | HashMap | inline `[u8; V]` | no | yes | *(default)* |
//! | [`TypedTree`] | SkipList | typed `T` (in-memory, [`TypedRef`]) | yes | no | `typed-tree` |
//! | [`TypedMap`] | HashMap | typed `T` (in-memory, [`TypedRef`]) | no | no | `typed-tree` |
//! | [`ZeroTree`] | SkipList | zerocopy `T` (in-memory) | yes | yes | `typed-tree` |
//! | [`ZeroMap`] | HashMap | zerocopy `T` (in-memory) | no | yes | `typed-tree` |
//! | [`VarTree`] | SkipList | [`ByteView`] (disk + cache) | yes | no | `var-collections` |
//! | [`VarMap`] | HashMap | [`ByteView`] (disk + cache) | no | no | `var-collections` |
//! | `VarTypedTree` | SkipList | typed `T` (disk + cache) | yes | no | `typed-tree` + `var-collections` |
//! | `VarTypedMap` | HashMap | typed `T` (disk + cache) | no | no | `typed-tree` + `var-collections` |
//!
//! # Usage
//!
//! ```ignore
//! // Bitcask backend (default)
//! let tree = ConstTree::<[u8; 16], 64>::open("data/users", Config::balanced().build())?;
//!
//! // FixedStore backend
//! let tree = FixedTree::<[u8; 16], 64>::open("data/counters", FixedConfig::balanced().build())?;
//!
//! tree.put(&key, &value)?;
//! let val = tree.get(&key);
//! tree.close()?;
//! ```
//!
//! # Durability
//!
//! ## Bitcask
//!
//! Writes are buffered in memory (`write_buffer_size` per shard, default 1 MB).
//! `put()` returns as soon as the entry is copied into the buffer and the
//! in-memory index is updated — **no disk I/O on the write path**.
//!
//! This means unflushed data is lost on crash. To control durability:
//!
//! - [`flush_buffers()`](ConstTree::flush_buffers) — flush write buffers to disk (no fsync)
//! - [`close()`](ConstTree::close) — flush + fsync + write hint files
//!
//! ## FixedStore
//!
//! Each `put()` does a `pwrite` through the page cache (~200ns).
//! `fdatasync` is called in batches (configurable interval/count), **after**
//! releasing the shard lock. With `enable_fsync = true`, an additional
//! per-write `fdatasync` runs inside the shard lock for immediate durability.
//! No compaction, no write amplification, 1x space usage.
//!
//! # Thread safety
//!
//! All tree/map types are `Send + Sync`. Share via `Arc` for concurrent access:
//!
//! ```ignore
//! let tree = Arc::new(ConstTree::<[u8; 8], 8>::open("data/mydb", Config::balanced().build())?);
//! let t = tree.clone();
//! std::thread::spawn(move || { t.put(&key, &value).unwrap(); });
//! ```
//!
//! **Reads:**
//! - `ConstTree` / `ZeroTree` / `TypedTree` — **lock-free**: the index is a lock-free
//!   SkipList (`TypedTree` resolves the value through a `seize` RCU guard, no mutex).
//! - `VarTree` — lock-free SkipList lookup; on a block-cache **miss** a brief shard lock
//!   fetches the file handles, then the `pread` runs **outside** the lock.
//! - `ConstMap` / `ZeroMap` / `TypedMap` — a **brief per-shard mutex** guards the HashMap
//!   index. Values are inline for `Const`/`Zero`; `TypedMap` reads a pointer under the lock,
//!   then accesses the value lock-free via a `seize` guard.
//! - `VarMap` / `VarTypedMap` — brief per-shard mutex on the index; a `pread` on a cache
//!   miss runs outside the lock.
//!
//! **Writes** acquire the target key's **per-shard mutex** (write buffer + index update), so
//! writes to *different shards* never contend on the buffer or durability I/O. Tree writes
//! additionally link the new node into the shared SkipList under its internal linking lock —
//! briefly contended across shards, but the critical section is O(node height), not the full
//! O(log n) search.
//!
//! # Encryption at rest (feature `encryption`)
//!
//! Page-level AES-256-GCM encryption. Key from env or direct config:
//!
//! ```ignore
//! let key = PageCipher::key_from_env("ARMDB_KEY")?;
//! let config = Config::balanced().encryption_key(Some(key)).build();
//! let tree = ConstTree::<[u8; 16], 64>::open("data/encrypted", config)?;
//! // all data is transparently encrypted on disk
//! ```
//!
//! # Write hooks (secondary indexes)
//!
//! Generic `WriteHook<K>` / `TypedWriteHook<K, T>` parameter for synchronous
//! write and init notifications. Zero overhead when unused (`NoHook` default).
//!
//! - `on_write` — fires on every `put`/`insert`/`delete`/`cas`/`compare_delete`/`update`/`fetch_update`,
//!   including mutations inside `atomic()` (buffered under the shard lock and replayed once
//!   it is released, in application order). If the closure returns `Err`, hooks still fire
//!   for operations that were applied. On `Const*`/`Zero*` collections replay happens after
//!   the `sync()?` seam; Var/Typed collections have no per-write sync.
//! - `on_init` — fires once per live entry during collection open (after
//!   recovery). Enable via `NEEDS_INIT = true`. See [`armdb/docs/hooks.md`]
//!   for details.
//! - `NEEDS_OLD_VALUE` — only affects VarTree/VarMap (skips disk I/O for
//!   old value when `false`). In-memory collections (Const/Typed/Zero) always
//!   provide the old value at zero cost.
//!
//! ```ignore
//! impl WriteHook<[u8; 16]> for MyIndex {
//!     const NEEDS_OLD_VALUE: bool = true;
//!     const NEEDS_INIT: bool = true;
//!
//!     fn on_write(&self, key: &[u8; 16], old: Option<&[u8]>, new: Option<&[u8]>) {
//!         // update secondary index incrementally
//!     }
//!
//!     fn on_init(&self, key: &[u8; 16], value: &[u8]) {
//!         // populate secondary index at startup
//!     }
//! }
//!
//! let tree = ConstTree::<[u8; 16], 64, MyIndex>::open_hooked("data/indexed", config, my_index)?;
//! tree.migrate(|_, _| MigrateAction::Keep)?; // triggers on_init for all entries
//! ```
//!
//! # Compaction
//!
//! Compaction is **not automatic**. Dead bytes accumulate as entries are
//! overwritten or deleted. Use [`Compactor`] to run it in the background:
//!
//! ```ignore
//! use std::sync::Arc;
//! use std::time::Duration;
//!
//! let tree = Arc::new(ConstTree::<[u8; 16], 64>::open("data/mydb", Config::balanced().build())?);
//! let t = tree.clone();
//! let _compactor = Compactor::start(move || t.compact(), Duration::from_secs(60));
//! ```
//!
//! Or call `tree.compact()` manually when needed.
//!
//! # Iteration
//!
//! All Tree types provide `iter()`, `range()`, and `prefix_iter()` methods.
//! Map types (HashMap index) **do not support iteration**.
//!
//! Each method returns a dedicated iterator implementing `Iterator` + `DoubleEndedIterator`:
//!
//! | Tree | Iterator | Item |
//! |------|----------|------|
//! | [`ConstTree`] | [`ConstIter`] | `(K, [u8; V])` — copy |
//! | [`VarTree`] | [`VarIter`] | `(K, ByteView)` — RC, possible disk I/O |
//! | [`TypedTree`] | [`TypedIter`] | `(K, TypedRef<T>)` — guard-protected reference, zero I/O |
//! | [`ZeroTree`] | [`ZeroIter`] | `(K, T)` — copy, zero I/O |
//!
//! | Method | Description |
//! |--------|-------------|
//! | `iter()` | All entries in index order |
//! | `range(start, end)` | Entries in `[start, end)` — start inclusive, end exclusive |
//! | `range_bounds(start, end)` | Entries with custom `Bound` — `Included`, `Excluded`, or `Unbounded` |
//! | `prefix_iter(prefix)` | Entries whose key starts with `prefix` |
//!
//! ```ignore
//! for (key, value) in tree.iter() { /* ... */ }
//!
//! let latest = tree.prefix_iter(&user_id).take(20).collect::<Vec<_>>();
//!
//! for (key, value) in tree.range(&start_key, &end_key) { /* ... */ }
//!
//! // Custom bounds: (5, 10] — exclude 5, include 10
//! use std::ops::Bound;
//! let entries: Vec<_> = tree.range_bounds(
//!     Bound::Excluded(&5u64.to_be_bytes()),
//!     Bound::Included(&10u64.to_be_bytes()),
//! ).collect();
//!
//! // DoubleEndedIterator — .rev() or .next_back()
//! let oldest = tree.prefix_iter(&user_id).rev().take(10);
//!
//! // TypedTree only: cheap scan — `&T` borrowed for the call, no per-row guard.
//! // `ControlFlow::Break` stops early.
//! tree.range(&start_key, &end_key).for_each_ref(|key, value| {
//!     std::ops::ControlFlow::Continue(())
//! });
//! ```
//!
//! ## Complexity
//!
//! | Operation | Complexity | Notes |
//! |-----------|------------|-------|
//! | `next()` | **O(1)** | follows SkipList level-0 forward pointer |
//! | `next_back()` | first step: expected **O(log n)**; an m-row reverse walk: expected/amortized **O(log n + m)** | resumes a read-only SkipList predecessor staircase; a fresh iterator still seeks from the top |
//! | `iter()` / `range()` / `prefix_iter()` setup | O(log n) | initial SkipList search |
//!
//! The reverse bound follows the geometric `p = 0.25` tower distribution; an
//! all-height-1 topology can fall back to the old search cost.
//!
//! `VarIter`: both `next()` and `next_back()` may additionally perform a
//! `pread` on block-cache miss. Use `warmup()` to pre-populate the cache.
//!
//! ## Weakly-consistent semantics
//!
//! Iterators do **not** create a snapshot. They are weakly-consistent:
//!
//! - Concurrent inserts/updates **may be visible** during iteration
//! - Deleted entries (marked nodes) are **automatically skipped**
//! - The `seize` guard prevents memory reclamation for the lifetime of the
//!   iterator — no use-after-free, but the index is not frozen
//!
//! # Ordering: `Config::reversed`
//!
//! `Config::reversed` controls the SkipList comparator direction.
//!
//! | `reversed` | `iter()` / `prefix_iter()` | `.rev()` / `next_back()` |
//! |:----------:|:--------------------------:|:------------------------:|
//! | `true` (**default**) | **DESC** (newest first) | ASC (oldest first) |
//! | `false` | **ASC** (oldest first) | DESC (newest first) |
//!
//! ```ignore
//! // reversed=true (default) — DESC: идеально для "newest first" пагинации
//! let tree = ConstTree::<[u8; 16], 64>::open("data/posts", Config::balanced().build())?;
//! let latest = tree.prefix_iter(&user_id).take(20);    // newest 20
//! let oldest = tree.prefix_iter(&user_id).rev().take(5); // oldest 5
//!
//! // reversed=false — ASC: естественный порядок ключей
//! let config = Config::balanced().reversed(false).build();
//! let tree = ConstTree::<[u8; 16], 64>::open("data/logs", config)?;
//! for (key, value) in tree.iter() { /* ascending order */ }
//! ```
//!
//! Keys are stored on disk as-is. `reversed` can be changed between restarts
//! without migration — it only affects in-memory index ordering.
//!
//! FixedStore collections take the same knob via `FixedConfig::reversed`
//! (default `true` → DESC); it behaves identically and is likewise in-memory
//! only.
//!
//! # Prefix sharding
//!
//! ```ignore
//! let config = Config::balanced().shard_prefix_bits(32).build();
//! let tree = ConstTree::<[u8; 16], 64>::open("data/users", config)?;
//! ```
//!
//! # Caveats
//!
//! - **Iterators are weakly-consistent, not snapshot.** Concurrent inserts and
//!   updates may be visible during iteration. Deleted entries are skipped.
//!   The `seize` guard prevents use-after-free but does not freeze the index.
//! - **CAS/update holds shard lock during possible disk I/O.** `VarTree::cas`,
//!   `VarTree::update`, `VarMap::cas`, and `VarMap::update` read the current value
//!   under the shard mutex. On a block-cache miss this issues a `pread` — blocking
//!   all writes to that shard until the read completes. Pre-warm the cache or size
//!   it to cover the working set.
//! - **`migrate()` on HashMap trees allocates `O(keys/shards)` memory.**
//!   `ConstMap::migrate` and `VarMap::migrate` collect all shard keys into a `Vec`
//!   before iterating. For very large shards this causes a transient memory spike.
//!   SkipList trees (`ConstTree`, `VarTree`) are not affected.
//!
//! # Shutdown
//!
//! ```ignore
//! // 1. Stop background tasks first
//! compactor.stop();
//! // 2. Close the tree (writes hint files, flushes, fsyncs)
//! Arc::try_unwrap(tree).expect("no other references").close()?;
//! ```
//!
//! If `close()` is not called (e.g. the tree is dropped via `Arc::drop`),
//! `Shard::Drop` still flushes write buffers, fsyncs, and writes hint files
//! automatically — no data loss and no slow recovery on next startup.
//!
//! # Layers above the core
//!
//! The items above are the storage core. Everything built on top has its own
//! entry point and its own document:
//!
//! | Layer | Entry point | Document |
//! |---|---|---|
//! | Named collections, migrations, background workers, RPC | [`armour::Db`] | `docs/armour.md` |
//! | Ranges, pages, bulk range operations | `collection.scope::<N>()` | `docs/iterators.md` |
//! | Decoded-value cache | `get_shared` on Var typed families | `docs/tuning.md` |
//! | Cross-collection transactions | `db.tx()` | `docs/transactions.md` |
//! | TTL | `TtlPolicy` / `TtlHook` | `docs/hooks.md` |
//! | Secondary indexes, counters, unique namespaces, change streams | `schema::SchemaRegistry` | `docs/schema-metadata.md` |
//! | Durable queues | `db.open_queue::<N>()` | `docs/queues.md` |
//! | Realtime watches | `WatchHook` + `watch()` | `docs/watch.md` |
//!
//! # Features
//!
//! - `typed-tree` — enables [`TypedTree`], [`TypedMap`], [`ZeroTree`], [`ZeroMap`],
//!   [`Codec`] and codec implementations
//! - `var-collections` — enables [`VarTree`], [`VarMap`] (variable-length values with LRU cache)
//! - `rapira-codec` — [`RapiraCodec`] for rapira serialization (implies `typed-tree`)
//! - `bytemuck-codec` — [`BytemuckCodec`] / [`BytemuckSliceCodec`] (implies `typed-tree`)
//! - `bitcode-codec` — [`BitcodeCodec`] (implies `typed-tree`)
//! - `postcard-codec` — `PostcardCodec` for postcard/serde serialization (implies `typed-tree`)
//! - `encryption` — AES-256-GCM page-level encryption at rest
//! - `replication` — two independent replication stacks behind one flag:
//!   leader/follower log-shipping for Bitcask collections (`replication/`)
//!   and event-based slot replication for FixedStore ones
//!   (`fixed_replication/`; catch-up is a full slot scan on reconnect, its
//!   cursor is diagnostics-only)
//! - `armour` — integration with armour ecosystem: [`Db`](armour::Db),
//!   schema-versioned migrations, binary RPC server (TCP/UDS).
//!   See [`armour`] module docs.
//! - `rpc` — TCP/UDS RPC server (implies `armour`)
//! - `schema` — relation metadata over collections: engine-maintained secondary
//!   indexes, counters, unique namespaces and change streams, plus the CI
//!   validator and Mermaid ER export (implies `armour`)
//! - `fjall` — `LsmTree`, an fjall-backed collection for datasets
//!   larger than RAM (implies `armour`)
//! - `io-uring` — io_uring flush-path backend (Linux only). Off by default: the
//!   default [`IoBackend`] is `Pwrite`
//! - `solana` — Solana pubkey/signature key types (implies `armour`)
//! - `uuid` — `Uuid` key type
//! - `id-cipher` — enables `armour-core/cipher` (wire-level id encryption)
//! - `hot-path-tracing` — per-operation `tracing::trace!` calls
//!
//! `recommended` is a convenience bundle for applications that embed the engine
//! and do not serve it over the network: it takes the default set minus `rpc`
//! (and the `armour-rpc`/`compio`/`ctrlc` dependencies behind it) and minus
//! `replication`, and adds `encryption`. Use it with `default-features = false`.
//!
//! Internal/test-only: `parking_lot` (default; without it a panic under a shard
//! lock poisons that mutex — see libfunc/armour#154), `loom`, `proptest`,
//! `ctx-gates`, `test-faults`, `queue-test-support`, `bench-internals`.

#![warn(clippy::unwrap_used)]
// Test-support items (`tx_debug_*`, `arm_*`, `test_try_lock`, the fault
// injectors) exist for tests that are themselves feature-gated. Compile the
// unit tests in a reduced feature set and those helpers are, correctly, dead —
// roughly forty of them. That is a property of the configuration, not a defect
// to fix item by item, so silence `dead_code` for exactly those builds. The
// default feature set keeps the lint at full strength.
#![cfg_attr(
    all(
        test,
        not(all(
            feature = "parking_lot",
            feature = "rapira-codec",
            feature = "var-collections",
            feature = "rpc"
        ))
    ),
    allow(dead_code)
)]

// T10 review F4: [`unique_index!`] hardcodes the string `"armdb::zerocopy"` in
// a `#[zerocopy(crate = "…")]` override, because that attribute takes a
// string literal and a string cannot carry `$crate` hygiene. Without this
// declaration, that hardcoded path resolves only from a *downstream* crate
// (where `armdb` is a real, externally-named dependency) — it fails to
// resolve from this crate's own internal invocations of the macro (unit
// tests in `unique/diff.rs`, `unique_tests.rs`, `schema/tests.rs`), which are
// compiled as part of this same crate and so have no `armdb` in their extern
// prelude at all. `extern crate self as armdb;` is the standard fix: it
// binds this crate's own root to the name `armdb`, so the identical hardcoded
// path resolves in both contexts. Gated like the `zerocopy`/`armour_core`
// re-exports below, since that is the feature every practical invocation of
// the macro already requires (`Db::open_unique_index`).
#[cfg(feature = "armour")]
extern crate self as armdb;

#[cfg(feature = "armour")]
mod access;
mod batch;
#[cfg(feature = "var-collections")]
mod byte_view;
#[cfg(feature = "var-collections")]
mod cache;
#[cfg(feature = "typed-tree")]
pub mod codec;
pub mod compaction;
mod config;
mod const_map;
mod const_tree;
/// Counter target types and the checked `resolve`/`resolve_typed` arithmetic
/// (T9), plus the contribution diff, wired into every path that can move a
/// counter: the non-transactional write path (facade and `atomic()`/TTL
/// replay), `db.tx()` commit, the open-time recount, and `schema::repair`.
#[cfg(feature = "typed-tree")]
mod counter;
/// The `counters_dirty` marker (T9): persisted once per session, when a
/// counted source is opened (a failed persist fails the open), and cleared
/// only by a fully successful `Db::close`/`clean_shutdown` — and then only for
/// the collections this session accounted for.
#[cfg(feature = "typed-tree")]
mod counter_dirty;
/// `CounterCollection` roundtrip tests (T9 part 3) plus the shared T9 test
/// fixture (`Group`/`Member`/`MemberKey`/`counted_fixture[_at]`) reused
/// verbatim by later T9 tasks.
#[cfg(all(
    test,
    feature = "typed-tree",
    feature = "var-collections",
    feature = "armour",
    feature = "rapira-codec"
))]
mod counter_tests;
#[cfg(feature = "encryption")]
mod crypto;
mod ctx;
#[cfg(feature = "ctx-gates")]
#[doc(hidden)]
pub mod ctx_gates_sync;
#[cfg(feature = "var-collections")]
mod decoded_cache;
mod disk_loc;
pub mod durability;
mod engine;
mod entry;
mod error;
pub mod fixed;
mod flusher;
#[cfg(feature = "replication")]
pub(crate) mod frame_reader;
mod held_ops;
#[cfg(feature = "typed-tree")]
mod hex;
mod hint;
mod hint_worker;
mod hook;
mod io;
mod key;
mod lock;
mod map_index;
mod meta;
#[cfg(feature = "typed-tree")]
mod projection;
#[cfg(all(feature = "armour", feature = "typed-tree"))]
mod queue;
#[cfg(all(
    debug_assertions,
    feature = "armour",
    feature = "typed-tree",
    feature = "queue-test-support"
))]
#[doc(hidden)]
pub use queue::fixed::test_support as queue_test_support;
#[cfg(all(
    debug_assertions,
    feature = "armour",
    feature = "typed-tree",
    feature = "queue-test-support"
))]
#[doc(hidden)]
pub use queue::wait::test_support as queue_wake_test_support;
mod recovery;
#[cfg(feature = "encryption")]
mod salt;
mod scope;
mod shard;
mod shutdown;
#[cfg(any(feature = "loom", miri, feature = "bench-internals"))]
pub mod skiplist;
#[cfg(not(any(feature = "loom", miri, feature = "bench-internals")))]
mod skiplist;
mod sweeper;
mod sync;
#[cfg(all(test, feature = "typed-tree"))]
mod test_faults;
mod tree_meta;
mod ttl;
/// Transaction log (T5 part 1). Wired into `Db` in part 2.
#[allow(dead_code)]
mod txlog;
/// Reentrancy depth for `atomic()` — independent of the `armour` / `db.tx()` stack.
mod txn_depth;
/// Engine-owned unique namespace collection (T10): the 80-byte row/owner
/// types, the opaque `UniqueIndex` wrapper, claim projection and `db.tx()`
/// resolution (`resolve_claims`, beside `resolve_counters`).
#[cfg(feature = "typed-tree")]
mod unique;
/// Shared T10 claim-forwarding test fixture (Task 3 review fix F5), reused by
/// `hook.rs` and `ttl.rs` — mirrors `counter_tests`'s role for T9.
#[cfg(all(test, feature = "typed-tree", feature = "armour"))]
mod unique_tests;
pub(crate) use txn_depth::AtomicDepthGuard;
#[cfg(feature = "armour")]
#[cfg(not(feature = "test-faults"))]
#[allow(dead_code)]
mod txn;
#[cfg(all(feature = "armour", feature = "test-faults"))]
#[allow(dead_code)]
pub mod txn;
#[cfg(feature = "armour")]
pub use txn::{Selection, Tx, TxConfig, TxScope};
mod upsert;
#[cfg(feature = "var-collections")]
mod value_cache;
#[cfg(feature = "var-collections")]
mod var_map;
#[cfg(feature = "var-collections")]
mod var_tree;
#[cfg(feature = "typed-tree")]
mod zero_map;
#[cfg(feature = "typed-tree")]
mod zero_tree;

#[cfg(feature = "typed-tree")]
mod typed_map;
#[cfg(feature = "typed-tree")]
mod typed_tree;
#[cfg(feature = "typed-tree")]
mod watch;

#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
mod var_typed_map;
#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
mod var_typed_tree;

#[cfg(feature = "replication")]
pub mod replication;

#[cfg(feature = "replication")]
pub mod fixed_replication;

pub mod docs;

#[cfg(feature = "armour")]
pub mod armour;

#[cfg(feature = "schema")]
pub mod schema;

#[cfg(feature = "fjall")]
pub mod lsm;

#[cfg(feature = "armour")]
pub use armour_core;
pub use batch::Applied;
#[allow(deprecated)]
pub use batch::BatchWrite;
#[cfg(feature = "var-collections")]
pub use byte_view::ByteView;
#[cfg(feature = "bitcode-codec")]
pub use codec::BitcodeCodec;
#[cfg(feature = "typed-tree")]
pub use codec::Codec;
#[cfg(feature = "typed-tree")]
pub use codec::InspectionEncoding;
#[cfg(feature = "postcard-codec")]
pub use codec::PostcardCodec;
#[cfg(feature = "rapira-codec")]
pub use codec::RapiraCodec;
#[cfg(feature = "typed-tree")]
pub use codec::ZerocopyCodec;
#[cfg(feature = "bytemuck-codec")]
pub use codec::{BytemuckCodec, BytemuckSliceCodec, BytemuckVec};
pub use compaction::Compactor;
#[cfg(feature = "var-collections")]
pub use config::CacheConfig;
pub use config::Config;
pub use config::IoBackend;
pub use config::Workload;
pub use const_map::{ConstMap, ConstMapIterView, ConstMapShard};
pub use const_tree::{ConstIter, ConstShard, ConstTree};
#[cfg(feature = "typed-tree")]
pub use counter::{
    CounterCollection, CounterSink, CounterTargets, OnMissingTarget, OneOfBuilder,
    TypedCounterTarget,
};
#[cfg(feature = "encryption")]
pub use crypto::PageCipher;
pub use error::{DbError, DbResult, FencedShard, SchemaMismatchKind, TxFailStage};
pub use fixed::{FixedConfig, FixedMap, FixedTree, FixedWorkload};
pub use flusher::Flusher;
#[cfg(feature = "typed-tree")]
pub use hook::TypedWriteHook;
#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
pub use hook::VarTypedHookAdapter;
#[cfg(feature = "typed-tree")]
pub use hook::ZeroHookAdapter;
pub use hook::{NoHook, WriteHook};
pub use key::{Key, Location};
pub use map_index::{Dir, KeyPage, Page};
/// Deprecated alias — kept one release for downstream. Internal crate code
/// uses `Projected` directly (see `projection::Indexed`).
#[cfg(feature = "typed-tree")]
#[allow(deprecated)]
pub use projection::Indexed;
#[doc(hidden)]
pub use projection::{CountingIndex, FailFirstDeleteIndex, FailNPutsIndex};
#[cfg(feature = "typed-tree")]
pub use projection::{
    DEFAULT_MAX_PROJECTED_BYTES, DEFAULT_MAX_PROJECTED_ROWS, IndexKeyed, IndexTargets, NoEvents,
    PendingProjection, ProjectableIndex, Projected, ProjectionSink,
};
#[cfg(all(feature = "typed-tree", feature = "armour"))]
pub use projection::{EventState, Events};
#[cfg(all(
    feature = "armour",
    feature = "typed-tree",
    feature = "rapira-codec",
    feature = "var-collections"
))]
pub use queue::VarQueueMode;
#[cfg(all(feature = "armour", feature = "typed-tree"))]
pub use queue::{
    DEAD_CLASS, EmitSink, FixedQueueMode, ID_BLOCK, LIVE_CLASS, LeaseToken, LeasedEntry, Queue,
    QueueConfig, QueueDue, QueueKey, QueueMode, QueueSpec, QueueStats, QueueStreamPayload,
    QueueTargets,
};
pub use scope::{
    BoxedRows, BulkScan, ChunkedPage, CoalescedMerge, ConstMapKeyIter, ConstMapRowIter,
    ConstTreeKeyIter, ConstTreeRowIter, MapScan, MappedPage, MergeSorted, OrderedScan, OwnedRows,
    PageSpec, Progress, Scope, StopReason, StrictRows, TreeScan, boxed, merge_sorted, page_chunks,
};
#[cfg(feature = "fjall")]
pub use scope::{LsmKeyIter, LsmRowIter};
#[cfg(feature = "typed-tree")]
pub use scope::{
    MapKeyIter, MapRowIter, TreeKeyIter, TreeRowIter, ZeroMapKeyIter, ZeroMapRowIter,
    ZeroTreeKeyIter, ZeroTreeRowIter,
};
#[cfg(feature = "var-collections")]
pub use scope::{VarMapKeyIter, VarMapRowIter, VarTreeKeyIter, VarTreeRowIter};
#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
pub use scope::{VarTypedMapKeyIter, VarTypedMapRowIter, VarTypedTreeKeyIter, VarTypedTreeRowIter};
pub use shutdown::ShutdownSignal;
pub use sweeper::{SweepPassResult, Sweeper};
pub use tree_meta::{CollectionMeta, TreeMeta};
pub use ttl::{SweepOutcome, TtlHook, TtlPolicy};
#[cfg(feature = "typed-tree")]
pub use typed_map::{TypedMap, TypedMapIterView, TypedMapShard};
#[cfg(feature = "typed-tree")]
pub use typed_tree::{TypedIter, TypedRef, TypedShard, TypedTree};
#[cfg(feature = "typed-tree")]
pub use unique::{
    ClaimSink, UNIQUE_OWNER_KEY_CAP, UniqueIndex, UniqueNamespace, UniqueOwner, UniqueRow,
    UniqueTargets, collection_tag,
};
pub use upsert::{IntoUpsert, Upsert};
#[cfg(feature = "var-collections")]
pub use var_map::{VarMap, VarMapShard};
#[cfg(feature = "var-collections")]
pub use var_tree::{VarIter, VarShard, VarTree};
#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
pub use var_typed_map::{VarTypedMap, VarTypedMapIterView, VarTypedMapShard};
#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
pub use var_typed_tree::{VarTypedIter, VarTypedShard, VarTypedTree};
#[cfg(feature = "typed-tree")]
pub use watch::{
    RecvFuture, WatchDecoder, WatchError, WatchEvent, WatchHook, WatchKind, WatchOptions,
    WatchReceiver, WatchSpec,
};
#[cfg(feature = "typed-tree")]
pub use zero_map::{ZeroMap, ZeroMapIterView, ZeroMapShard};
#[cfg(feature = "typed-tree")]
pub use zero_tree::{ZeroIter, ZeroShard, ZeroTree};

/// Declare a durable queue marker type.
///
/// The marker is emitted `pub`, matching [`unique_index!`]: a library crate has
/// to be able to `pub use` its queues, and a `pub fn` handing back an
/// `Arc<Queue<Jobs>>` would otherwise trip `private_interfaces`. Restrict it
/// where you declare it (a private module, `pub(crate) use`) if you do not want
/// it exported.
#[cfg(all(
    feature = "armour",
    feature = "typed-tree",
    feature = "rapira-codec",
    feature = "var-collections"
))]
#[macro_export]
macro_rules! queue {
    ($name:ident, payload = $payload:ty, name = $lit:literal) => {
        pub struct $name;

        impl $crate::QueueSpec for $name {
            type Payload = $payload;
            type Mode = $crate::FixedQueueMode;

            const NAME: &'static str = $lit;
            const PAYLOAD_NAME: &'static str = concat!($lit, ".payload");
        }
    };
    ($name:ident, payload = $payload:ty, name = $lit:literal, var) => {
        pub struct $name;

        impl $crate::QueueSpec for $name {
            type Payload = $payload;
            type Mode = $crate::VarQueueMode;

            const NAME: &'static str = $lit;
            const PAYLOAD_NAME: &'static str = concat!($lit, ".payload");
        }
    };
}

/// Declare a durable fixed-payload queue marker type.
///
/// Variable-payload queues additionally require the `rapira-codec` and
/// `var-collections` features.
#[cfg(all(
    feature = "armour",
    feature = "typed-tree",
    not(all(feature = "rapira-codec", feature = "var-collections"))
))]
#[macro_export]
macro_rules! queue {
    ($name:ident, payload = $payload:ty, name = $lit:literal) => {
        pub struct $name;

        impl $crate::QueueSpec for $name {
            type Payload = $payload;
            type Mode = $crate::FixedQueueMode;

            const NAME: &'static str = $lit;
            const PAYLOAD_NAME: &'static str = concat!($lit, ".payload");
        }
    };
    ($name:ident, payload = $payload:ty, name = $lit:literal, var) => {
        compile_error!("variable queues require the `rapira-codec` and `var-collections` features");
    };
}
/// Re-exported so [`unique_index!`] can route its generated `zerocopy::…`
/// paths through `$crate::zerocopy` (T10 review F4) — the macro takes no
/// `armour_core`/`zerocopy` value as an argument (unlike [`impl_key_zerocopy!`],
/// whose caller necessarily has both crates in scope because it passes one
/// in), so a downstream crate depending only on `armdb` could not otherwise
/// satisfy the bare `zerocopy::…` paths the expansion names.
#[cfg(feature = "armour")]
pub use zerocopy;

#[doc(hidden)]
pub use disk_loc::DiskLoc;

#[doc(hidden)]
pub use entry::{
    EntryHeader, FLAGS_MASK, SEQUENCE_MASK, SOFT_DELETE_BIT, TOMBSTONE_BIT, compute_crc32,
    entry_size, serialize_entry,
};
#[doc(hidden)]
pub use hint::{HintEntry, hint_entry_size, parse_hint_entries};

/// Test-only re-exports for integration tests (`armdb/tests/*.rs`) that need
/// engine-private constructors unreachable through the public API. Not part
/// of the crate's public contract — items here may change or disappear
/// without a semver bump.
#[cfg(feature = "typed-tree")]
#[doc(hidden)]
pub mod testing {
    pub use crate::unique::unique_owner_for;
    /// `#[cfg(any(test, feature = "test-faults"))]` (T10 review I1): neither
    /// of these is available to a plain `cargo build`/dependent crate — see
    /// their own doc comments in `crate::unique` for why the bypass they
    /// grant must not compile there.
    #[cfg(any(test, feature = "test-faults"))]
    pub use crate::unique::{corrupt_unique_row, force_put};

    /// Build a permanent [`crate::UniqueRow`] from an owner (see
    /// [`unique_owner_for`]) — pairs with [`force_put`] for the schema
    /// validator's orphan test, which needs a well-formed owner row with no
    /// claiming source row: `UniqueIndex` has no public write path at all,
    /// so this is the only way to construct that state directly.
    pub fn unique_row_for(owner: crate::UniqueOwner) -> crate::UniqueRow {
        crate::UniqueRow::new(owner)
    }

    /// Wall-clock milliseconds since the Unix epoch — the same reading
    /// [`crate::txn::Tx::reserve`]'s resolver stamps a reservation's deadline
    /// from (T10 Task 8). Exposed so an integration test can assert a
    /// deadline landed in a sane range without reaching into the crate's
    /// private clock helper directly.
    pub fn now_ms() -> u64 {
        crate::unique::reservation_now_ms()
    }

    /// Test-only observation of the stream buffer order. Task 9 consumes the
    /// private records directly; this keeps the carrier's erased payloads out
    /// of the public API while integration tests prove they were not reordered.
    #[cfg(feature = "armour")]
    pub fn stream_visible_at(sink: &crate::EmitSink<'_>) -> Vec<std::time::SystemTime> {
        sink.emissions()
            .iter()
            .map(|emission| emission.visible_at)
            .collect()
    }

    /// Build a [`crate::ClaimSink`] over `targets` with the given row/byte
    /// budget — `ClaimSink::new` is crate-private (mirrors
    /// [`crate::ProjectionSink`]'s constructor), so integration tests that
    /// exercise the sink directly, independent of a full carrier, reach it
    /// here.
    pub fn claim_sink(
        targets: &crate::UniqueTargets,
        max_rows: usize,
        max_bytes: usize,
    ) -> crate::ClaimSink<'_> {
        crate::ClaimSink::new(targets, max_rows, max_bytes)
    }

    /// Test-facing view of one T10 Task 6 claim op (see [`tx_claims_of`]) —
    /// mirrors `crate::txn::participant::ClaimOp` minus its `participant`
    /// handle, which is crate-private (`TxParticipant`) and cannot cross this
    /// `pub` boundary. `is_claim`/`is_release` are precomputed from the
    /// source `ClaimOp` at conversion time (see `From` below) rather than
    /// re-matching a locally stored `ClaimKind` — one interpretation of
    /// "what kind is this", on `ClaimOp` itself, not two.
    #[cfg(feature = "armour")]
    pub struct TxClaimOp {
        pub namespace: &'static str,
        pub key: Vec<u8>,
        pub owner: crate::UniqueOwner,
        is_claim: bool,
        is_release: bool,
    }

    #[cfg(feature = "armour")]
    impl TxClaimOp {
        pub fn is_claim(&self) -> bool {
            self.is_claim
        }
        pub fn is_release(&self) -> bool {
            self.is_release
        }
    }

    #[cfg(feature = "armour")]
    impl From<crate::txn::participant::ClaimOp> for TxClaimOp {
        fn from(op: crate::txn::participant::ClaimOp) -> Self {
            let is_claim = op.is_claim();
            let is_release = op.is_release();
            Self {
                namespace: op.namespace,
                key: op.key,
                owner: op.owner,
                is_claim,
                is_release,
            }
        }
    }

    /// Claim ops a `TypedMap` source's `tx_claims` would emit for one
    /// decided write (T10 Task 6) — `TxParticipant::tx_claims` and `ClaimOp`
    /// are both crate-private, so integration tests that exercise the
    /// commit-plan seam directly (ahead of Task 7's resolver) reach it here.
    #[cfg(feature = "armour")]
    pub fn tx_claims_of<K, T, C, H>(
        map: &crate::TypedMap<K, T, C, H>,
        key: &K,
        old: Option<&[u8]>,
        new: Option<&[u8]>,
    ) -> crate::DbResult<Vec<TxClaimOp>>
    where
        K: crate::Key + Send + Sync + std::hash::Hash + Eq + 'static,
        // `CollectionMeta` (public), not `TxCollectionName` (crate-private —
        // would leak a private bound through this `pub fn`'s signature):
        // `CollectionMeta: GetType` and the blanket
        // `impl<T: CollectionMeta> TxCollectionName for T` together satisfy
        // `TypedMap<K, T, C, H>: TxParticipant`'s real bound without naming it.
        T: crate::CollectionMeta + Send + Sync + 'static,
        C: crate::codec::Codec<T> + Sync + 'static,
        H: crate::TypedWriteHook<K, T> + 'static,
    {
        use crate::txn::participant::TxParticipant;
        let key_bytes = key.as_bytes().to_vec();
        let ops = map.tx_claims(&key_bytes, old, new)?;
        Ok(ops.into_iter().map(TxClaimOp::from).collect())
    }

    /// Every rank-1 participant a `TypedMap` source's write can reach — the
    /// collection names of its declared secondary-index targets, counter
    /// targets, *and* unique-namespace targets alike
    /// (`tx_preplan_projection_targets`, T9/T10), all preplanned into the
    /// commit whether or not this call's row actually claims/indexes/counts.
    /// Callers that only care about the namespace half filter the result
    /// themselves (as the test using this does, via `.contains`).
    #[cfg(feature = "armour")]
    pub fn tx_preplan_names<K, T, C, H>(
        map: &crate::TypedMap<K, T, C, H>,
    ) -> crate::DbResult<Vec<&'static str>>
    where
        K: crate::Key + Send + Sync + std::hash::Hash + Eq,
        T: Send + Sync,
        C: crate::codec::Codec<T> + Sync,
        H: crate::TypedWriteHook<K, T>,
    {
        Ok(map
            .tx_preplan_projection_targets()?
            .into_iter()
            .map(|p| p.name())
            .collect())
    }
}

use std::mem::size_of;

pub(crate) fn shard_for_key<K: Key>(
    key: &K,
    shard_prefix_bits: usize,
    shard_count: usize,
) -> usize {
    if shard_prefix_bits == 0 || shard_prefix_bits >= size_of::<K>() * 8 {
        let hash = xxhash_rust::xxh3::xxh3_64(key.as_bytes());
        return (hash as usize) % shard_count;
    }

    let full_bytes = shard_prefix_bits / 8;
    let extra_bits = shard_prefix_bits % 8;

    let hash = if extra_bits == 0 {
        xxhash_rust::xxh3::xxh3_64(&key.as_bytes()[..full_bytes])
    } else {
        let mut buf = K::zeroed();
        buf.as_bytes_mut()[..full_bytes + 1].copy_from_slice(&key.as_bytes()[..full_bytes + 1]);
        let mask = !((1u8 << (8 - extra_bits)) - 1);
        buf.as_bytes_mut()[full_bytes] = key.as_bytes()[full_bytes] & mask;
        xxhash_rust::xxh3::xxh3_64(&buf.as_bytes()[..full_bytes + 1])
    };

    (hash as usize) % shard_count
}

/// Action returned by the `migrate()` callback for each entry.
pub enum MigrateAction<V> {
    /// Leave this entry unchanged.
    Keep,
    /// Replace the value.
    Update(V),
    /// Delete this entry.
    Delete,
}

/// Expands to `ZeroTree<<V as CollectionMeta>::SelfId, { size_of::<V>() }, V [, H, D]>`.
#[cfg(feature = "typed-tree")]
#[macro_export]
macro_rules! zero_tree {
    ($V:ty) => {
        $crate::ZeroTree<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $V,
            $crate::TtlHook<$V, $crate::NoHook>,
        >
    };
    ($V:ty, fixed) => {
        $crate::ZeroTree<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $V,
            $crate::TtlHook<$V, $crate::NoHook>,
            $crate::durability::Fixed,
        >
    };
    ($V:ty, $H:ty) => {
        $crate::ZeroTree<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $V,
            $crate::TtlHook<$V, $H>,
            $crate::durability::Bitcask,
        >
    };
    ($V:ty, $H:ty, fixed) => {
        $crate::ZeroTree<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $V,
            $crate::TtlHook<$V, $H>,
            $crate::durability::Fixed,
        >
    };
}

/// Expands to `ZeroMap<<V as CollectionMeta>::SelfId, { size_of::<V>() }, V [, H, D]>`.
#[cfg(feature = "typed-tree")]
#[macro_export]
macro_rules! zero_map {
    ($V:ty) => {
        $crate::ZeroMap<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $V,
            $crate::TtlHook<$V, $crate::NoHook>,
        >
    };
    ($V:ty, fixed) => {
        $crate::ZeroMap<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $V,
            $crate::TtlHook<$V, $crate::NoHook>,
            $crate::durability::Fixed,
        >
    };
    ($V:ty, $H:ty) => {
        $crate::ZeroMap<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $V,
            $crate::TtlHook<$V, $H>,
            $crate::durability::Bitcask,
        >
    };
    ($V:ty, $H:ty, fixed) => {
        $crate::ZeroMap<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $V,
            $crate::TtlHook<$V, $H>,
            $crate::durability::Fixed,
        >
    };
}

/// Expands to `ConstTree<<V as CollectionMeta>::SelfId, { size_of::<V>() } [, H, D]>`.
#[macro_export]
macro_rules! const_tree {
    ($V:ty) => {
        $crate::ConstTree<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
        >
    };
    ($V:ty, fixed) => {
        $crate::ConstTree<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $crate::NoHook,
            $crate::durability::Fixed,
        >
    };
    ($V:ty, $H:ty) => {
        $crate::ConstTree<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $H,
            $crate::durability::Bitcask,
        >
    };
    ($V:ty, $H:ty, fixed) => {
        $crate::ConstTree<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $H,
            $crate::durability::Fixed,
        >
    };
}

/// Expands to `ConstMap<<V as CollectionMeta>::SelfId, { size_of::<V>() } [, H, D]>`.
#[macro_export]
macro_rules! const_map {
    ($V:ty) => {
        $crate::ConstMap<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
        >
    };
    ($V:ty, fixed) => {
        $crate::ConstMap<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $crate::NoHook,
            $crate::durability::Fixed,
        >
    };
    ($V:ty, $H:ty) => {
        $crate::ConstMap<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $H,
            $crate::durability::Bitcask,
        >
    };
    ($V:ty, $H:ty, fixed) => {
        $crate::ConstMap<
            <$V as $crate::CollectionMeta>::SelfId,
            { ::std::mem::size_of::<$V>() },
            $H,
            $crate::durability::Fixed,
        >
    };
}

/// Expands to `TypedTree<<V as CollectionMeta>::SelfId, V, C [, H]>`.
#[cfg(feature = "typed-tree")]
#[macro_export]
macro_rules! typed_tree {
    ($V:ty, $C:ty) => {
        $crate::TypedTree<
            <$V as $crate::CollectionMeta>::SelfId,
            $V,
            $C,
            $crate::TtlHook<$V, $crate::NoHook>,
        >
    };
    ($V:ty, $C:ty, $H:ty) => {
        $crate::TypedTree<
            <$V as $crate::CollectionMeta>::SelfId,
            $V,
            $C,
            $crate::TtlHook<$V, $H>,
        >
    };
}

/// Expands to `TypedMap<<V as CollectionMeta>::SelfId, V, C [, H]>`.
#[cfg(feature = "typed-tree")]
#[macro_export]
macro_rules! typed_map {
    ($V:ty, $C:ty) => {
        $crate::TypedMap<
            <$V as $crate::CollectionMeta>::SelfId,
            $V,
            $C,
            $crate::TtlHook<$V, $crate::NoHook>,
        >
    };
    ($V:ty, $C:ty, $H:ty) => {
        $crate::TypedMap<
            <$V as $crate::CollectionMeta>::SelfId,
            $V,
            $C,
            $crate::TtlHook<$V, $H>,
        >
    };
}

/// Expands to `VarTree<<V as CollectionMeta>::SelfId [, H]>`.
#[cfg(feature = "var-collections")]
#[macro_export]
macro_rules! var_tree {
    ($V:ty) => {
        $crate::VarTree<<$V as $crate::CollectionMeta>::SelfId>
    };
    ($V:ty, $H:ty) => {
        $crate::VarTree<<$V as $crate::CollectionMeta>::SelfId, $H>
    };
}

/// Expands to `VarMap<<V as CollectionMeta>::SelfId [, H]>`.
#[cfg(feature = "var-collections")]
#[macro_export]
macro_rules! var_map {
    ($V:ty) => {
        $crate::VarMap<<$V as $crate::CollectionMeta>::SelfId>
    };
    ($V:ty, $H:ty) => {
        $crate::VarMap<<$V as $crate::CollectionMeta>::SelfId, $H>
    };
}

/// Expands to `VarTypedTree<<V as CollectionMeta>::SelfId, V, C [, H]>`.
#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
#[macro_export]
macro_rules! var_typed_tree {
    ($V:ty, $C:ty) => {
        $crate::VarTypedTree<
            <$V as $crate::CollectionMeta>::SelfId,
            $V,
            $C,
            $crate::TtlHook<$V, $crate::NoHook>,
        >
    };
    ($V:ty, $C:ty, $H:ty) => {
        $crate::VarTypedTree<
            <$V as $crate::CollectionMeta>::SelfId,
            $V,
            $C,
            $crate::TtlHook<$V, $H>,
        >
    };
}

/// Expands to `VarTypedMap<<V as CollectionMeta>::SelfId, V, C [, H]>`.
#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
#[macro_export]
macro_rules! var_typed_map {
    ($V:ty, $C:ty) => {
        $crate::VarTypedMap<
            <$V as $crate::CollectionMeta>::SelfId,
            $V,
            $C,
            $crate::TtlHook<$V, $crate::NoHook>,
        >
    };
    ($V:ty, $C:ty, $H:ty) => {
        $crate::VarTypedMap<
            <$V as $crate::CollectionMeta>::SelfId,
            $V,
            $C,
            $crate::TtlHook<$V, $H>,
        >
    };
}