siamesedb 0.1.23

The simple local key-value store.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
use super::super::super::DbMapKeyType;
use super::super::{
    CountOfPerSize, FileBufSizeParam, FileDbParams, KeysCountStats, LengthStats, RecordSizeStats,
};
use super::dbxxx::FileDbXxxInner;
use super::piece::PieceMgr;
use super::semtype::*;
use super::tr::IdxNode;
use super::vfile::VarFile;
use rabuf::{SmallRead, SmallWrite};
use std::cell::RefCell;
use std::convert::TryInto;
use std::fs::OpenOptions;
use std::io::{Read, Result, Write};
use std::path::Path;
use std::rc::Rc;

type HeaderSignature = [u8; 8];

//const CHUNK_SIZE: u32 = 4 * 1024;
//const CHUNK_SIZE: u32 = 4 * 4 * 1024;
//const CHUNK_SIZE: u32 = 4 * 4 * 4 * 1024;
const CHUNK_SIZE: u32 = 128 * 1024;
const IDX_HEADER_SZ: u64 = 128;
const IDX_HEADER_SIGNATURE: HeaderSignature = [b's', b'i', b'a', b'm', b'd', b'b', b'T', 0u8];
const IDX_HEADER_TOP_NODE_OFFSET: u64 = 16;

#[cfg(not(feature = "node_cache"))]
use std::marker::PhantomData;

#[cfg(feature = "node_cache")]
use super::nc::NodeCache;

#[cfg(not(feature = "node_cache"))]
#[derive(Debug)]
pub struct VarFileNodeCache(pub VarFile, PhantomData<i32>, NodePieceOffset);

#[cfg(feature = "node_cache")]
#[derive(Debug)]
pub struct VarFileNodeCache(pub VarFile, NodeCache, NodePieceOffset);

#[derive(Debug, Clone)]
pub struct IdxFile(pub Rc<RefCell<VarFileNodeCache>>);

impl IdxFile {
    pub fn open_with_params<P: AsRef<Path>>(
        path: P,
        ks_name: &str,
        sig2: HeaderSignature,
        params: &FileDbParams,
    ) -> Result<Self> {
        let piece_mgr = PieceMgr::new(&NODE_SIZE_FREE_OFFSET, &NODE_SIZE_ARY);
        let mut pb = path.as_ref().to_path_buf();
        pb.push(format!("{}.idx", ks_name));
        let std_file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(pb)?;
        let mut file = match params.idx_buf_size {
            FileBufSizeParam::Size(val) => {
                let idx_buf_chunk_size = CHUNK_SIZE;
                let idx_buf_num_chunks = val / idx_buf_chunk_size;
                VarFile::with_capacity(
                    piece_mgr,
                    "idx",
                    std_file,
                    idx_buf_chunk_size,
                    idx_buf_num_chunks.try_into().unwrap(),
                )?
            }
            FileBufSizeParam::PerMille(val) => {
                VarFile::with_per_mille(piece_mgr, "idx", std_file, CHUNK_SIZE, val)?
            }
            FileBufSizeParam::Auto => VarFile::new(piece_mgr, "idx", std_file)?,
        };
        let file_length: NodePieceOffset = file.seek_to_end()?;
        //
        #[cfg(not(feature = "node_cache"))]
        let mut file_nc = VarFileNodeCache(file, PhantomData, NodePieceOffset::new(0));
        #[cfg(feature = "node_cache")]
        let mut file_nc = VarFileNodeCache(file, NodeCache::new(), NodePieceOffset::new(0));
        //
        if file_length.is_zero() {
            write_idxf_init_header(&mut file_nc.0, sig2)?;
            // writing top node
            let top_node = IdxNode::new(NodePieceOffset::new(IDX_HEADER_SZ));
            let new_top_node_ = file_nc.write_node(top_node, true)?;
            debug_assert!(new_top_node_.get_ref().offset() == NodePieceOffset::new(IDX_HEADER_SZ));
            file_nc.2 = new_top_node_.get_ref().offset();
        } else {
            check_idxf_header(&mut file_nc.0, sig2)?;
            let top_node_offset = file_nc.0.read_top_node_offset()?;
            file_nc.2 = top_node_offset;
        }
        //
        Ok(Self(Rc::new(RefCell::new(file_nc))))
    }
    #[inline]
    pub fn read_fill_buffer(&self) -> Result<()> {
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.0.read_fill_buffer()
    }
    #[inline]
    pub fn flush(&self) -> Result<()> {
        let mut locked = RefCell::borrow_mut(&self.0);
        #[cfg(feature = "node_cache")]
        locked.flush_node_cache()?;
        locked.0.flush()
    }
    #[inline]
    pub fn sync_all(&self) -> Result<()> {
        let mut locked = RefCell::borrow_mut(&self.0);
        #[cfg(feature = "node_cache")]
        locked.flush_node_cache_clear()?;
        locked.0.sync_all()
    }
    #[inline]
    pub fn sync_data(&self) -> Result<()> {
        let mut locked = RefCell::borrow_mut(&self.0);
        #[cfg(feature = "node_cache")]
        locked.flush_node_cache_clear()?;
        locked.0.sync_data()
    }
    #[cfg(feature = "buf_stats")]
    #[inline]
    pub fn buf_stats(&self) -> Vec<(String, i64)> {
        let locked = RefCell::borrow(&self.0);
        locked.0.buf_stats()
    }
    //
    #[inline]
    pub fn read_top_node(&self) -> Result<IdxNode> {
        let top_node_offset = {
            let locked = RefCell::borrow(&self.0);
            locked.2
            /*
             */
            /*
            let mut locked = RefCell::borrow_mut(&self.0);
            locked.0.read_top_node_offset()?
            */
        };
        self.read_node(top_node_offset)
    }
    pub fn write_top_node(&self, node: IdxNode) -> Result<IdxNode> {
        if node.get_ref().offset().is_zero() {
            let new_top_node = self.write_new_node(node)?;
            let new_top_node_offset = new_top_node.get_ref().offset();
            {
                let mut locked = RefCell::borrow_mut(&self.0);
                if new_top_node_offset != locked.2 {
                    locked.0.write_top_node_offset(new_top_node_offset)?;
                    locked.2 = new_top_node_offset;
                }
            }
            Ok(new_top_node)
        } else {
            let top_node_offset = {
                let locked = RefCell::borrow(&self.0);
                locked.2
                /*
                let mut locked = RefCell::borrow_mut(&self.0);
                locked.0.read_top_node_offset()?
                */
            };
            let new_top_node = self.write_node(node)?;
            let new_top_node_offset = new_top_node.get_ref().offset();
            if new_top_node_offset != top_node_offset {
                let mut locked = RefCell::borrow_mut(&self.0);
                if locked.2 != new_top_node_offset {
                    locked.0.write_top_node_offset(new_top_node_offset)?;
                    locked.2 = new_top_node_offset;
                }
            }
            Ok(new_top_node)
        }
    }
    //
    #[inline]
    pub fn read_node(&self, offset: NodePieceOffset) -> Result<IdxNode> {
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.read_node(offset)
    }
    #[inline]
    pub fn write_node(&self, node: IdxNode) -> Result<IdxNode> {
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.write_node(node, false)
    }
    #[inline]
    pub fn write_new_node(&self, mut node: IdxNode) -> Result<IdxNode> {
        node.get_mut().set_offset({
            let mut locked = RefCell::borrow_mut(&self.0);
            locked.0.seek_to_end()?
        });
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.write_node(node, true)
    }
    #[inline]
    pub fn delete_node(&self, node: IdxNode) -> Result<NodePieceSize> {
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.delete_node(node)
    }
    #[inline]
    pub fn _read_node_only_keys_count(&self, offset: NodePieceOffset) -> Result<KeysCount> {
        //let mut locked = RefCell::borrow_mut(&self.0);
        //let idx_node = locked.read_node(offset)?;
        let idx_node = self.read_node(offset)?;
        #[cfg(feature = "siamese_debug")]
        let keys_len = idx_node.get_ref().keys_len().try_into().unwrap();
        #[cfg(not(feature = "siamese_debug"))]
        let keys_len = idx_node.get_ref().keys_len() as u16;
        //
        Ok(KeysCount::new(keys_len))
    }
}

// for debug
impl IdxFile {
    pub fn graph_string(&self) -> Result<String> {
        let top_node = self.read_top_node()?;
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.graph_string("", &top_node)
    }
    pub fn graph_string_with_key_string<KT>(&self, dbxxx: &FileDbXxxInner<KT>) -> Result<String>
    where
        KT: DbMapKeyType + std::fmt::Display,
    {
        let top_node = self.read_top_node()?;
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.graph_string_with_key_string("", &top_node, dbxxx)
    }
    // check the index tree is balanced
    pub fn is_balanced(&self, node: &IdxNode) -> Result<bool> {
        let node_offset = node.get_ref().downs_get(0);
        let h = if !node_offset.is_zero() {
            let node1 = self.read_node(node_offset)?;
            if !self.is_balanced(&node1)? {
                return Ok(false);
            }
            self.height(&node1)?
        } else {
            0
        };
        for i in 1..node.get_ref().downs_len() {
            let node_offset = node.get_ref().downs_get(i);
            let hh = if !node_offset.is_zero() {
                let node1 = self.read_node(node_offset)?;
                if !self.is_balanced(&node1)? {
                    return Ok(false);
                }
                self.height(&node1)?
            } else {
                0
            };
            if h != hh {
                return Ok(false);
            }
        }
        Ok(true)
    }
    // return height of node tree
    fn height(&self, node: &IdxNode) -> Result<u32> {
        let node_offset = node.get_ref().downs_get(0);
        let mut mx = if !node_offset.is_zero() {
            let node1 = self.read_node(node_offset)?;
            self.height(&node1)?
        } else {
            0
        };
        for i in 1..node.get_ref().downs_len() {
            let node_offset = node.get_ref().downs_get(i);
            let h = if !node_offset.is_zero() {
                let node1 = self.read_node(node_offset)?;
                self.height(&node1)?
            } else {
                0
            };
            if h > mx {
                mx = h;
            }
        }
        Ok(1 + mx)
    }
    //
    pub fn is_mst_valid<KT>(&self, node: &IdxNode, dbxxx: &FileDbXxxInner<KT>) -> Result<bool>
    where
        KT: DbMapKeyType + std::fmt::Display + std::default::Default + std::cmp::PartialOrd,
    {
        if node.get_ref().keys_is_empty() {
            return Ok(true);
        }
        #[cfg(not(feature = "tr_has_short_key"))]
        let key_offset = node.get_ref().keys_get(0);
        #[cfg(feature = "tr_has_short_key")]
        let (key_offset, _short_key) = node.get_ref().keys_get(0);
        //
        let key_string = if !key_offset.is_zero() {
            dbxxx.load_key_data(key_offset)?
        } else {
            Default::default()
        };
        let node_offset = node.get_ref().downs_get(0);
        if !node_offset.is_zero() {
            let node1 = self.read_node(node_offset)?;
            if !self.is_small(&key_string, &node1, dbxxx)? {
                return Ok(false);
            }
            if !self.is_mst_valid(&node1, dbxxx)? {
                return Ok(false);
            }
        }
        //
        for i in 1..node.get_ref().keys_len() {
            #[cfg(not(feature = "tr_has_short_key"))]
            let key_offset1 = node.get_ref().keys_get(i - 1);
            #[cfg(feature = "tr_has_short_key")]
            let (key_offset1, _short_key1) = node.get_ref().keys_get(i - 1);
            //
            #[cfg(not(feature = "tr_has_short_key"))]
            let key_offset2 = node.get_ref().keys_get(i);
            #[cfg(feature = "tr_has_short_key")]
            let (key_offset2, _short_key2) = node.get_ref().keys_get(i);
            //
            let node_offset = node.get_ref().downs_get(i);
            //
            let key_string1 = if !key_offset1.is_zero() {
                dbxxx.load_key_data(key_offset1)?
            } else {
                Default::default()
            };
            let key_string2 = if !key_offset2.is_zero() {
                dbxxx.load_key_data(key_offset2)?
            } else {
                Default::default()
            };
            if key_string1 >= key_string2 {
                return Ok(false);
            }
            if !node_offset.is_zero() {
                let node1 = self.read_node(node_offset)?;
                if !self.is_between(&key_string1, &key_string2, &node1, dbxxx)? {
                    return Ok(false);
                }
                if !self.is_mst_valid(&node1, dbxxx)? {
                    return Ok(false);
                }
            }
        }
        //
        #[cfg(not(feature = "tr_has_short_key"))]
        let key_offset = node.get_ref().keys_get(node.get_ref().keys_len() - 1);
        #[cfg(feature = "tr_has_short_key")]
        let (key_offset, _short_key) = node.get_ref().keys_get(node.get_ref().keys_len() - 1);
        //
        let node_offset = node.get_ref().downs_get(node.get_ref().keys_len());
        if !node_offset.is_zero() {
            let node1 = self.read_node(node_offset)?;
            if !key_offset.is_zero() {
                let key_string = dbxxx.load_key_data(key_offset)?;
                if !self.is_large(&key_string, &node1, dbxxx)? {
                    return Ok(false);
                }
            }
            if !self.is_mst_valid(&node1, dbxxx)? {
                return Ok(false);
            }
        }
        //
        Ok(true)
    }
    //
    fn is_small<KT>(&self, key: &KT, node: &IdxNode, dbxxx: &FileDbXxxInner<KT>) -> Result<bool>
    where
        KT: DbMapKeyType + std::fmt::Display + std::default::Default + std::cmp::PartialOrd,
    {
        for i in 0..node.get_ref().keys_len() {
            let node_offset = node.get_ref().downs_get(i);
            if !node_offset.is_zero() {
                let node1 = self.read_node(node_offset)?;
                if !self.is_small(key, &node1, dbxxx)? {
                    return Ok(false);
                }
            }
            #[cfg(not(feature = "tr_has_short_key"))]
            let key_offset = node.get_ref().keys_get(i);
            #[cfg(feature = "tr_has_short_key")]
            let (key_offset, _short_key) = node.get_ref().keys_get(i);
            //
            if !key_offset.is_zero() {
                let key_string1 = dbxxx.load_key_data(key_offset)?;
                if key <= &key_string1 {
                    return Ok(false);
                }
            }
        }
        //
        let node_offset = node.get_ref().downs_get(node.get_ref().keys_len());
        if !node_offset.is_zero() {
            let node1 = self.read_node(node_offset)?;
            if !self.is_small(key, &node1, dbxxx)? {
                return Ok(false);
            }
        }
        //
        Ok(true)
    }
    fn is_between<KT>(
        &self,
        key1: &KT,
        key2: &KT,
        node: &IdxNode,
        dbxxx: &FileDbXxxInner<KT>,
    ) -> Result<bool>
    where
        KT: DbMapKeyType + std::fmt::Display + std::default::Default + std::cmp::PartialOrd,
    {
        for i in 0..node.get_ref().keys_len() {
            let node_offset = node.get_ref().downs_get(i);
            if !node_offset.is_zero() {
                let node1 = self.read_node(node_offset)?;
                if !self.is_between(key1, key2, &node1, dbxxx)? {
                    return Ok(false);
                }
            }
            #[cfg(not(feature = "tr_has_short_key"))]
            let key_offset11 = node.get_ref().keys_get(i);
            #[cfg(feature = "tr_has_short_key")]
            let (key_offset11, _short_key11) = node.get_ref().keys_get(i);
            //
            if !key_offset11.is_zero() {
                let ket_string11 = dbxxx.load_key_data(key_offset11)?;
                if key1 >= &ket_string11 {
                    return Ok(false);
                }
                if key2 <= &ket_string11 {
                    return Ok(false);
                }
            }
        }
        //
        let node_offset = node.get_ref().downs_get(node.get_ref().keys_len());
        if !node_offset.is_zero() {
            let node1 = self.read_node(node_offset)?;
            if !self.is_between(key1, key2, &node1, dbxxx)? {
                return Ok(false);
            }
        }
        //
        Ok(true)
    }
    fn is_large<KT>(&self, key: &KT, node: &IdxNode, dbxxx: &FileDbXxxInner<KT>) -> Result<bool>
    where
        KT: DbMapKeyType + std::fmt::Display + std::default::Default + std::cmp::PartialOrd,
    {
        for i in 0..node.get_ref().keys_len() {
            let node_offset = node.get_ref().downs_get(i);
            if !node_offset.is_zero() {
                let node1 = self.read_node(node_offset)?;
                if !self.is_large(key, &node1, dbxxx)? {
                    return Ok(false);
                }
            }
            #[cfg(not(feature = "tr_has_short_key"))]
            let key_offset = node.get_ref().keys_get(i);
            #[cfg(feature = "tr_has_short_key")]
            let (key_offset, _short_key) = node.get_ref().keys_get(i);
            //
            if !key_offset.is_zero() {
                let ket_string1 = dbxxx.load_key_data(key_offset)?;
                if key >= &ket_string1 {
                    return Ok(false);
                }
            }
        }
        //
        let node_offset = node.get_ref().downs_get(node.get_ref().keys_len());
        if !node_offset.is_zero() {
            let node1 = self.read_node(node_offset)?;
            if !self.is_large(key, &node1, dbxxx)? {
                return Ok(false);
            }
        }
        //
        Ok(true)
    }
    //
    pub fn is_dense(&self, top_node: &IdxNode) -> Result<bool> {
        if top_node.get_ref().downs_is_empty() {
            return Ok(true);
        }
        let n = top_node.get_ref().downs_len();
        if n > NODE_SLOTS_MAX as usize {
            return Ok(false);
        }
        if n == 1 && !top_node.get_ref().downs_get(0).is_zero() {
            return Ok(false);
        }
        for i in 0..n {
            let node_offset = top_node.get_ref().downs_get(i);
            if !node_offset.is_zero() {
                let node1 = self.read_node(node_offset)?;
                if !self.is_dense_half(&node1)? {
                    return Ok(false);
                }
            }
        }
        //
        Ok(true)
    }
    fn is_dense_half(&self, node: &IdxNode) -> Result<bool> {
        let n = node.get_ref().downs_len();
        if n < NODE_SLOTS_MAX_HALF as usize || n > NODE_SLOTS_MAX as usize {
            return Ok(false);
        }
        for i in 0..n {
            let node_offset = node.get_ref().downs_get(i);
            if !node_offset.is_zero() {
                let node1 = self.read_node(node_offset)?;
                if !self.is_dense_half(&node1)? {
                    return Ok(false);
                }
            }
        }
        //
        Ok(true)
    }
    pub fn depth_of_node_tree(&self, node: &IdxNode) -> Result<u64> {
        let mut cnt = 1;
        if !node.get_ref().downs_is_empty() {
            let node_offset = node.get_ref().downs_get(0);
            if !node_offset.is_zero() {
                let node1 = self.read_node(node_offset)?;
                cnt += self.depth_of_node_tree(&node1)?;
            }
        }
        //
        Ok(cnt)
    }
    pub fn count_of_free_node(&self) -> Result<Vec<(u32, u64)>> {
        let sz_ary = NODE_SIZE_ARY;
        //
        let mut vec = Vec::new();
        let mut locked = RefCell::borrow_mut(&self.0);
        for node_size in sz_ary {
            let cnt = locked
                .0
                .count_of_free_piece_list(NodePieceSize::new(node_size))?;
            vec.push((node_size, cnt));
        }
        Ok(vec)
    }
    //
    pub fn keys_count_stats(&self) -> Result<KeysCountStats> {
        let mut keys_count_stats = KeysCountStats::default();
        //
        let top_node = self.read_top_node()?;
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.idx_keys_count_stats(&top_node, &mut keys_count_stats)?;
        //
        Ok(keys_count_stats)
    }
    //
    pub fn count_of_used_node<F>(
        &self,
        read_key_value_piece_size_func: F,
    ) -> Result<(CountOfPerSize, CountOfPerSize, CountOfPerSize)>
    where
        F: Fn(KeyPieceOffset) -> Result<(KeyPieceSize, ValuePieceSize)> + std::marker::Copy,
    {
        let mut node_vec = Vec::new();
        for node_size in NODE_SIZE_ARY {
            let cnt = 0;
            node_vec.push((node_size, cnt));
        }
        //
        let mut key_piece_vec = Vec::new();
        for piece_size in super::key::REC_SIZE_ARY {
            let cnt = 0;
            key_piece_vec.push((piece_size, cnt));
        }
        let mut value_piece_vec = Vec::new();
        for piece_size in super::val::REC_SIZE_ARY {
            let cnt = 0;
            value_piece_vec.push((piece_size, cnt));
        }
        //
        let top_node = self.read_top_node()?;
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.count_of_used_node(
            &top_node,
            &mut node_vec,
            &mut key_piece_vec,
            &mut value_piece_vec,
            read_key_value_piece_size_func,
        )?;
        //
        Ok((key_piece_vec, value_piece_vec, node_vec))
    }
    //
    pub fn piece_size_stats<KV, F>(&self, read_piece_size_func: F) -> Result<RecordSizeStats<KV>>
    where
        F: Fn(KeyPieceOffset) -> Result<PieceSize<KV>> + std::marker::Copy,
        KV: Default + Copy + Ord,
    {
        let mut piece_size_stats = RecordSizeStats::default();
        //
        let top_node = self.read_top_node()?;
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.idx_piece_size_stats(&top_node, &mut piece_size_stats, read_piece_size_func)?;
        //
        Ok(piece_size_stats)
    }
    //
    pub fn length_stats<KV: Default + Copy + Ord, F>(
        &self,
        read_key_length_func: F,
    ) -> Result<LengthStats<KV>>
    where
        F: Fn(KeyPieceOffset) -> Result<Length<KV>> + std::marker::Copy,
    {
        let mut kv_length_stats = LengthStats::<KV>::default();
        //
        let top_node = self.read_top_node()?;
        let mut locked = RefCell::borrow_mut(&self.0);
        locked.idx_kv_length_stats(&top_node, &mut kv_length_stats, read_key_length_func)?;
        //
        Ok(kv_length_stats)
    }
}

/**
write initiale header to file.

## header map

The db index header size is 128 bytes.

```text
+--------+-------+-------------+---------------------------+
| offset | bytes | name        | comment                   |
+--------+-------+-------------+---------------------------+
| 0      | 8     | signature1  | b"siamdbT\0"              |
| 8      | 8     | signature2  | 8 bytes type signature    |
| 16     | 8     | top node    | offset of top node        |
| 24     | 8     | free1 off   | offset of free 1st list   |
| 32     | 8     | free2 off   | offset of free 2ndlist    |
| 40     | 8     | free3 off   | offset of free 3rd list   |
| 48     | 8     | free4 off   | offset of free 4th list   |
| 56     | 8     | free5 off   | offset of free 5th list   |
| 64     | 8     | free6 off   | offset of free 6th list   |
| 72     | 8     | free7 off   | offset of free 7th list   |
| 80     | 8     | free8 off   | offset of free 8th list   |
| 88     | 40    | reserve1    |                           |
+--------+-------+-------------+---------------------------+
```

- signature1: always fixed 8 bytes
- signature2: 8 bytes type signature

*/

fn write_idxf_init_header(file: &mut VarFile, signature2: HeaderSignature) -> Result<()> {
    file.seek_from_start(NodePieceOffset::new(0))?;
    // signature1
    file.write_all(&IDX_HEADER_SIGNATURE)?;
    // signature2
    file.write_all(&signature2)?;
    // root offset
    file.write_u64_le(IDX_HEADER_SZ)?;
    // free1 .. rserve1
    file.write_all(&[0u8; 104])?;
    //
    Ok(())
}

fn check_idxf_header(file: &mut VarFile, signature2: HeaderSignature) -> Result<()> {
    file.seek_from_start(NodePieceOffset::new(0))?;
    // signature1
    let mut sig1 = [0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8];
    file.read_exact(&mut sig1)?;
    assert!(sig1 == IDX_HEADER_SIGNATURE, "invalid header signature1");
    // signature2
    let mut sig2 = [0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8];
    file.read_exact(&mut sig2)?;
    assert!(
        sig2 == signature2,
        "invalid header signature2, type signature: {:?}",
        sig2
    );
    // top node offset
    let _top_node_offset = file.read_u64_le()?;
    assert!(_top_node_offset != 0, "invalid root offset");
    //
    Ok(())
}

impl VarFile {
    pub fn read_top_node_offset(&mut self) -> Result<NodePieceOffset> {
        self.seek_from_start(NodePieceOffset::new(IDX_HEADER_TOP_NODE_OFFSET))?;
        self.read_u64_le().map(NodePieceOffset::new)
    }
    fn write_top_node_offset(&mut self, offset: NodePieceOffset) -> Result<()> {
        self.seek_from_start(NodePieceOffset::new(IDX_HEADER_TOP_NODE_OFFSET))?;
        self.write_u64_le(offset.into())?;
        Ok(())
    }
}

const NODE_SIZE_FREE_OFFSET_1ST: u64 = 24;

const NODE_SIZE_FREE_OFFSET: [u64; 8] = [
    NODE_SIZE_FREE_OFFSET_1ST,
    NODE_SIZE_FREE_OFFSET_1ST + 8,
    NODE_SIZE_FREE_OFFSET_1ST + 8 * 2,
    NODE_SIZE_FREE_OFFSET_1ST + 8 * 3,
    NODE_SIZE_FREE_OFFSET_1ST + 8 * 4,
    NODE_SIZE_FREE_OFFSET_1ST + 8 * 5,
    NODE_SIZE_FREE_OFFSET_1ST + 8 * 6,
    NODE_SIZE_FREE_OFFSET_1ST + 8 * 7,
];

#[cfg(feature = "small_node_slots")]
pub const NODE_SLOTS_MAX: u16 = 6;

#[cfg(feature = "small_node_slots")]
const NODE_SIZE_ARY: [u32; 8] = [
    16,
    16 * 2,
    16 * 2 * 2,
    16 * 2 * 3,
    16 * 2 * 4,
    16 * 2 * 5,
    16 * 2 * 6,
    16 * 2 * 7,
];

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_u32u32")]
//pub const NODE_SLOTS_MAX: u16 = 1023;
//pub const NODE_SLOTS_MAX: u16 = 511;
//pub const NODE_SLOTS_MAX: u16 = 255;
//pub const NODE_SLOTS_MAX: u16 = 127;
//pub const NODE_SLOTS_MAX: u16 = 63;
//pub const NODE_SLOTS_MAX: u16 = 31;
//pub const NODE_SLOTS_MAX: u16 = 24;
pub const NODE_SLOTS_MAX: u16 = 12;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_u32u32")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 2 * 2,
    16 * 2 * 3,
    16 * 2 * 4,
    16 * 2 * 5,
    16 * 2 * 6,
    16 * 2 * 7,
    16 * 2 * 8,
    16 * 2 * 9,
];

/*
#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_u64u64")]
pub const NODE_SLOTS_MAX: u16 = 512;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_u64u64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 2 * 22,
    16 * 4 * 2 * 26,
    16 * 4 * 2 * 28,
    16 * 4 * 2 * 30,
    16 * 4 * 2 * 32,
    16 * 4 * 2 * 34,
    16 * 4 * 2 * 36,
    16 * 4 * 2 * 38,
];
*/
/*
#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_u64u64")]
pub const NODE_SLOTS_MAX: u16 = 256;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_u64u64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 2 * 11,
    16 * 4 * 2 * 18,
    16 * 4 * 2 * 20,
    16 * 4 * 2 * 22,
    16 * 4 * 2 * 24,
    16 * 4 * 2 * 26,
    16 * 4 * 2 * 28,
    16 * 4 * 2 * 30,
];
*/
/*
#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_u64u64")]
pub const NODE_SLOTS_MAX: u16 = 128;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_u64u64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 2 * 4, //
    16 * 4 * 2 * 8, //
    16 * 4 * 2 * 16, //
    16 * 4 * 2 * 17,
    16 * 4 * 2 * 18,
    16 * 4 * 2 * 19,
    16 * 4 * 2 * 20,
    16 * 4 * 2 * 21,
];
*/
/* */
#[cfg(not(feature = "small_node_slots"))]
#[cfg(not(feature = "oi_hash_turbo"))]
#[cfg(feature = "vf_u64u64")]
pub const NODE_SLOTS_MAX: u16 = 64;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(not(feature = "oi_hash_turbo"))]
#[cfg(feature = "vf_u64u64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 2,
    16 * 4 * 2 * 2, //
    16 * 4 * 2 * 4, //
    16 * 4 * 2 * 8, //
    16 * 4 * 2 * 9,
    16 * 4 * 2 * 10,
    16 * 4 * 2 * 11,
    16 * 4 * 2 * 12,
];

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "oi_hash_turbo")]
#[cfg(feature = "vf_u64u64")]
pub const NODE_SLOTS_MAX: u16 = 64;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "oi_hash_turbo")]
#[cfg(feature = "vf_u64u64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 2 * 2,  //
    16 * 4 * 2 * 4,  //
    16 * 4 * 2 * 8,  //
    16 * 4 * 2 * 16, // +
    16 * 4 * 2 * 32,
    16 * 4 * 2 * 34,
    16 * 4 * 2 * 36,
    16 * 4 * 2 * 38,
];

/*
#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_u64u64")]
pub const NODE_SLOTS_MAX: u16 = 32;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_u64u64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4,
    16 * 4 * 2, //
    16 * 4 * 4, //
    16 * 4 * 6,
    16 * 4 * 8, //
    16 * 4 * 9,
    16 * 4 * 10,
    16 * 4 * 11,
];
*/
/*
db_map.depth_of_node_tree(): 4

pub const NODE_SLOTS_MAX: u16 = 512;

#[cfg(not(feature = "small_node_slots"))]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 2 * 22,
    16 * 4 * 2 * 26,
    16 * 4 * 2 * 28,
    16 * 4 * 2 * 30,
    16 * 4 * 2 * 32,
    16 * 4 * 2 * 34,
    16 * 4 * 2 * 36,
    16 * 4 * 2 * 38,
];
*/
/*
460.43user 71.00system 8:56.61elapsed 99%CPU (0avgtext+0avgdata 13316maxresident)k
3824inputs+2986832outputs (4major+3046minor)pagefaults 0swaps
414M	./cmp_siamesedb/target/bench-db.siamesedb
db_map.depth_of_node_tree(): 4
*/
/*
#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "oi_hash_turbo")]
#[cfg(feature = "vf_vu64")]
pub const NODE_SLOTS_MAX: u16 = 256;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "oi_hash_turbo")]
#[cfg(feature = "vf_vu64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 2 * 8, // +
    16 * 4 * 2 * 16,
    16 * 4 * 2 * 17,
    16 * 4 * 2 * 18,
    16 * 4 * 2 * 19,
    16 * 4 * 2 * 20,
    16 * 4 * 2 * 21,
    16 * 4 * 2 * 22,
];
*/
/*
377.26user 67.40system 7:29.32elapsed 98%CPU (0avgtext+0avgdata 9784maxresident)k
4080inputs+2405296outputs (4major+15811minor)pagefaults 0swaps
395M	./cmp_siamesedb/target/bench-db.siamesedb
db_map.depth_of_node_tree(): 4
*/
/* *
#[cfg(not(feature = "small_node_slots"))]
//#[cfg(feature = "oi_hash_turbo")]
#[cfg(feature = "vf_vu64")]
pub const NODE_SLOTS_MAX: u16 = 128;

#[cfg(not(feature = "small_node_slots"))]
//#[cfg(feature = "oi_hash_turbo")]
#[cfg(feature = "vf_vu64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 2 * 4, // +
    16 * 4 * 2 * 8, //
    16 * 4 * 2 * 9,
    16 * 4 * 2 * 10,
    16 * 4 * 2 * 11,
    16 * 4 * 2 * 12,
    16 * 4 * 2 * 13,
    16 * 4 * 2 * 14,
];
*/
/*
pub const NODE_SLOTS_MAX: u16 = 48;

#[cfg(not(feature = "small_node_slots"))]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 2,
    16 * 4 * 2 * 2,
    16 * 4 * 2 * 3,
    16 * 4 * 2 * 4,
    16 * 4 * 2 * 5,
    16 * 4 * 2 * 6,
    16 * 4 * 2 * 7,
    16 * 4 * 2 * 8,
];
*/
/*
329.68user 69.59system 6:45.48elapsed 98%CPU (0avgtext+0avgdata 13124maxresident)k
3824inputs+2171664outputs (4major+41444minor)pagefaults 0swaps
383M	./cmp_siamesedb/target/bench-db.siamesedb
db_map.depth_of_node_tree(): 5
*/
/* */
#[cfg(not(feature = "small_node_slots"))]
#[cfg(not(feature = "tr_has_short_key"))]
#[cfg(feature = "vf_vu64")]
pub const NODE_SLOTS_MAX: u16 = 64;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(not(feature = "tr_has_short_key"))]
#[cfg(feature = "vf_vu64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 2,
    16 * 4 * 4,  //
    16 * 4 * 8,  //
    16 * 4 * 16, //
    16 * 4 * 18,
    16 * 4 * 20,
    16 * 4 * 22,
    16 * 4 * 24,
];

/*
313.65user 76.71system 6:34.52elapsed 98%CPU (0avgtext+0avgdata 13072maxresident)k
0inputs+2014176outputs (0major+62696minor)pagefaults 0swaps
386M	./cmp_siamesedb/target/bench-db.siamesedb
db_map.depth_of_node_tree(): 6
*/
/* */
#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "tr_has_short_key")]
#[cfg(feature = "vf_vu64")]
pub const NODE_SLOTS_MAX: u16 = 32;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "tr_has_short_key")]
#[cfg(feature = "vf_vu64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4 * 3 * 3,
    16 * 4 * 3 * 4,
    16 * 4 * 3 * 5,
    16 * 4 * 3 * 6,
    16 * 4 * 3 * 7,
    16 * 4 * 3 * 8,
    16 * 4 * 3 * 9,
    16 * 4 * 3 * 10,
];

/*
-g
187.01user 1.49system 3:09.54elapsed 99%CPU (0avgtext+0avgdata 407752maxresident)k
0inputs+973656outputs (0major+101670minor)pagefaults 0swaps

-c
141.69user 0.91system 2:23.54elapsed 99%CPU (0avgtext+0avgdata 411168maxresident)k
0inputs+0outputs (0major+102580minor)pagefaults 0swaps

393M	./cmp_siamesedb/target/bench-db.siamesedb
db_map.depth_of_node_tree(): 7
*/
/*
pub const NODE_SLOTS_MAX: u16 = 16;

#[cfg(not(feature = "small_node_slots"))]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 4,
    16 * 4 * 2,
    16 * 4 * 4,
    16 * 4 * 5,
    16 * 4 * 6,
    16 * 4 * 7,
    16 * 4 * 8,
    16 * 4 * 9,
];
*/
/*
-g
184.58user 1.35system 3:07.51elapsed 99%CPU (0avgtext+0avgdata 400792maxresident)k
0inputs+778992outputs (0major+99942minor)pagefaults 0swaps

-c
140.35user 0.79system 2:22.02elapsed 99%CPU (0avgtext+0avgdata 406108maxresident)k
0inputs+0outputs (0major+101292minor)pagefaults 0swaps

381M	./cmp_siamesedb/target/bench-db.siamesedb
db_map.depth_of_node_tree(): 8
*/
/* *
pub const NODE_SLOTS_MAX: u16 = 12;

#[cfg(not(feature = "small_node_slots"))]
#[cfg(feature = "vf_vu64")]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 3,
    16 * 4,
    16 * 6,
    16 * 8,
    16 * 10,
    16 * 14,
    16 * 16,
    16 * 18,
];
*/
/*
-g
186.71user 1.41system 3:09.31elapsed 99%CPU (0avgtext+0avgdata 409280maxresident)k
0inputs+798416outputs (0major+102053minor)pagefaults 0swaps

-c
141.90user 0.91system 2:23.81elapsed 99%CPU (0avgtext+0avgdata 415180maxresident)k
0inputs+0outputs (0major+103538minor)pagefaults 0swaps

390M	./cmp_siamesedb/target/bench-db.siamesedb
db_map.depth_of_node_tree(): 9

pub const NODE_SLOTS_MAX: u16 = 10;

#[cfg(not(feature = "small_node_slots"))]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 1 * 2,
    16 * 1 * 3,
    16 * 1 * 4,
    16 * 1 * 5,
    16 * 1 * 6,
    16 * 1 * 7,
    16 * 1 * 8,
    16 * 1 * 9,
];
*/
/*
-g
191.93user 1.41system 3:14.53elapsed 99%CPU (0avgtext+0avgdata 411704maxresident)k
0inputs+970704outputs (0major+102705minor)pagefaults 0swaps
-c
143.53user 0.80system 2:25.16elapsed 99%CPU (0avgtext+0avgdata 418428maxresident)k
0inputs+0outputs (0major+104379minor)pagefaults 0swaps

404M	./cmp_siamesedb/target/bench-db.siamesedb
db_map.depth_of_node_tree(): 10

pub const NODE_SLOTS_MAX: u16 = 8;

#[cfg(not(feature = "small_node_slots"))]
const NODE_SIZE_ARY: [u32; 8] = [
    16 * 1 * 2,
    16 * 1 * 3,
    16 * 1 * 4,
    16 * 1 * 5,
    16 * 1 * 6,
    16 * 1 * 7,
    16 * 1 * 8,
    16 * 1 * 9,
];
*/

pub const NODE_SLOTS_MAX_HALF: u16 = NODE_SLOTS_MAX / 2;

/*
 * node_size = keys_count.len + (2 * NODE_SLOTS_MAX - 1) * vu64.len
 * node_size = 1 + (2 *   8 -1) * 9 =  136 --> vu64 encoded len: 2
 * node_size = 1 + (2 *  16 -1) * 9 =  288 --> vu64 encoded len: 2
 * node_size = 1 + (2 *  32 -1) * 9 =  569 --> vu64 encoded len: 2
 * node_size = 1 + (2 *  64 -1) * 9 = 1144 --> vu64 encoded len: 2
 * node_size = 1 + (2 * 128 -1) * 9 = 2296 --> vu64 encoded len: 2
 * node_size = 2 + (2 * 256 -1) * 9 = 4601 --> vu64 encoded len: 2
 * node_size = 2 + (2 * 512 -1) * 9 = 9209 --> vu64 encoded len: 2
*/

impl VarFileNodeCache {
    #[cfg(feature = "node_cache")]
    #[inline]
    fn flush_node_cache(&mut self) -> Result<()> {
        self.1.flush(&mut self.0)?;
        Ok(())
    }

    #[cfg(feature = "node_cache")]
    #[inline]
    pub fn flush_node_cache_clear(&mut self) -> Result<()> {
        self.1.clear(&mut self.0)?;
        Ok(())
    }

    fn delete_node(&mut self, node_: IdxNode) -> Result<NodePieceSize> {
        let node_offset = node_.get_ref().offset();
        //
        #[cfg(not(feature = "node_cache"))]
        let old_node_size = {
            self.0.seek_from_start(node_offset)?;
            self.0.read_node_size()?
        };
        #[cfg(feature = "node_cache")]
        let old_node_size = {
            match self.1.delete(&node_offset) {
                Some(node_size) => node_size,
                None => {
                    self.0.seek_from_start(node_offset)?;
                    self.0.read_node_size()?
                }
            }
        };
        //
        self.0.push_free_piece_list(node_offset, old_node_size)?;
        Ok(old_node_size)
    }

    fn write_node(&mut self, mut node_: IdxNode, is_new: bool) -> Result<IdxNode> {
        debug_assert!(!node_.get_ref().offset().is_zero());
        debug_assert!((node_.get_ref().offset().as_value() & 0x0F) == 0);
        //
        let new_node_size = {
            #[cfg(feature = "siamese_debug")]
            let buf_len: u32 = node_.get_ref().encoded_node_size().try_into().unwrap();
            #[cfg(not(feature = "siamese_debug"))]
            let buf_len: u32 = node_.get_ref().encoded_node_size() as u32;
            //
            #[cfg(any(feature = "vf_u32u32", feature = "vf_u64u64"))]
            let encoded_len: u32 = 2;
            #[cfg(feature = "vf_vu64")]
            let encoded_len: u32 = {
                let encoded_len = if buf_len < 128 { 1 } else { 2 };
                //let encoded_len = vu64::encoded_len(buf_len as u64);
                debug_assert!(encoded_len == vu64::encoded_len(buf_len as u64));
                encoded_len.into()
            };
            //
            // buggy: size operation for node size.
            self.0
                .piece_mgr
                .roundup(NodePieceSize::new(buf_len + encoded_len))
        };
        //
        if !is_new {
            #[cfg(not(feature = "node_cache"))]
            let old_node_size = {
                self.0.seek_from_start(node_.get_ref().offset())?;
                self.0.read_node_size()?
            };
            #[cfg(feature = "node_cache")]
            let old_node_size = {
                let offset = node_.get_ref().offset();
                if let Some(node_size) = self.1.get_node_size(&offset) {
                    node_size
                } else {
                    self.0.seek_from_start(offset)?;
                    self.0.read_node_size()?
                }
            };
            if new_node_size <= old_node_size
                && !self.0.piece_mgr.can_down(old_node_size, new_node_size)
            {
                // over writes.
                #[cfg(not(feature = "node_cache"))]
                {
                    node_.get_mut().set_size(old_node_size);
                    node_.idx_write_node_one(&mut self.0)?;
                    return Ok(node_);
                }
                #[cfg(feature = "node_cache")]
                {
                    let node_ = self.1.put(&mut self.0, node_, old_node_size, true)?;
                    return Ok(node_);
                }
            } else {
                let offset = node_.get_ref().offset();
                // delete old and add new
                #[cfg(feature = "node_cache")]
                self.1.delete(&offset);
                // old
                self.0.push_free_piece_list(offset, old_node_size)?;
            }
        }
        // add new.
        {
            let free_node_offset = self.0.pop_free_piece_list(new_node_size)?;
            let (new_node_offset, new_node_size) = if !free_node_offset.is_zero() {
                self.0.seek_from_start(free_node_offset)?;
                let node_size = self.0.read_node_size()?;
                #[cfg(debug_assertions)]
                if node_size != new_node_size {
                    debug_assert!(
                        new_node_size.as_value() > NODE_SIZE_ARY[NODE_SIZE_ARY.len() - 2],
                        "new_node_size: {} == NODE_SIZE_ARY[NODE_SIZE_ARY.len() - 2]: {}",
                        new_node_size.as_value(),
                        NODE_SIZE_ARY[NODE_SIZE_ARY.len() - 2]
                    );
                }
                //self.0.write_node_clear(free_node_offset, node_size)?;
                (free_node_offset, node_size)
            } else {
                let node_offset: NodePieceOffset = self.0.seek_to_end()?;
                self.0.write_node_clear(node_offset, new_node_size)?;
                #[cfg(debug_assertions)]
                {
                    let _current_pos = self.0.seek_position()?;
                    debug_assert!(
                        node_offset + new_node_size == _current_pos,
                        "node_offset: {} + new_node_size: {} == _current_pos: {}",
                        node_offset,
                        new_node_size,
                        _current_pos,
                    );
                }
                (node_offset, new_node_size)
            };
            debug_assert!(!new_node_offset.is_zero());
            debug_assert!((new_node_offset.as_value() & 0x0F) == 0);
            {
                {
                    let mut node = node_.get_mut();
                    node.set_offset(new_node_offset);
                    node.set_size(new_node_size);
                }
                #[cfg(not(feature = "node_cache"))]
                {
                    node_.idx_write_node_one(&mut self.0)?;
                    Ok(node_)
                }
                #[cfg(feature = "node_cache")]
                {
                    //
                    // BUG: the buggy nc on non nc_large. why?
                    //
                    #[cfg(feature = "nc_large")]
                    let node_ = self.1.put(&mut self.0, node_, new_node_size, true)?;
                    #[cfg(not(feature = "nc_large"))]
                    node_.idx_write_node_one(&mut self.0)?;
                    //
                    Ok(node_)
                }
            }
        }
    }

    fn read_node_no_cache(&mut self, offset: NodePieceOffset) -> Result<(IdxNode, NodePieceSize)> {
        IdxNode::idx_read_node_one(&mut self.0, offset)
    }
    #[cfg(not(feature = "node_cache"))]
    fn read_node(&mut self, offset: NodePieceOffset) -> Result<IdxNode> {
        self.read_node_no_cache(offset).map(|o| o.0)
    }
    #[cfg(feature = "node_cache")]
    fn read_node(&mut self, offset: NodePieceOffset) -> Result<IdxNode> {
        debug_assert!(!offset.is_zero());
        debug_assert!((offset.as_value() & 0x0F) == 0);
        //
        if let Some(cached_node) = self.1.get(&offset) {
            return Ok(cached_node);
        }
        let (node_, node_size) = self.read_node_no_cache(offset)?;
        let node_ = self.1.put(&mut self.0, node_, node_size, false)?;
        //
        Ok(node_)
    }
}

//const GRAPH_NODE_ST: &str = "∧";
//const GRAPH_NODE_ED: &str = "∨";
const GRAPH_NODE_ST: &str = "^";
const GRAPH_NODE_ED: &str = "v";
//const GRAPH_NODE_ST: &str = "{";
//const GRAPH_NODE_ED: &str = "}";

// for debug
impl VarFileNodeCache {
    fn graph_string(&mut self, head: &str, node_: &IdxNode) -> Result<String> {
        use std::fmt::Write;
        //
        let node = node_.get_ref();
        let mut gs = format!(
            "{}{}:{:04x}\n",
            head,
            GRAPH_NODE_ST,
            node.offset().as_value()
        );
        let mut i = node.downs_len() - 1;
        let node_offset = node.downs_get(i);
        if !node_offset.is_zero() {
            let node = self
                .read_node(node_offset)
                .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
            let gs0 = self.graph_string(&format!("{}    ", head), &node)?;
            gs += &gs0;
        }
        while i > 0 {
            i -= 1;
            #[cfg(not(feature = "tr_has_short_key"))]
            let key_offset = node.keys_get(i);
            #[cfg(feature = "tr_has_short_key")]
            let (key_offset, _short_key) = node.keys_get(i);
            //
            let _ = writeln!(gs, "{}{:04x}", head, key_offset.as_value());
            let node_offset = node.downs_get(i);
            if !node_offset.is_zero() {
                let node = self
                    .read_node(node_offset)
                    .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
                let gs0 = self.graph_string(&format!("{}    ", head), &node)?;
                gs += &gs0;
            }
        }
        let _ = writeln!(gs, "{}{}", head, GRAPH_NODE_ED);
        //
        Ok(gs)
    }

    fn graph_string_with_key_string<KT>(
        &mut self,
        head: &str,
        node_: &IdxNode,
        dbxxx: &FileDbXxxInner<KT>,
    ) -> Result<String>
    where
        KT: DbMapKeyType + std::fmt::Display,
    {
        use std::fmt::Write;
        //
        let node = node_.get_ref();
        let mut gs = format!(
            "{}{}:0x{:04x},{03}\n",
            head,
            GRAPH_NODE_ST,
            node.offset().as_value(),
            node.size()
        );
        let mut i = node.downs_len() - 1;
        let node_offset = node.downs_get(i);
        if !node_offset.is_zero() {
            let node = self
                .read_node(node_offset)
                .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
            let gs0 = self.graph_string_with_key_string(&format!("{}    ", head), &node, dbxxx)?;
            gs += &gs0;
        }
        while i > 0 {
            i -= 1;
            #[cfg(not(feature = "tr_has_short_key"))]
            let key_offset = node.keys_get(i);
            #[cfg(feature = "tr_has_short_key")]
            let (key_offset, _short_key) = node.keys_get(i);
            //
            if !key_offset.is_zero() {
                let key_string = dbxxx.load_key_data(key_offset)?;
                let _ = writeln!(gs, "{}{:04x}:'{}'", head, key_offset.as_value(), key_string);
            }
            let node_offset = node.downs_get(i);
            if !node_offset.is_zero() {
                let node = self
                    .read_node(node_offset)
                    .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
                let gs0 =
                    self.graph_string_with_key_string(&format!("{}    ", head), &node, dbxxx)?;
                gs += &gs0;
            }
        }
        let _ = writeln!(gs, "{}{}", head, GRAPH_NODE_ED);
        //
        Ok(gs)
    }

    fn idx_keys_count_stats(
        &mut self,
        node_: &IdxNode,
        keys_vec: &mut KeysCountStats,
    ) -> Result<()> {
        let node = node_.get_ref();
        let mut i = node.downs_len() - 1;
        let node_offset = node.downs_get(i);
        if !node_offset.is_zero() {
            let node = self
                .read_node(node_offset)
                .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
            self.idx_keys_count_stats(&node, keys_vec)?;
        }
        while i > 0 {
            i -= 1;
            //
            let node_offset = node.downs_get(i);
            if !node_offset.is_zero() {
                let node = self
                    .read_node(node_offset)
                    .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
                let keys_count = node.get_ref().keys_len();
                #[cfg(feature = "siamese_debug")]
                keys_vec.touch_size(KeysCount::new(keys_count.try_into().unwrap()));
                #[cfg(not(feature = "siamese_debug"))]
                keys_vec.touch_size(KeysCount::new(keys_count as u16));
                self.idx_keys_count_stats(&node, keys_vec)?;
            }
        }
        //
        Ok(())
    }

    fn count_of_used_node<F>(
        &mut self,
        node_: &IdxNode,
        node_vec: &mut Vec<(u32, u64)>,
        key_piece_vec: &mut Vec<(u32, u64)>,
        value_piece_vec: &mut Vec<(u32, u64)>,
        read_key_value_piece_size_func: F,
    ) -> Result<()>
    where
        F: Fn(KeyPieceOffset) -> Result<(KeyPieceSize, ValuePieceSize)> + std::marker::Copy,
    {
        let node = node_.get_ref();
        match node_vec.iter().position(|v| v.0 == node.size().as_value()) {
            Some(sz_idx) => {
                node_vec[sz_idx].1 += 1;
            }
            None => {
                let last = node_vec.len() - 1;
                node_vec[last].1 += 1;
            }
        }
        //
        let mut i = node.downs_len() - 1;
        let node_offset = node.downs_get(i);
        if !node_offset.is_zero() {
            let node = self
                .read_node(node_offset)
                .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
            self.count_of_used_node(
                &node,
                node_vec,
                key_piece_vec,
                value_piece_vec,
                read_key_value_piece_size_func,
            )?;
        }
        while i > 0 {
            i -= 1;
            //
            #[cfg(not(feature = "tr_has_short_key"))]
            let key_offset = node.keys_get(i);
            #[cfg(feature = "tr_has_short_key")]
            let (key_offset, _short_key) = node.keys_get(i);
            //
            if !key_offset.is_zero() {
                let (key_piece_size, value_piece_size) =
                    read_key_value_piece_size_func(key_offset)?;
                match key_piece_vec
                    .iter()
                    .position(|v| v.0 == key_piece_size.as_value())
                {
                    Some(sz_idx) => {
                        key_piece_vec[sz_idx].1 += 1;
                    }
                    None => {
                        let last = key_piece_vec.len() - 1;
                        key_piece_vec[last].1 += 1;
                    }
                }
                match value_piece_vec
                    .iter()
                    .position(|v| v.0 == value_piece_size.as_value())
                {
                    Some(sz_idx) => {
                        value_piece_vec[sz_idx].1 += 1;
                    }
                    None => {
                        let last = value_piece_vec.len() - 1;
                        value_piece_vec[last].1 += 1;
                    }
                }
            }
            //
            let node_offset = node.downs_get(i);
            if !node_offset.is_zero() {
                let node = self
                    .read_node(node_offset)
                    .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
                self.count_of_used_node(
                    &node,
                    node_vec,
                    key_piece_vec,
                    value_piece_vec,
                    read_key_value_piece_size_func,
                )?;
            }
        }
        //
        Ok(())
    }

    fn idx_piece_size_stats<KV, F>(
        &mut self,
        node_: &IdxNode,
        piece_vec: &mut RecordSizeStats<KV>,
        read_piece_size_func: F,
    ) -> Result<()>
    where
        F: Fn(KeyPieceOffset) -> Result<PieceSize<KV>> + Copy,
        KV: Copy + Ord,
    {
        let node = node_.get_ref();
        let mut i = node.downs_len() - 1;
        let node_offset = node.downs_get(i);
        if !node_offset.is_zero() {
            let node = self
                .read_node(node_offset)
                .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
            self.idx_piece_size_stats(&node, piece_vec, read_piece_size_func)?;
        }
        while i > 0 {
            i -= 1;
            //
            #[cfg(not(feature = "tr_has_short_key"))]
            let key_offset = node.keys_get(i);
            #[cfg(feature = "tr_has_short_key")]
            let (key_offset, _short_key) = node.keys_get(i);
            //
            if !key_offset.is_zero() {
                let piece_size = read_piece_size_func(key_offset)?;
                piece_vec.touch_size(piece_size);
            }
            //
            let node_offset = node.downs_get(i);
            if !node_offset.is_zero() {
                let node = self
                    .read_node(node_offset)
                    .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
                self.idx_piece_size_stats(&node, piece_vec, read_piece_size_func)?;
            }
        }
        //
        Ok(())
    }

    fn idx_kv_length_stats<KV: Default + Copy + Ord, F>(
        &mut self,
        node_: &IdxNode,
        length_vec: &mut LengthStats<KV>,
        read_kv_length_func: F,
    ) -> Result<()>
    where
        F: Fn(KeyPieceOffset) -> Result<Length<KV>> + Copy,
    {
        let node = node_.get_ref();
        let mut i = node.downs_len() - 1;
        let node_offset = node.downs_get(i);
        if !node_offset.is_zero() {
            let node = self
                .read_node(node_offset)
                .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
            self.idx_kv_length_stats(&node, length_vec, read_kv_length_func)?;
        }
        while i > 0 {
            i -= 1;
            //
            #[cfg(not(feature = "tr_has_short_key"))]
            let key_offset = node.keys_get(i);
            #[cfg(feature = "tr_has_short_key")]
            let (key_offset, _short_key) = node.keys_get(i);
            //
            if !key_offset.is_zero() {
                let key_length = read_kv_length_func(key_offset)?;
                length_vec.touch_length(key_length);
            }
            //
            let node_offset = node.downs_get(i);
            if !node_offset.is_zero() {
                let node = self
                    .read_node(node_offset)
                    .unwrap_or_else(|_| panic!("offset: {:04x}", node_offset.as_value()));
                self.idx_kv_length_stats(&node, length_vec, read_kv_length_func)?;
            }
        }
        //
        Ok(())
    }
}

//
// ref) http://wwwa.pikara.ne.jp/okojisan/b-tree/bsb-tree.html
//

/*
```text
used node piece:
+--------+-------+-------------+-----------------------------------+
| offset | bytes | name        | comment                           |
+--------+-------+-------------+-----------------------------------+
| 0      | 1..5  | node size   | size in bytes of this node: vu32  |
| --     | 2     | status      | is_leaf, has_key ...etc           |
| --     | 1     | key-count   | count of keys                     |
| --     | 1..9  | key1        | offset of key-value               |
|        |       | ...         |                                   |
|        |       | key4        |                                   |
| --     | 1..9  | down1       | offset of next node               |
|        |       | ...         |                                   |
|        |       | down5       |                                   |
|        | 1..9  | down1       | offset of next node               |
| --     | 1..9  | keybody1    | key body data (at has_key)        |
|        |       | ...         |                                   |
|        |       | keybody4    |                                   |
+--------+-------+-------------+-----------------------------------+
```
*/
/*
```text
free piece:
+--------+-------+-------------+-----------------------------------+
| offset | bytes | name        | comment                           |
+--------+-------+-------------+-----------------------------------+
| 0      | 1..5  | node size   | size in bytes of this node: u32   |
| --     | 1     | keys-count  | always zero                       |
| --     | 8     | next        | next free piece offset           |
| --     | --    | reserve     | reserved free space               |
+--------+-------+-------------+-----------------------------------+
```
*/