rlucene 0.1.0-alpha.3

A Rust port of Apache Lucene, a full-text search engine library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
use crate::core::codecs::mutable_point_tree::MutablePointTree;
use crate::core::index::BytesRef;
use crate::core::index::index_reader::Identity;
use crate::core::index::merge_state::DocMap;
use crate::core::index::point_values::{
  IntersectVisitor, MAX_DIMENSIONS, MAX_INDEX_DIMENSIONS, MAX_NUM_BYTES, PointTree, PointTreeEnum,
  PointValues, Relation,
};
use crate::core::search::doc_id_set_iterator::DocIdSetIterator;
use crate::core::search::doc_id_set_iterator::NO_MORE_DOCS;
use crate::core::store::IO_CONTEXT_DEFAULT;
use crate::core::store::directory::Directory;
use crate::core::store::{DataInput, IOContext, IndexInput, IndexOutput, IndexOutputEnum2};
use crate::core::util::HasIdentity;
use crate::core::util::bit_util::BitUtil;
use crate::core::util::bkd::bkd_config::BKDConfig;
use crate::core::util::bkd::bkd_reader::BKDReader;
use crate::core::util::bkd::bkd_writer::{
  BKDWriter, DEFAULT_MAX_MB_SORT_IN_HEAP, VERSION_META_FILE,
};
use crate::core::util::clone::TryClone;
use crate::core::util::close::{Closeable, CloseableRef};
use crate::core::util::error::lucene_error::{LuceneError, LuceneErrorKind, Result};
use crate::core::util::io_utils::IOUtils;
use crate::core::util::numeric_utils::NumericUtils;
use crate::core::util::{SliceCopyOps, ToInt, TryIntoInt};
use crate::test_framework::core::store::corrupting_index_output::CorruptingIndexOutput;
use crate::test_framework::core::util::lucene_test_case::{
  at_least, at_least_usize, create_temp_dir, new_directory, new_directory_shared, new_fs_directory,
  new_mock_directory, new_mock_fs_directory, random, random_from_seed,
};
use crate::test_framework::core::util::test_util::TestUtil;
use bit_set::BitSet;
use num_bigint::{BigInt, Sign};
use num_traits::Zero;
use parking_lot::Mutex;
use rand::prelude::StdRng;
use rand::{Rng, RngExt};
use std::cell::RefCell;
use std::fmt::Display;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

#[allow(dead_code)] // for quick search
struct TestBKD;

struct DocMapMock {
  cur_doc_id_base: i32,
}

impl DocMap for DocMapMock {
  fn get(&self, doc_id: i32) -> Result<i32> {
    Ok(self.cur_doc_id_base + doc_id)
  }
}

fn get_point_values<I>(index_input: Arc<Mutex<I>>) -> Result<BKDReader<I>>
where
  I: IndexInput,
{
  let meta_in = &mut *index_input.lock();
  let (mut reader, version) = BKDReader::init_with_meta(meta_in, index_input.clone())?;
  let (min_leaf_block_fp, index_start_pointer) = if version >= VERSION_META_FILE {
    (
      DataInput::read_long(meta_in)?,
      DataInput::read_long(meta_in)?.try_convert()?,
    )
  } else {
    let index_start_pointer = meta_in.get_file_pointer()?;
    let min_leaf_block_fp = meta_in.read_vlong()?;
    meta_in.seek(index_start_pointer)?;
    (min_leaf_block_fp, index_start_pointer)
  };
  reader.same_in = true;
  reader.min_leaf_block_fp = min_leaf_block_fp;
  reader.index_start_pointer = index_start_pointer;
  reader.is_tree_balanced = reader.num_leaves != 1 && reader.is_tree_balanced()?;
  Ok(reader)
}

#[test]
fn test_basic_ints_1d() -> Result<()> {
  let mut random = random();
  let config = BKDConfig::new(1, 1, 4, 2)?;
  let dir = new_directory_shared(&mut random)?;

  {
    let mut writer = BKDWriter::new(100, dir.as_ref(), "tmp", config.clone(), 1.0, 100)?;
    let mut scratch = [0u8; 4];

    for doc_id in 0..100 {
      NumericUtils::int_to_sortable_bytes(doc_id, &mut scratch, 0);
      writer.add(&scratch, doc_id)?;
    }

    let index_fp;
    {
      let mut out = dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
      let finalizer = writer.finish(&mut out)?.unwrap();
      {
        index_fp = out.get_file_pointer()?;
      }
      writer.write_index(&mut out, None, &finalizer)?;
    }

    {
      let mut input = dir.open_input("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
      input.seek(index_fp)?;
      let sub_point_values = get_point_values(Arc::new(Mutex::new(input)))?;

      // Simple 1D range query:
      let mut query_min = vec![vec![0u8; 4]];
      NumericUtils::int_to_sortable_bytes(42, &mut query_min[0], 0);
      let mut query_max = vec![vec![0u8; 4]];
      NumericUtils::int_to_sortable_bytes(87, &mut query_max[0], 0);

      let mut hits = BitSet::new();
      let mut visitor = IntersectVisitorImpl {
        hits: &mut hits,
        query_min: &query_min,
        query_max: &query_max,
        config: config.clone(),
        random: &mut random,
      };
      let r = sub_point_values;
      r.intersect(&mut visitor)?;

      for doc_id in 0..100 {
        let expected = (42..=87).contains(&doc_id);
        let actual = hits.contains(doc_id);
        assert_eq!(expected, actual, "docID={}", doc_id);
      }
    }
  }

  Ok(())
}

#[test]
fn test_random_ints_n_dims() -> Result<()> {
  let mut random = random();
  let num_docs = at_least(&mut random, 1000);
  let dir = new_directory_shared(&mut random)?;
  let num_dims = TestUtil::next_usize(&mut random, 1, 5);
  let num_index_dims = TestUtil::next_usize(&mut random, 1, num_dims);
  let max_points_in_leaf_node = TestUtil::next_usize(&mut random, 50, 100);
  let max_mb: f32 = 3.0 + (3.0 * random.random::<f32>());
  let config = BKDConfig::new(num_dims, num_index_dims, 4, max_points_in_leaf_node)?;
  let mut writer = BKDWriter::new(
    num_docs,
    dir.as_ref(),
    "tmp",
    config.clone(),
    max_mb as f64,
    num_docs as i64,
  )?;
  let mut docs = vec![vec![]; num_docs as usize];
  let mut scratch = vec![0u8; 4 * num_dims];
  let mut min_value = vec![i32::MAX; num_dims];
  let mut max_value = vec![i32::MIN; num_dims];

  for doc_id in 0..num_docs {
    let mut values = vec![0; num_dims];
    if cfg!(feature = "test_log_verbose") {
      println!("doc_id={}", doc_id);
    }
    for dim in 0..num_dims {
      values[dim] = random.random();
      min_value[dim] = min_value[dim].min(values[dim]);
      max_value[dim] = max_value[dim].max(values[dim]);
      NumericUtils::int_to_sortable_bytes(values[dim], &mut scratch, dim * BitUtil::INT_BYTES);
      if cfg!(feature = "test_log_verbose") {
        println!("    {} -> {}", doc_id, values[dim]);
      }
    }
    docs[doc_id as usize] = values;
    writer.add(&scratch, doc_id)?;
  }

  let index_fp;
  {
    let mut out = dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
    let finalizer = writer.finish(&mut out)?.unwrap();
    {
      index_fp = out.get_file_pointer()?;
    }
    writer.write_index(&mut out, None, &finalizer)?;
  }

  {
    let mut input = dir.open_input("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
    input.seek(index_fp)?;
    let sub_point_values = get_point_values(Arc::new(Mutex::new(input)))?;
    let r = sub_point_values;

    let min_packed_value = r.get_min_packed_value()?.unwrap();
    let max_packed_value = r.get_max_packed_value()?.unwrap();
    for dim in 0..num_index_dims {
      assert_eq!(
        min_value[dim],
        NumericUtils::sortable_bytes_to_int(min_packed_value.as_ref(), dim * BitUtil::INT_BYTES,),
        "Mismatch in min value for dim {}",
        dim
      );
      assert_eq!(
        max_value[dim],
        NumericUtils::sortable_bytes_to_int(max_packed_value.as_ref(), dim * BitUtil::INT_BYTES,),
        "Mismatch in max value for dim {}",
        dim
      );
    }

    let iters = at_least(&mut random, 100);
    let mut query_min: Vec<i32> = Vec::new();
    let mut query_min_bytes: Vec<Vec<u8>> = Vec::new();
    let mut query_max: Vec<i32> = Vec::new();
    let mut query_max_bytes: Vec<Vec<u8>> = Vec::new();
    for iter in 0..iters {
      if cfg!(feature = "test_log_verbose") {
        println!("TEST: iter={}", iter);
      }
      query_min.clear();
      query_min.resize(num_dims, 0);
      query_min_bytes.resize_with(num_dims, || vec![0u8; 4]);
      for bytes in &mut query_min_bytes {
        bytes.fill(0);
      }
      query_max.clear();
      query_max.resize(num_dims, 0);
      query_max_bytes.resize_with(num_dims, || vec![0u8; 4]);
      for bytes in &mut query_max_bytes {
        bytes.fill(0);
      }

      for dim in 0..num_index_dims {
        query_min[dim] = random.random();
        query_max[dim] = random.random();
        if query_min[dim] > query_max[dim] {
          std::mem::swap(&mut query_min[dim], &mut query_max[dim]);
        }
        NumericUtils::int_to_sortable_bytes(query_min[dim], &mut query_min_bytes[dim], 0);
        NumericUtils::int_to_sortable_bytes(query_max[dim], &mut query_max_bytes[dim], 0);
      }

      let mut hits = BitSet::new();
      let mut visitor = IntersectVisitorImpl {
        hits: &mut hits,
        query_min: &query_min_bytes,
        query_max: &query_max_bytes,
        config: config.clone(),
        random: &mut random,
      };

      r.intersect(&mut visitor)?;

      for (doc_id, doc_values) in docs.iter().enumerate() {
        let mut expected = true;
        for dim in 0..num_index_dims {
          let x = doc_values[dim];
          if x < query_min[dim] || x > query_max[dim] {
            expected = false;
            break;
          }
        }
        let actual = hits.contains(doc_id);
        assert_eq!(expected, actual, "docID={}", doc_id);
      }
    }
  }

  Ok(())
}
// Tests on N-dimensional points where each dimension is a BigInteger
#[test]
fn test_big_int_n_dims() -> Result<()> {
  let mut random = random();
  let num_docs = at_least(&mut random, 1000);
  let dir = new_directory_shared(&mut random)?;

  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 2, 30);
  let num_dims = TestUtil::next_usize(&mut random, 1, 5);
  let max_points_in_leaf_node = TestUtil::next_usize(&mut random, 50, 100);
  let max_mb: f32 = 3.0 + (3.0 * random.random::<f32>());
  let config = BKDConfig::new(
    num_dims,
    num_dims,
    num_bytes_per_dim,
    max_points_in_leaf_node,
  )?;
  let mut writer = BKDWriter::new(
    num_docs,
    dir.as_ref(),
    "tmp",
    config.clone(),
    max_mb as f64,
    num_docs as i64,
  )?;

  let mut docs = vec![vec![]; num_docs as usize];
  let mut scratch = vec![0u8; num_bytes_per_dim * num_dims];

  for doc_id in 0..num_docs {
    let mut values = vec![BigInt::zero(); num_dims];
    if cfg!(feature = "test_log_verbose") {
      println!("  doc_id={}", doc_id);
    }
    for (dim, value) in values.iter_mut().enumerate().take(num_dims) {
      *value = random_big_int(num_bytes_per_dim, &mut random);
      NumericUtils::big_int_to_sortable_bytes(
        value,
        num_bytes_per_dim,
        &mut scratch,
        dim * num_bytes_per_dim,
      )?;
      if cfg!(feature = "test_log_verbose") {
        println!("    {} -> {}", dim, value);
      }
    }

    docs[doc_id as usize] = values;
    writer.add(&scratch, doc_id)?;
  }

  let index_fp;
  {
    let mut out = dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
    let finalizer = writer.finish(&mut out)?.unwrap();
    {
      index_fp = out.get_file_pointer()?;
    }
    writer.write_index(&mut out, None, &finalizer)?;
  }

  {
    let mut input = dir.open_input("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
    input.seek(index_fp)?;
    let sub_point_values = get_point_values(Arc::new(Mutex::new(input)))?;
    let point_values = sub_point_values;

    let iters = at_least(&mut random, 100);
    let mut query_min: Vec<BigInt> = Vec::new();
    let mut query_min_bytes: Vec<Vec<u8>> = Vec::new();
    let mut query_max: Vec<BigInt> = Vec::new();
    let mut query_max_bytes: Vec<Vec<u8>> = Vec::new();
    for iter in 0..iters {
      if cfg!(feature = "test_log_verbose") {
        println!("TEST: iter={}", iter);
      }
      query_min.clear();
      query_min.resize(num_dims, BigInt::zero());
      query_min_bytes.resize_with(num_dims, || vec![0u8; num_bytes_per_dim]);
      for bytes in &mut query_min_bytes {
        bytes.fill(0);
      }
      query_max.clear();
      query_max.resize(num_dims, BigInt::zero());
      query_max_bytes.resize_with(num_dims, || vec![0u8; num_bytes_per_dim]);
      for bytes in &mut query_max_bytes {
        bytes.fill(0);
      }

      for dim in 0..num_dims {
        query_min[dim] = random_big_int(num_bytes_per_dim, &mut random);
        query_max[dim] = random_big_int(num_bytes_per_dim, &mut random);
        if query_min[dim] > query_max[dim] {
          std::mem::swap(&mut query_min[dim], &mut query_max[dim]);
        }
        NumericUtils::big_int_to_sortable_bytes(
          &query_min[dim],
          num_bytes_per_dim,
          &mut query_min_bytes[dim],
          0,
        )?;
        NumericUtils::big_int_to_sortable_bytes(
          &query_max[dim],
          num_bytes_per_dim,
          &mut query_max_bytes[dim],
          0,
        )?;
      }

      let mut hits = BitSet::new();
      let mut visitor = IntersectVisitorImpl {
        hits: &mut hits,
        query_min: &query_min_bytes,
        query_max: &query_max_bytes,
        config: config.clone(),
        random: &mut random,
      };

      point_values.intersect(&mut visitor)?;

      for (doc_id, doc_values) in docs.iter().enumerate() {
        let mut expected = true;
        for dim in 0..num_dims {
          let x = &doc_values[dim];
          if x < &query_min[dim] || x > &query_max[dim] {
            expected = false;
            break;
          }
        }
        let actual = hits.contains(doc_id);
        assert_eq!(expected, actual, "docID={}", doc_id);
      }
    }
  }
  Ok(())
}
/// Make sure we close open files, delete temp files, etc., on error.
#[test]
fn test_with_exceptions() -> Result<()> {
  let mut random = random();
  let num_docs = at_least_usize(&mut random, 10000);
  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 2, 30);
  let num_data_dims = TestUtil::next_usize(&mut random, 1, MAX_DIMENSIONS);
  let num_index_dims = std::cmp::min(
    TestUtil::next_usize(&mut random, 1, num_data_dims),
    MAX_INDEX_DIMENSIONS,
  ) as usize;

  let mut doc_values = vec![vec![vec![0u8; num_bytes_per_dim]; num_data_dims]; num_docs];

  for values in doc_values.iter_mut().take(num_docs) {
    for value in values.iter_mut().take(num_data_dims) {
      random.fill_bytes(value);
    }
  }

  let mut max_mb_heap = 0.05;
  // Keep retrying until we 1) we allow a big enough heap, and 2) we hit a
  // random IOExc from MDW:
  let mut done = false;
  while !done {
    let dir = new_mock_fs_directory(&mut random, create_temp_dir()?)?;
    dir.set_random_io_exception_rate(0.05);
    dir.set_random_io_exception_rate_on_open(0.05);

    match (verify_with_max_mb(
      &mut random,
      &dir,
      &doc_values,
      None,
      num_data_dims,
      num_index_dims,
      num_bytes_per_dim,
      50,
      max_mb_heap,
    ))
    .map_err(LuceneError::into_kind)
    {
      Ok(()) => {},
      Err(LuceneErrorKind::IllegalArgument(iae)) => {
        // This just means we got a too-small maxMB for the
        // maxPointsInLeafNode; just retry w/ more heap
        assert!(
          iae
            .message
            .contains("either increase maxMBSortInHeap or decrease maxPointsInLeafNode")
        );
        max_mb_heap *= 1.25;
      },
      Err(ioe) => {
        if ioe.to_string().contains("a random I/O error") {
          // BKDWriter should fully clean up after itself:
          done = true;
        } else {
          return Err(ioe.into());
        }
      },
    }

    let files = dir.list_all()?;
    assert!(files.is_empty(), "files={:?}", files);
    dir.close()?;
  }
  Ok(())
}

#[test]
fn test_random_binary_tiny() -> Result<()> {
  let mut random = random();
  do_test_random_binary(&mut random, 10)
}

#[test]
fn test_random_binary_medium() -> Result<()> {
  let mut random = random();
  do_test_random_binary(&mut random, 10_000)
}

#[cfg(feature = "nightly")]
#[test]
#[ignore = "nightly"]
fn test_random_binary_big() -> Result<()> {
  let mut random = random();
  do_test_random_binary(&mut random, 200_000)
}
#[test]
fn test_too_little_heap() -> Result<()> {
  let dir = new_directory_shared(&mut random())?;

  let err = BKDWriter::new(
    1,
    dir.as_ref(),
    "bkd",
    BKDConfig::new(1, 1, 16, 1_000_000)?,
    0.001,
    0,
  );
  assert!(err.is_err());
  if let Err(err) = err {
    let err_msg = format!("{:?}", err);
    assert!(err_msg.contains("either increase maxMBSortInHeap or decrease maxPointsInLeafNode"));
  }
  Ok(())
}
fn do_test_random_binary<R>(random: &mut R, count: usize) -> Result<()>
where
  R: Rng + ?Sized,
{
  let num_docs = TestUtil::next_usize(random, count, count * 2);
  let num_bytes_per_dim = TestUtil::next_usize(random, 2, 30);

  let num_data_dims = TestUtil::next_usize(random, 1, MAX_DIMENSIONS);
  let num_index_dims = std::cmp::min(
    TestUtil::next_usize(random, 1, num_data_dims),
    MAX_INDEX_DIMENSIONS,
  ) as usize;

  let mut doc_values = vec![vec![vec![0u8; num_bytes_per_dim]; num_data_dims]; num_docs];

  for doc_value in doc_values.iter_mut().take(num_docs) {
    for val in doc_value.iter_mut().take(num_data_dims) {
      random.fill_bytes(val);
    }
  }

  verify(
    random,
    &doc_values,
    None,
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
  )
}

#[test]
fn test_all_equal() -> Result<()> {
  let mut random = random();

  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 2, 30);
  let num_data_dims = TestUtil::next_usize(&mut random, 1, MAX_DIMENSIONS);
  let num_index_dims = std::cmp::min(
    TestUtil::next_usize(&mut random, 1, num_data_dims),
    MAX_INDEX_DIMENSIONS,
  );

  let num_docs = at_least_usize(&mut random, 1000);
  let mut doc_values = vec![vec![vec![0u8; num_bytes_per_dim]; num_data_dims]; num_docs];

  for doc_id in 0..num_docs {
    if doc_id == 0 {
      for values in doc_values[doc_id].iter_mut().take(num_data_dims) {
        random.fill_bytes(values);
      }
    } else {
      let (previous, current) = doc_values.split_at_mut(doc_id);
      current[0].clone_from(&previous[0]);
    }
  }

  verify(
    &mut random,
    &doc_values,
    None,
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
  )
}

#[test]
fn test_index_dim_equal_data_dim_different() -> Result<()> {
  let mut random = random();

  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 2, 30);
  let num_data_dims = TestUtil::next_usize(&mut random, 2, MAX_DIMENSIONS);
  let num_index_dims = std::cmp::min(
    TestUtil::next_usize(&mut random, 1, num_data_dims - 1),
    MAX_INDEX_DIMENSIONS,
  );

  let num_docs = at_least_usize(&mut random, 1000);
  let mut doc_values = vec![vec![vec![0u8; num_bytes_per_dim]; num_data_dims]; num_docs];

  let mut index_dimensions = vec![vec![0u8; num_bytes_per_dim]; num_data_dims];
  for dim_value in index_dimensions.iter_mut().take(num_index_dims) {
    random.fill_bytes(dim_value);
  }

  for doc_value in doc_values.iter_mut().take(num_docs) {
    for (dim, val) in doc_value.iter_mut().enumerate().take(num_index_dims) {
      val.clone_from(&index_dimensions[dim]);
    }
    for val in doc_value
      .iter_mut()
      .skip(num_index_dims)
      .take(num_data_dims - num_index_dims)
    {
      random.fill_bytes(val);
    }
  }

  verify(
    &mut random,
    &doc_values,
    None,
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
  )
}

#[test]
fn test_one_dim_equal() -> Result<()> {
  let mut random = random();

  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 2, 30);
  let num_data_dims = TestUtil::next_usize(&mut random, 1, MAX_DIMENSIONS);
  let num_index_dims = std::cmp::min(
    TestUtil::next_usize(&mut random, 1, num_data_dims),
    MAX_INDEX_DIMENSIONS,
  );

  let num_docs = at_least_usize(&mut random, 1000);
  let the_equal_dim = random.random_range(0..num_data_dims);
  let mut doc_values = vec![vec![vec![0u8; num_bytes_per_dim]; num_data_dims]; num_docs];

  for doc_id in 0..num_docs {
    for values in doc_values[doc_id].iter_mut().take(num_data_dims) {
      random.fill_bytes(values);
    }

    if doc_id > 0 {
      let (previous, current) = doc_values.split_at_mut(doc_id);
      current[0][the_equal_dim].clone_from(&previous[0][the_equal_dim]);
    }
  }

  let max_points_in_leaf_node = TestUtil::next_usize(&mut random, 20, 50);

  verify_full(
    &mut random,
    &doc_values,
    None,
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
    max_points_in_leaf_node,
  )
}

#[test]
fn test_one_dim_low_card() -> Result<()> {
  let mut random = random();

  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 2, 30);
  let num_data_dims = TestUtil::next_usize(&mut random, 2, MAX_DIMENSIONS);
  let num_index_dims = std::cmp::min(
    TestUtil::next_usize(&mut random, 2, num_data_dims),
    MAX_INDEX_DIMENSIONS,
  );

  let num_docs = at_least_usize(&mut random, 10_000);
  let the_low_card_dim = random.random_range(0..num_data_dims);

  let mut value1 = vec![0u8; num_bytes_per_dim];
  random.fill_bytes(&mut value1);
  let mut value2 = value1.clone();

  let last = &mut value2[num_bytes_per_dim - 1];
  if *last == 0 || random.random_bool(0.5) {
    *last = last.wrapping_add(1);
  } else {
    *last = last.wrapping_sub(1);
  }

  let mut doc_values = vec![vec![vec![0u8; num_bytes_per_dim]; num_data_dims]; num_docs];

  for doc_value in doc_values.iter_mut().take(num_docs) {
    for (dim, val) in doc_value.iter_mut().take(num_data_dims).enumerate() {
      if dim == the_low_card_dim {
        val.clone_from(if random.random_bool(0.5) {
          &value1
        } else {
          &value2
        });
      } else {
        random.fill_bytes(val);
      }
    }
  }

  let max_points_in_leaf_node = TestUtil::next_usize(&mut random, 20, 50);
  verify_full(
    &mut random,
    &doc_values,
    None,
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
    max_points_in_leaf_node,
  )
}

#[test]
fn test_one_dim_two_values() -> Result<()> {
  let mut random = random();

  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 2, 30);
  let num_data_dims = TestUtil::next_usize(&mut random, 1, MAX_DIMENSIONS);
  let num_index_dims = std::cmp::min(
    TestUtil::next_usize(&mut random, 1, num_data_dims),
    MAX_INDEX_DIMENSIONS,
  );

  let num_docs = at_least_usize(&mut random, 1000);
  let the_dim = random.random_range(0..num_data_dims);

  let mut value1 = vec![0u8; num_bytes_per_dim];
  random.fill_bytes(&mut value1);
  let mut value2 = vec![0u8; num_bytes_per_dim];
  random.fill_bytes(&mut value2);

  let mut doc_values = vec![vec![vec![0u8; num_bytes_per_dim]; num_data_dims]; num_docs];

  for doc_value in doc_values.iter_mut().take(num_docs) {
    for (dim, val) in doc_value.iter_mut().take(num_data_dims).enumerate() {
      if dim == the_dim {
        val.clone_from(if random.random_bool(0.5) {
          &value1
        } else {
          &value2
        });
      } else {
        random.fill_bytes(val);
      }
    }
  }

  verify(
    &mut random,
    &doc_values,
    None,
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
  )
}

#[test]
fn test_random_few_different_values() -> Result<()> {
  let mut random = random();

  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 2, 30);
  let num_data_dims = TestUtil::next_usize(&mut random, 1, MAX_DIMENSIONS);
  let num_index_dims = std::cmp::min(
    TestUtil::next_usize(&mut random, 1, num_data_dims),
    MAX_INDEX_DIMENSIONS,
  );

  let num_docs = at_least_usize(&mut random, 10000);
  let cardinality = TestUtil::next_usize(&mut random, 2, 100);

  let mut values = vec![vec![vec![0u8; num_bytes_per_dim]; num_data_dims]; cardinality];
  for value_set in values.iter_mut().take(cardinality) {
    for value in value_set.iter_mut().take(num_data_dims) {
      random.fill_bytes(value);
    }
  }

  let mut doc_values = vec![vec![vec![0u8; num_bytes_per_dim]; num_data_dims]; num_docs];
  for (doc_value, _) in doc_values.iter_mut().zip(0..num_docs) {
    let v = random.random_range(0..cardinality);
    doc_value.clone_from(&values[v]);
  }

  verify(
    &mut random,
    &doc_values,
    None,
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
  )
}

#[test]
fn test_multi_valued() -> Result<()> {
  let mut random = random();

  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 2, 30);
  let num_data_dims = TestUtil::next_usize(&mut random, 1, MAX_DIMENSIONS);
  let num_index_dims = std::cmp::min(
    TestUtil::next_usize(&mut random, 1, num_data_dims),
    MAX_INDEX_DIMENSIONS,
  ) as usize;

  let num_docs = at_least(&mut random, 1000);
  let mut doc_values: Vec<Vec<Vec<u8>>> = Vec::new();
  let mut doc_ids: Vec<i32> = Vec::new();

  for doc_id in 0..num_docs {
    let num_values_in_doc = TestUtil::next_usize(&mut random, 1, 5);
    for _ in 0..num_values_in_doc {
      doc_ids.push(doc_id);
      let mut values = vec![vec![0u8; num_bytes_per_dim]; num_data_dims];
      for value in values.iter_mut().take(num_data_dims) {
        random.fill_bytes(value);
      }

      doc_values.push(values);
    }
  }

  verify(
    &mut random,
    &doc_values,
    Some(doc_ids),
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
  )
}

/// `doc_ids` can be `None` for the single-valued case; otherwise, it maps value
/// to `doc_id`.
fn verify<R>(
  random: &mut R,
  doc_values: &[Vec<Vec<u8>>],
  doc_ids: Option<Vec<i32>>,
  num_data_dims: usize,
  num_index_dims: usize,
  num_bytes_per_dim: usize,
) -> Result<()>
where
  R: Rng + ?Sized,
{
  let max_points_in_leaf_node = TestUtil::next_usize(random, 50, 1000);
  verify_full(
    random,
    doc_values,
    doc_ids,
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
    max_points_in_leaf_node,
  )
}
#[allow(clippy::too_many_arguments)]
fn verify_full<R>(
  random: &mut R,
  doc_values: &[Vec<Vec<u8>>],
  doc_ids: Option<Vec<i32>>,
  num_data_dims: usize,
  num_index_dims: usize,
  num_bytes_per_dim: usize,
  max_points_in_leaf_node: usize,
) -> Result<()>
where
  R: Rng + ?Sized,
{
  let dir = new_directory(random)?;
  let max_mb: f64 = 3.0 + (3.0 * random.random::<f64>());
  verify_with_max_mb(
    random,
    &dir,
    doc_values,
    doc_ids,
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
    max_points_in_leaf_node,
    max_mb,
  )
}
#[allow(clippy::too_many_arguments)]
fn verify_with_max_mb<D, R>(
  random: &mut R,
  dir: &D,
  doc_values: &[Vec<Vec<u8>>],
  doc_ids: Option<Vec<i32>>,
  num_data_dims: usize,
  num_index_dims: usize,
  num_bytes_per_dim: usize,
  mut max_points_in_leaf_node: usize,
  mut max_mb: f64,
) -> Result<()>
where
  D: Directory,
  D::IndexInput: CloseableRef,
  R: Rng + ?Sized,
{
  let num_values = doc_values.len();

  if cfg!(feature = "test_log_verbose") {
    println!(
      "TEST: numValues={} numDataDims={} numIndexDims={} numBytesPerDim={} maxPointsInLeafNode={} maxMB={}",
      num_values, num_data_dims, num_index_dims, num_bytes_per_dim, max_points_in_leaf_node, max_mb
    );
  }

  let mut to_merge: Option<Vec<usize>> = None;
  let mut doc_maps = None;
  let mut seg = 0;

  let max_docs = if random.random_bool(0.5) {
    num_values as i64
  } else {
    let mut v = i64::MIN;
    while v < num_values as i64 {
      v = random.random::<i64>();
    }
    v
  };

  let mut writer: Option<BKDWriter<&D>> = None;
  let mut out: Option<D::IndexOutput> = None;
  let mut input: Option<Arc<Mutex<D::IndexInput>>> = None;

  let result = (|| -> Result<()> {
    writer = Some(BKDWriter::new(
      num_values as i32,
      dir,
      &format!("_{}", seg),
      BKDConfig::new(
        num_data_dims,
        num_index_dims,
        num_bytes_per_dim,
        max_points_in_leaf_node,
      )?,
      max_mb,
      max_docs,
    )?);

    out = Some(dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?);

    let mut scratch = vec![0u8; num_bytes_per_dim * num_data_dims];
    let mut last_doc_id_base = 0;
    let use_merge = num_data_dims == 1 && num_values >= 10 && random.random_bool(0.5);
    let mut values_in_this_seg = if use_merge {
      TestUtil::next_usize(random, num_values / 10, num_values)
    } else {
      0
    };

    let mut seg_count = 0;

    for ord in 0..num_values {
      let doc_id = doc_ids.as_ref().map_or(ord as i32, |ids| ids[ord]);
      for (dim, value) in doc_values[ord].iter().take(num_data_dims).enumerate() {
        scratch.copy_from(&value[0..num_bytes_per_dim], dim * num_bytes_per_dim);
      }
      writer
        .as_mut()
        .unwrap()
        .add(&scratch, doc_id - last_doc_id_base)?;

      seg_count += 1;

      if use_merge && seg_count == values_in_this_seg {
        if to_merge.is_none() {
          to_merge = Some(Vec::new());
          doc_maps = Some(Vec::new());
        }

        let cur_doc_id_base = last_doc_id_base;
        doc_maps
          .as_mut()
          .unwrap()
          .push(Rc::new(DocMapMock { cur_doc_id_base }));

        let out_ref = out.as_mut().unwrap();
        let finalizer = writer.as_mut().unwrap().finish(out_ref)?.unwrap();
        to_merge.as_mut().unwrap().push(out_ref.get_file_pointer()?);
        writer
          .as_mut()
          .unwrap()
          .write_index(out_ref, None, &finalizer)?;
        values_in_this_seg = TestUtil::next_usize(random, num_values / 10, num_values / 2);
        seg_count = 0;

        seg += 1;
        max_points_in_leaf_node = TestUtil::next_usize(random, 50, 1000);
        max_mb = 3.0 + (3.0 * random.random::<f64>());

        writer = Some(BKDWriter::new(
          num_values as i32,
          dir,
          &format!("_{}", seg),
          BKDConfig::new(
            num_data_dims,
            num_index_dims,
            num_bytes_per_dim,
            max_points_in_leaf_node,
          )?,
          max_mb,
          doc_values.len() as i64,
        )?);
        last_doc_id_base = doc_id;
      }
    }

    let index_fp;

    if let Some(to_merge) = &mut to_merge {
      if seg_count > 0 {
        let out_ref = out.as_mut().unwrap();
        let finalizer = writer.as_mut().unwrap().finish(out_ref)?.unwrap();
        to_merge.push(out_ref.get_file_pointer()?);
        writer
          .as_mut()
          .unwrap()
          .write_index(out_ref, None, &finalizer)?;
        let cur_doc_id_base = last_doc_id_base;
        doc_maps
          .as_mut()
          .unwrap()
          .push(Rc::new(DocMapMock { cur_doc_id_base }));
      }
      if let Some(mut output) = out.take() {
        output.close()?;
      }
      input = Some(Arc::new(Mutex::new(dir.open_input(
        "bkd",
        IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?,
      )?)));
      seg += 1;
      writer = Some(BKDWriter::new(
        num_values as i32,
        dir,
        &format!("_{}", seg),
        BKDConfig::new(
          num_data_dims,
          num_index_dims,
          num_bytes_per_dim,
          max_points_in_leaf_node,
        )?,
        max_mb,
        doc_values.len() as i64,
      )?);

      let mut readers = Vec::new();
      for fp in to_merge {
        let input_ref = input.as_ref().unwrap();
        input_ref.lock().seek(*fp)?;
        readers.push(get_point_values(input_ref.clone())?);
      }

      out = Some(dir.create_output("bkd2", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?);
      {
        let out_ref = out.as_mut().unwrap();
        let finalizer = writer
          .as_mut()
          .unwrap()
          .merge(out_ref, doc_maps, readers)?
          .unwrap();
        index_fp = out_ref.get_file_pointer()?;
        writer
          .as_mut()
          .unwrap()
          .write_index(out_ref, None, &finalizer)?;
      }
      if let Some(mut output) = out.take() {
        output.close()?;
      }
      if let Some(input_ref) = input.take() {
        input_ref.lock().close()?;
      }
      input = Some(Arc::new(Mutex::new(dir.open_input(
        "bkd2",
        IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?,
      )?)));
    } else {
      let out_ref = out.as_mut().unwrap();
      let finalizer = writer.as_mut().unwrap().finish(out_ref)?.unwrap();
      index_fp = out_ref.get_file_pointer()?;
      writer
        .as_mut()
        .unwrap()
        .write_index(out_ref, None, &finalizer)?;
      if let Some(mut output) = out.take() {
        output.close()?;
      }
      input = Some(Arc::new(Mutex::new(dir.open_input(
        "bkd",
        IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?,
      )?)));
    }

    let input_ref = input.as_ref().unwrap();
    input_ref.lock().seek(index_fp)?;
    let sub_point_values = get_point_values(input_ref.clone())?;
    assert_size(&mut sub_point_values.get_point_tree()?, random)?;
    let point_values = sub_point_values;

    let iters = at_least(random, 100);
    for _ in 0..iters {
      let mut query_min = vec![vec![0u8; num_bytes_per_dim]; num_data_dims];
      let mut query_max = vec![vec![0u8; num_bytes_per_dim]; num_data_dims];

      for dim in 0..num_data_dims {
        random.fill_bytes(&mut query_min[dim]);
        random.fill_bytes(&mut query_max[dim]);

        if query_min[dim] > query_max[dim] {
          std::mem::swap(&mut query_min[dim], &mut query_max[dim]);
        }
      }

      let mut expected = BitSet::new();
      for (ord, value) in doc_values.iter().enumerate().take(num_values) {
        let mut matches = true;
        for (dim, (min, max)) in query_min
          .iter()
          .zip(query_max.iter())
          .enumerate()
          .take(num_index_dims)
        {
          let val = &value[dim][0..num_bytes_per_dim];
          if val.cmp(&min[0..num_bytes_per_dim]).to_int() < 0
            || val.cmp(&max[0..num_bytes_per_dim]).to_int() > 0
          {
            matches = false;
            break;
          }
        }
        if matches {
          let doc_id = doc_ids.as_ref().map_or(ord as i32, |ids| ids[ord]);
          expected.insert(doc_id as usize);
        }
      }

      let config = BKDConfig::new(
        num_data_dims,
        num_index_dims,
        num_bytes_per_dim,
        max_points_in_leaf_node,
      )?;
      let mut hits = BitSet::new();
      point_values.intersect(&mut IntersectVisitorImpl {
        hits: &mut hits,
        query_min: &query_min,
        query_max: &query_max,
        config: config.clone(),
        random,
      })?;
      assert_hits(&hits, &expected);
      hits.make_empty();
      PointTree::visit_doc_values(
        &mut point_values.get_point_tree()?,
        &mut IntersectVisitorImpl {
          hits: &mut hits,
          query_min: &query_min,
          query_max: &query_max,
          config: config.clone(),
          random,
        },
      )?;
      assert_hits(&hits, &expected);
    }
    drop(point_values);
    if let Some(input_ref) = input.take() {
      input_ref.lock().close()?;
    }
    dir.delete_file("bkd")?;
    if to_merge.is_some() {
      dir.delete_file("bkd2")?;
    }

    Ok(())
  })();

  if result.is_err() {
    if let Some(writer) = writer.as_mut() {
      let _ = writer.close();
    }
    if let Some(input_ref) = input.take() {
      let _ = input_ref.lock().close();
    }
    if let Some(mut output) = out.take() {
      let _ = output.close();
    }
    let files = vec!["bkd".to_string(), "bkd2".to_string()];
    IOUtils::delete_files_ignoring_exceptions(dir, &files);
  }

  result
}
fn assert_size<R, T>(tree: &mut T, random: &mut R) -> Result<()>
where
  R: Rng + ?Sized,
  T: PointTree,
{
  // TODO:do we need clone?
  // let mut clone = tree.clone();
  // assert_eq!(clone.size()?, tree.size()?);

  // Rarely continue with the clone tree
  // let tree = if rarely(random) { &mut clone } else { tree };

  let mut visit_doc_id_size = [0; 1];
  let mut visit_doc_values_size = [0; 1];

  let mut visitor = IntersectVisitorMock1 {
    visit_doc_id_size: &mut visit_doc_id_size,
    visit_doc_values_size: &mut visit_doc_values_size,
  };

  if random.random_bool(0.5) {
    tree.visit_doc_ids(&mut visitor)?;
    tree.visit_doc_values(&mut visitor)?;
  } else {
    tree.visit_doc_values(&mut visitor)?;
    tree.visit_doc_ids(&mut visitor)?;
  }

  assert_eq!(visit_doc_id_size[0], visit_doc_values_size[0]);
  assert_eq!(visit_doc_id_size[0], tree.size()? as i64);

  if tree.move_to_child()? {
    loop {
      random_point_tree_navigation(tree, random)?;
      assert_size(tree, random)?;
      if !tree.move_to_sibling()? {
        break;
      }
    }
    tree.move_to_parent()?;
  }
  Ok(())
}

struct IntersectVisitorMock1<'a> {
  visit_doc_id_size: &'a mut [i64],
  visit_doc_values_size: &'a mut [i64],
}
impl IntersectVisitor for IntersectVisitorMock1<'_> {
  fn visit(&mut self, _doc_id: i32) -> Result<()> {
    self.visit_doc_id_size[0] += 1;
    Ok(())
  }

  fn visit_with_packed_value(&mut self, _doc_id: i32, _packed_value: &[u8]) -> Result<()> {
    self.visit_doc_values_size[0] += 1;
    Ok(())
  }

  fn compare(&self, _min_packed_value: &[u8], _max_packed_value: &[u8]) -> Result<Relation> {
    Ok(Relation::CellCrossesQuery)
  }
}
fn random_point_tree_navigation<R, T>(tree: &mut T, random: &mut R) -> Result<()>
where
  R: Rng + ?Sized,
  T: PointTree,
{
  let min_packed_value = tree.get_min_packed_value()?.as_ref().to_vec();
  let max_packed_value = tree.get_max_packed_value()?.as_ref().to_vec();
  let size = tree.size()?;

  if random.random_bool(0.5) && tree.move_to_child()? {
    random_point_tree_navigation(tree, random)?;
    if random.random_bool(0.5) && tree.move_to_sibling()? {
      random_point_tree_navigation(tree, random)?;
    }
    tree.move_to_parent()?;
  }

  // Ensure we always finish on the same node we started
  assert_eq!(
    min_packed_value.as_slice(),
    tree.get_min_packed_value()?.as_ref()
  );
  assert_eq!(
    max_packed_value.as_slice(),
    tree.get_max_packed_value()?.as_ref()
  );
  assert_eq!(size, tree.size()?);

  Ok(())
}

fn assert_hits(hits: &BitSet, expected: &BitSet) {
  let limit = expected.count().max(hits.iter().count());
  for doc_id in 0..limit {
    assert_eq!(
      expected.contains(doc_id),
      hits.contains(doc_id),
      "docID={}",
      doc_id
    );
  }
}

fn random_big_int<R>(num_bytes: usize, random: &mut R) -> BigInt
where
  R: Rng + ?Sized,
{
  let num_bits = num_bytes * 8 - 1;
  let mut bytes = vec![0u8; num_bits.div_ceil(8)];

  random.fill_bytes(&mut bytes);

  if let Some(first_byte) = bytes.first_mut() {
    *first_byte &= !(1 << (num_bits % 8));
  }

  let x = BigInt::from_bytes_be(Sign::Plus, &bytes);

  if random.random_bool(0.5) { -x } else { x }
}

// TODO:
// fn get_directory(num_points: i32) where R: Rng + ?Sized{
// }
struct IntersectVisitorImpl<'a, R>
where
  R: ?Sized,
{
  hits: &'a mut BitSet,
  query_min: &'a [Vec<u8>],
  query_max: &'a [Vec<u8>],
  config: BKDConfig,
  random: &'a mut R,
}

impl<R> IntersectVisitor for IntersectVisitorImpl<'_, R>
where
  R: Rng + ?Sized,
{
  fn visit(&mut self, doc_id: i32) -> Result<()> {
    self.hits.insert(doc_id as usize);
    Ok(())
  }
  fn visit_with_packed_value(&mut self, doc_id: i32, packed_value: &[u8]) -> Result<()> {
    let num_index_dims = self.config.num_index_dims;
    let bytes_per_dim = self.config.bytes_per_dim;

    for dim in 0..num_index_dims {
      let offset = dim * bytes_per_dim;
      if packed_value[offset..offset + bytes_per_dim]
        .cmp(&self.query_min[dim][0..bytes_per_dim])
        .to_int()
        < 0
        || packed_value[offset..offset + bytes_per_dim]
          .cmp(&self.query_max[dim][0..bytes_per_dim])
          .to_int()
          > 0
      {
        return Ok(());
      }
    }
    // If all dimensions pass the range check, mark the document as a hit
    self.hits.insert(doc_id as usize);
    Ok(())
  }

  fn visit_iterator_with_packed_value<I>(
    &mut self,
    iterator: &mut I,
    packed_value: &[u8],
  ) -> Result<()>
  where
    I: DocIdSetIterator,
  {
    if self.random.random_bool(0.5) {
      // Check the default method is correct
      IntersectVisitor::default_visit_iterator_with_packed_value_(self, iterator, packed_value)?;
    } else {
      assert_eq!(iterator.doc_id(), -1);

      let cost = iterator.cost()? as i32;
      let mut number_of_points = 0;

      while let Ok(doc_id) = iterator.next_doc() {
        if doc_id == NO_MORE_DOCS {
          break;
        }

        assert_eq!(iterator.doc_id(), doc_id);
        self.visit_with_packed_value(doc_id, packed_value)?;
        number_of_points += 1;
      }

      assert_eq!(cost, number_of_points);
      assert_eq!(iterator.doc_id(), NO_MORE_DOCS);
      assert_eq!(iterator.next_doc()?, NO_MORE_DOCS);
      assert_eq!(iterator.doc_id(), NO_MORE_DOCS);
    }
    Ok(())
  }

  fn compare(&self, min_packed: &[u8], max_packed: &[u8]) -> Result<Relation> {
    let num_index_dims = self.config.num_index_dims;
    let bytes_per_dim = self.config.bytes_per_dim;
    let mut crosses = false;

    for dim in 0..num_index_dims {
      let offset = dim * bytes_per_dim;

      if max_packed[offset..offset + bytes_per_dim]
        .cmp(&self.query_min[dim][..bytes_per_dim])
        .to_int()
        < 0
        || min_packed[offset..offset + bytes_per_dim]
          .cmp(&self.query_max[dim][..bytes_per_dim])
          .to_int()
          > 0
      {
        return Ok(Relation::CellOutsideQuery);
      } else if min_packed[offset..offset + bytes_per_dim]
        .cmp(&self.query_min[dim][..bytes_per_dim])
        .to_int()
        < 0
        || max_packed[offset..offset + bytes_per_dim]
          .cmp(&self.query_max[dim][..bytes_per_dim])
          .to_int()
          > 0
      {
        crosses = true;
      }
    }

    if crosses {
      Ok(Relation::CellCrossesQuery)
    } else {
      Ok(Relation::CellInsideQuery)
    }
  }
}
#[test]
fn test_bit_flipped_on_partition1() -> Result<()> {
  let mut random = random();

  // Generate fixed data set:
  let num_docs = at_least_usize(&mut random, 10000);
  let num_bytes_per_dim = 4;
  let num_dims = 3;

  let mut doc_values = vec![vec![vec![0u8; num_bytes_per_dim]; num_dims]; num_docs];
  let mut counter = 0u8;

  for values in doc_values.iter_mut().take(num_docs) {
    for value in values.iter_mut().take(num_dims) {
      for byte in value.iter_mut() {
        *byte = counter;
        counter = counter.wrapping_add(1);
      }
    }
  }

  let dir0 = new_mock_directory(&mut random)?;
  let result = {
    let dir = CorruptingTempOutputDirectory::new(&dir0, 22, |prefix, suffix| {
      prefix == "_0" && suffix == "bkd_left0"
    });

    verify_with_max_mb(
      &mut random,
      &dir,
      &doc_values,
      None,
      num_dims,
      num_dims,
      num_bytes_per_dim,
      50,
      0.1,
    )
  };
  dir0.close()?;
  match (result).map_err(LuceneError::into_kind) {
    Err(LuceneErrorKind::CorruptIndex(e)) => {
      assert!(e.message.contains("checksum failed (hardware problem?)"));
      Ok(())
    },
    Ok(()) => panic!("expected a corrupt-index error"),
    Err(e) => Err(e.into()),
  }
}

/// Make sure corruption on a recursed partition is caught, when BKDWriter does
/// get angry.
#[test]
fn test_bit_flippedon_partition2() -> Result<()> {
  let mut random = random();

  // Generate fixed data set:
  let num_docs = at_least_usize(&mut random, 10000);
  let num_bytes_per_dim = 4;
  let num_dims = 3;

  let mut doc_values = vec![vec![vec![0u8; num_bytes_per_dim]; num_dims]; num_docs];
  let mut counter = 0u8;

  for values in doc_values.iter_mut().take(num_docs) {
    for value in values.iter_mut().take(num_dims) {
      for byte in value.iter_mut() {
        *byte = counter;
        counter = counter.wrapping_add(1);
      }
    }
  }

  let dir0 = new_mock_directory(&mut random)?;
  let result = {
    let dir =
      CorruptingTempOutputDirectory::new(&dir0, 22072, |_prefix, suffix| suffix == "bkd_left0");

    verify_with_max_mb(
      &mut random,
      &dir,
      &doc_values,
      None,
      num_dims,
      num_dims,
      num_bytes_per_dim,
      50,
      0.1,
    )
  };
  dir0.close()?;
  match result {
    Err(t) => assert_corruption_detected(&t),
    Ok(()) => panic!("expected a corrupt-index error"),
  }
}

fn assert_corruption_detected(t: &LuceneError) -> Result<()> {
  if let LuceneErrorKind::CorruptIndex(e) = t.kind()
    && e.message.contains("checksum failed (hardware problem?)")
  {
    return Ok(());
  }

  if let Some(LuceneErrorKind::CorruptIndex(e)) = t.get_suppressed()?.map(LuceneError::kind)
    && e.message.contains("checksum failed (hardware problem?)")
  {
    return Ok(());
  }

  panic!("did not see a suppressed corrupt-index error");
}

struct IntersectVisitorMock2 {
  last_doc_id: i32,
}
impl IntersectVisitorMock2 {
  fn new() -> Self {
    Self { last_doc_id: -1 }
  }
}
impl IntersectVisitor for IntersectVisitorMock2 {
  fn visit(&mut self, doc_id: i32) -> Result<()> {
    assert!(
      doc_id > self.last_doc_id,
      "lastDocID={} docID={}",
      self.last_doc_id,
      doc_id
    );
    self.last_doc_id = doc_id;
    Ok(())
  }

  fn visit_with_packed_value(&mut self, doc_id: i32, _packed_value: &[u8]) -> Result<()> {
    self.visit(doc_id)
  }

  fn compare(&self, _min_packed_value: &[u8], _max_packed_value: &[u8]) -> Result<Relation> {
    Ok(Relation::CellCrossesQuery)
  }
}
#[test]
fn test_tie_break_order() -> Result<()> {
  let mut random = random();
  let dir = new_directory_shared(&mut random)?;
  let num_docs = 10_000;

  let config = BKDConfig::new(1, 1, 4, 2)?;
  let mut writer = BKDWriter::new(
    num_docs + 1,
    dir.as_ref(),
    "tmp",
    config,
    0.01,
    num_docs as i64,
  )?;

  let bytes = [0u8; 4];
  for doc_id in 0..num_docs {
    writer.add(&bytes, doc_id)?;
  }

  let mut out = dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;

  let finalizer = writer.finish(&mut out)?.unwrap();
  let fp = out.get_file_pointer()?;
  writer.write_index(&mut out, None, &finalizer)?;
  out.close()?;

  let mut input = dir.open_input("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
  input.seek(fp)?;
  let sub_point_values = get_point_values(Arc::new(Mutex::new(input)))?;
  let point_values = sub_point_values;
  point_values.intersect(&mut IntersectVisitorMock2::new())?;
  Ok(())
}
struct IntersectVisitorMock3 {
  previous: Option<Vec<u8>>,
  has_changed: bool,
  num_data_dims: usize,
  num_bytes_per_dim: usize,
}
impl IntersectVisitorMock3 {
  fn new(num_data_dims: usize, num_bytes_per_dim: usize) -> Self {
    Self {
      previous: None,
      has_changed: false,
      num_data_dims,
      num_bytes_per_dim,
    }
  }
}
impl IntersectVisitor for IntersectVisitorMock3 {
  fn visit(&mut self, _doc_id: i32) -> Result<()> {
    Err(LuceneError::unsupported_operation(""))
  }

  fn visit_with_packed_value(&mut self, _doc_id: i32, packed_value: &[u8]) -> Result<()> {
    let len = self.num_data_dims * self.num_bytes_per_dim;
    if self.previous.is_none() {
      let mut value = vec![0u8; len];
      value.copy_from(&packed_value[..len], 0);
      self.previous = Some(value);
    } else if let Some(prev) = &mut self.previous {
      let mismatch = packed_value.eq(prev.as_slice());
      if !mismatch {
        if !self.has_changed {
          self.has_changed = true;
          prev.copy_from(&packed_value[..len], 0);
        } else {
          return Err(LuceneError::illegal_state(
            "Points are not in optimal order",
          ));
        }
      }
    }
    Ok(())
  }

  fn compare(&self, _min_packed_value: &[u8], _max_packed_value: &[u8]) -> Result<Relation> {
    Ok(Relation::CellCrossesQuery)
  }
}
#[test]
fn test_check_data_dim_optimal_order() -> Result<()> {
  let mut random = random();
  let dir = new_directory_shared(&mut random)?;
  let num_values = at_least(&mut random, 5000);
  let max_points_in_leaf_node = TestUtil::next_usize(&mut random, 50, 500);
  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 1, 4);
  let max_mb = 3.0 + 3.0 * random.random::<f64>();
  let num_index_dims = TestUtil::next_usize(&mut random, 1, 8);
  let num_data_dims = TestUtil::next_usize(&mut random, num_index_dims, 8);

  let mut point_value1 = vec![0u8; num_data_dims * num_bytes_per_dim];
  let mut point_value2 = vec![0u8; num_data_dims * num_bytes_per_dim];
  random.fill_bytes(&mut point_value1);
  random.fill_bytes(&mut point_value2);

  // Equal index dimensions but different data dimensions
  for i in 0..num_index_dims {
    let offset = i * num_bytes_per_dim;
    point_value2.copy_from(&point_value1[offset..offset + num_bytes_per_dim], offset);
  }

  let config = BKDConfig::new(
    num_data_dims,
    num_index_dims,
    num_bytes_per_dim,
    max_points_in_leaf_node,
  )?;

  let index_fp;
  {
    let mut writer = BKDWriter::new(
      2 * num_values,
      dir.as_ref(),
      "_temp",
      config.clone(),
      max_mb,
      (2 * num_values) as i64,
    )?;

    for i in 0..num_values {
      writer.add(&point_value1, i)?;
      writer.add(&point_value2, i)?;
    }

    let mut out = dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
    let finalizer = writer.finish(&mut out)?.unwrap();
    index_fp = out.get_file_pointer()?;
    writer.write_index(&mut out, None, &finalizer)?;
    writer.close()?;
  }

  let mut point_in = dir.open_input("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
  point_in.seek(index_fp)?;

  let sub_point_values = get_point_values(Arc::new(Mutex::new(point_in)))?;
  let point_values = sub_point_values;
  point_values.intersect(&mut IntersectVisitorMock3::new(
    num_data_dims,
    num_bytes_per_dim,
  ))?;
  Ok(())
}
struct IntersectVisitorMock4<'a> {
  count: &'a mut [i32],
  random: RefCell<StdRng>,
}

impl<'a> IntersectVisitorMock4<'a> {
  fn new(count: &'a mut [i32], random: u64) -> Self {
    let random = RefCell::new(random_from_seed(random));
    Self { count, random }
  }
}
impl IntersectVisitor for IntersectVisitorMock4<'_> {
  fn visit(&mut self, _doc_id: i32) -> Result<()> {
    self.count[0] += 1;
    Ok(())
  }

  fn visit_with_packed_value(&mut self, doc_id: i32, _packed_value: &[u8]) -> Result<()> {
    self.visit(doc_id)
  }

  fn compare(&self, _min_packed_value: &[u8], _max_packed_value: &[u8]) -> Result<Relation> {
    if self.random.borrow_mut().random_range(0..7) == 1 {
      Ok(Relation::CellCrossesQuery)
    } else {
      Ok(Relation::CellInsideQuery)
    }
  }
}
#[test]
fn test_2d_long_ords_offline() -> Result<()> {
  let mut random = random();
  let dir = new_directory_shared(&mut random)?;
  let num_docs = 100_000;

  let config = BKDConfig::new(2, 2, 4, 2)?;
  let mut writer = BKDWriter::new(
    num_docs + 1,
    dir.as_ref(),
    "tmp",
    config,
    0.01,
    num_docs as i64,
  )?;

  let mut buffer = [0u8; 2 * 4];
  for doc_id in 0..num_docs {
    random.fill_bytes(&mut buffer);
    writer.add(&buffer, doc_id)?;
  }

  let fp;
  {
    let mut out = dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
    let finalizer = writer.finish(&mut out)?.unwrap();
    fp = out.get_file_pointer()?;
    writer.write_index(&mut out, None, &finalizer)?;
  }

  let mut input = dir.open_input("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
  input.seek(fp)?;
  let sub_point_values = get_point_values(Arc::new(Mutex::new(input)))?;
  let point_values = sub_point_values;

  let mut count = [0];
  let mut visitor = IntersectVisitorMock4::new(&mut count, random.next_u64());
  point_values.intersect(&mut visitor)?;
  assert_eq!(count[0], num_docs);

  Ok(())
}
struct IntersectVisitorMock5<'a> {
  count: &'a mut [i32],
  random: RefCell<StdRng>,
  num_index_dims: usize,
  bytes_per_dim: usize,
  num_dims: usize,
}
impl<'a> IntersectVisitorMock5<'a> {
  fn new(
    count: &'a mut [i32],
    random: u64,
    num_index_dims: usize,
    bytes_per_dim: usize,
    num_dims: usize,
  ) -> Self {
    let random = RefCell::new(random_from_seed(random));
    Self {
      count,
      random,
      num_index_dims,
      bytes_per_dim,
      num_dims,
    }
  }
}
impl IntersectVisitor for IntersectVisitorMock5<'_> {
  fn visit(&mut self, _doc_id: i32) -> Result<()> {
    self.count[0] += 1;
    Ok(())
  }

  fn visit_with_packed_value(&mut self, doc_id: i32, packed_value: &[u8]) -> Result<()> {
    assert_eq!(packed_value.len(), (self.num_dims * self.bytes_per_dim));
    self.visit(doc_id)
  }

  fn compare(&self, min_packed: &[u8], max_packed: &[u8]) -> Result<Relation> {
    assert_eq!(min_packed.len(), (self.num_index_dims * self.bytes_per_dim));
    assert_eq!(max_packed.len(), (self.num_index_dims * self.bytes_per_dim));
    if self.random.borrow_mut().random_range(0..7) == 1 {
      Ok(Relation::CellCrossesQuery)
    } else {
      Ok(Relation::CellInsideQuery)
    }
  }
}
#[test]
fn test_wasted_leading_bytes() -> Result<()> {
  let mut random = random();
  let num_dims = TestUtil::next_usize(&mut random, 1, MAX_INDEX_DIMENSIONS);
  let num_index_dims = TestUtil::next_usize(&mut random, 1, num_dims);
  let bytes_per_dim = MAX_NUM_BYTES;
  let bytes_used = TestUtil::next_usize(&mut random, 1, 3);

  let dir = new_fs_directory(&mut random, create_temp_dir()?)?;
  let num_docs = at_least(&mut random, 10000);
  let config = BKDConfig::new(num_dims, num_index_dims, bytes_per_dim, 32)?;

  let mut writer = BKDWriter::new(
    num_docs + 1,
    dir.as_ref(),
    "tmp",
    config.clone(),
    1.0,
    num_docs as i64,
  )?;

  let mut tmp = vec![0u8; bytes_used];
  let mut buffer = vec![0u8; num_dims * bytes_per_dim];

  for doc_id in 0..num_docs {
    for dim in 0..num_dims {
      random.fill_bytes(&mut tmp);
      let offset = dim * bytes_per_dim + (bytes_per_dim - bytes_used);
      buffer.copy_from(&tmp, offset);
    }
    writer.add(&buffer, doc_id)?;
  }
  let fp;
  {
    let mut out = dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;

    let finalizer = writer.finish(&mut out)?.unwrap();
    fp = out.get_file_pointer()?;
    writer.write_index(&mut out, None, &finalizer)?;
  }
  let mut input = dir.open_input("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
  input.seek(fp)?;
  let sub_point_values = get_point_values(Arc::new(Mutex::new(input)))?;
  let point_values = sub_point_values;

  let mut count = [0];
  let mut visitor = IntersectVisitorMock5::new(
    &mut count,
    random.next_u64(),
    num_index_dims,
    bytes_per_dim,
    num_dims,
  );
  point_values.intersect(&mut visitor)?;
  assert_eq!(count[0], num_docs);

  Ok(())
}
struct IntersectVisitorMock6;
impl IntersectVisitor for IntersectVisitorMock6 {
  fn visit(&mut self, _doc_id: i32) -> Result<()> {
    Ok(())
  }

  fn visit_with_packed_value(&mut self, _doc_id: i32, _packed_value: &[u8]) -> Result<()> {
    Ok(())
  }

  fn compare(&self, _min_packed_value: &[u8], _max_packed_value: &[u8]) -> Result<Relation> {
    Ok(Relation::CellInsideQuery)
  }
}
struct IntersectVisitorMock7;
impl IntersectVisitor for IntersectVisitorMock7 {
  fn visit(&mut self, _doc_id: i32) -> Result<()> {
    Ok(())
  }

  fn visit_with_packed_value(&mut self, _doc_id: i32, _packed_value: &[u8]) -> Result<()> {
    Ok(())
  }

  fn compare(&self, _min_packed_value: &[u8], _max_packed_value: &[u8]) -> Result<Relation> {
    Ok(Relation::CellOutsideQuery)
  }
}
struct IntersectVisitorMock8<'a> {
  unique_point_value: &'a [u8],
  num_bytes_per_dim: usize,
}
impl IntersectVisitor for IntersectVisitorMock8<'_> {
  fn visit(&mut self, _doc_id: i32) -> Result<()> {
    Ok(())
  }

  fn visit_with_packed_value(&mut self, _doc_id: i32, _packed_value: &[u8]) -> Result<()> {
    Ok(())
  }

  fn compare(&self, min_packed_value: &[u8], max_packed_value: &[u8]) -> Result<Relation> {
    if self.unique_point_value[..self.num_bytes_per_dim]
      .cmp(&max_packed_value[..self.num_bytes_per_dim])
      .to_int()
      > 0
      || self.unique_point_value[..self.num_bytes_per_dim]
        .cmp(&min_packed_value[..self.num_bytes_per_dim])
        .to_int()
        < 0
    {
      Ok(Relation::CellOutsideQuery)
    } else {
      Ok(Relation::CellCrossesQuery)
    }
  }
}
#[test]
fn test_estimate_point_count() -> Result<()> {
  let mut random = random();
  let dir = new_directory_shared(&mut random)?;
  let num_values = at_least(&mut random, 10_000);
  let max_points_in_leaf_node = TestUtil::next_usize(&mut random, 50, 500);
  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 1, 4);

  let mut point_value = vec![0u8; num_bytes_per_dim];
  let mut unique_point_value = vec![0u8; num_bytes_per_dim];
  random.fill_bytes(&mut unique_point_value);

  let config = BKDConfig::new(1, 1, num_bytes_per_dim, max_points_in_leaf_node)?;
  let mut writer = BKDWriter::new(
    num_values,
    dir.as_ref(),
    "_temp",
    config.clone(),
    DEFAULT_MAX_MB_SORT_IN_HEAP as f64,
    num_values as i64,
  )?;

  for i in 0..num_values {
    if i == num_values / 2 {
      writer.add(&unique_point_value, i)?;
    } else {
      loop {
        random.fill_bytes(&mut point_value);
        if point_value != unique_point_value {
          break;
        }
      }
      writer.add(&point_value, i)?;
    }
  }

  let index_fp;
  {
    let mut out = dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
    let finalizer = writer.finish(&mut out)?.unwrap();
    index_fp = out.get_file_pointer()?;
    writer.write_index(&mut out, None, &finalizer)?;
  }

  let mut input = dir.open_input("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;
  input.seek(index_fp)?;
  let point_values = get_point_values(Arc::new(Mutex::new(input)))?;

  // If all points match, then the point count is numValues
  assert_eq!(
    point_values.estimate_point_count(&IntersectVisitorMock6)?,
    num_values as i64
  );
  // Return 0 if no points match
  assert_eq!(
    point_values.estimate_point_count(&IntersectVisitorMock7)?,
    0
  );
  // If only one point matches, then the point count is
  // (actualMaxPointsInLeafNode + 1) / 2 in general, or maybe 2x that if
  // the point is a split value
  let point_count = point_values.estimate_point_count(&IntersectVisitorMock8 {
    unique_point_value: &unique_point_value,
    num_bytes_per_dim,
  })?;
  let last_node_point_count = num_values as usize % max_points_in_leaf_node;
  let mid = max_points_in_leaf_node.div_ceil(2) as i64;
  let mid_last = last_node_point_count.div_ceil(2) as i64;

  assert!(
    point_count == mid// common case
                // not fully populated leaf
                || point_count == mid_last
                // if the point is a split value
                || point_count == 2 * mid
                // if the point is a split value and one leaf is not fully populated
                || point_count == mid + mid_last,
    "Unexpected point count: {}",
    point_count
  );

  Ok(())
}
pub struct MutablePointTreeMock1 {
  point_value: Vec<u8>,
  num_points_added: usize,
}

impl PointTree for MutablePointTreeMock1 {
  type MutablePointTree = Self;

  fn into_mutable(self) -> PointTreeEnum<Self::MutablePointTree, Self> {
    PointTreeEnum::Mutable(self)
  }

  fn size(&self) -> Result<usize> {
    Ok(self.num_points_added)
  }

  fn visit_doc_values<IV>(&mut self, visitor: &mut IV) -> Result<()>
  where
    IV: IntersectVisitor,
  {
    for _ in 0..self.num_points_added {
      visitor.visit_with_packed_value(0, self.point_value.as_slice())?;
    }
    Ok(())
  }
}

impl Clone for MutablePointTreeMock1 {
  fn clone(&self) -> Self {
    unreachable!()
  }
}
impl TryClone for MutablePointTreeMock1 {
  fn try_clone(&self) -> Result<Self>
  where
    Self: Sized,
  {
    Ok(self.clone())
  }
}

impl MutablePointTree for MutablePointTreeMock1 {
  fn get_value<'a>(
    &'a self,
    _i: usize,
    spare: &'a mut BytesRef<Vec<u8>>,
  ) -> Result<BytesRef<&'a [u8]>> {
    Ok(BytesRef {
      bytes: &self.point_value,
      offset: spare.offset,
      length: spare.length,
    })
  }

  fn get_byte_at(&self, _i: usize, k: usize) -> u8 {
    self.point_value[k]
  }

  fn get_doc_id(&self, _i: usize) -> Result<i32> {
    Ok(0)
  }

  fn swap(&mut self, _i: usize, _j: usize) {}

  fn save(&mut self, _i: usize, _j: usize) {}

  fn restore(&mut self, _i: usize, _j: usize) {}
}
#[test]
fn test_total_point_count_validation() -> Result<()> {
  let mut random = random();
  let dir = new_directory_shared(&mut random)?;
  let num_values = 10;
  let num_points_added = 50;
  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 1, 4);
  let mut point_value = vec![0u8; num_bytes_per_dim];
  random.fill_bytes(&mut point_value);

  let mut reader = MutablePointTreeMock1 {
    point_value,
    num_points_added,
  };

  let config = BKDConfig::new(
    1,
    1,
    num_bytes_per_dim,
    BKDConfig::DEFAULT_MAX_POINTS_IN_LEAF_NODE,
  )?;

  let mut writer = BKDWriter::new(
    num_values,
    dir.as_ref(),
    "_temp",
    config,
    DEFAULT_MAX_MB_SORT_IN_HEAP as f64,
    num_values as i64,
  )?;
  let mut out = dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;

  let result = writer.write_field(&mut out, &mut reader, "test_field_name");

  assert!(matches!(
    result,
    Err(error) if error.is_illegal_state_error()
  ));
  Ok(())
}
pub struct MutablePointTreeMock2 {
  tmp_values: Vec<Vec<u8>>,
  tmp_docs: Vec<i32>,
  num_bytes_per_dim: usize,
  point_values: Vec<Vec<u8>>,
  doc_id: Vec<i32>,
}

impl PointTree for MutablePointTreeMock2 {
  type MutablePointTree = Self;

  fn into_mutable(self) -> PointTreeEnum<Self::MutablePointTree, Self> {
    PointTreeEnum::Mutable(self)
  }

  fn size(&self) -> Result<usize> {
    Ok(11)
  }

  fn visit_doc_values<IV>(&mut self, visitor: &mut IV) -> Result<()>
  where
    IV: IntersectVisitor,
  {
    for i in 0..self.size()? {
      visitor.visit_with_packed_value(self.doc_id[i], &self.point_values[i])?
    }
    Ok(())
  }
}

impl Clone for MutablePointTreeMock2 {
  fn clone(&self) -> Self {
    unreachable!()
  }
}
impl TryClone for MutablePointTreeMock2 {
  fn try_clone(&self) -> Result<Self>
  where
    Self: Sized,
  {
    Ok(self.clone())
  }
}

impl MutablePointTree for MutablePointTreeMock2 {
  fn get_value<'a>(
    &'a self,
    i: usize,
    _spare: &'a mut BytesRef<Vec<u8>>,
  ) -> Result<BytesRef<&'a [u8]>> {
    Ok(BytesRef {
      bytes: &self.point_values[i],
      offset: 0,
      length: self.num_bytes_per_dim,
    })
  }

  fn get_byte_at(&self, i: usize, k: usize) -> u8 {
    self.point_values[i][k]
  }

  fn get_doc_id(&self, i: usize) -> Result<i32> {
    Ok(self.doc_id[i])
  }

  fn swap(&mut self, i: usize, j: usize) {
    self.point_values.swap(i, j);
    self.doc_id.swap(i, j)
  }

  fn save(&mut self, i: usize, j: usize) {
    self.tmp_values[j] = self.point_values[i].clone();
    self.tmp_docs[j] = self.doc_id[i];
  }

  fn restore(&mut self, i: usize, j: usize) {
    for k in i..j {
      self.point_values[k] = self.tmp_values[k].clone();
      self.doc_id[k] = self.tmp_docs[k];
    }
  }
}
#[test]
fn test_too_many_points() -> Result<()> {
  let mut random = random();
  let dir = new_directory(&mut random)?;

  let num_values = 10;
  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 1, 4);
  let mut point_value = vec![0u8; num_bytes_per_dim];

  let mut w = BKDWriter::new(
    num_values as i32,
    &dir,
    "_temp",
    BKDConfig::new(1, 1, num_bytes_per_dim, 2)?,
    DEFAULT_MAX_MB_SORT_IN_HEAP as f64,
    num_values,
  )?;

  for i in 0..num_values {
    random.fill_bytes(&mut point_value);
    w.add(&point_value, i as i32)?;
  }

  random.fill_bytes(&mut point_value);
  let err = w
    .add(&point_value, num_values as i32)
    .expect_err("expected LuceneErrorKind::IllegalState");
  assert!(err.is_illegal_state_error());
  assert_eq!(
    err.to_string(),
    format!(
      "totalPointCount={} was passed when we were created, but we just hit {} values",
      num_values,
      num_values + 1
    )
  );
  Ok(())
}

#[test]
fn test_too_many_points_1d() -> Result<()> {
  let mut random = random();
  let dir = new_directory_shared(&mut random)?;

  let num_values: usize = 10;
  let num_bytes_per_dim = TestUtil::next_usize(&mut random, 1, 4);
  let mut point_values = vec![vec![0u8; num_bytes_per_dim]; 11];
  let mut doc_ids = vec![0i32; 11];

  for i in 0..=num_values {
    random.fill_bytes(&mut point_values[i]);
    doc_ids[i] = i as i32;
  }

  let mut reader = MutablePointTreeMock2 {
    tmp_values: vec![vec![]; num_values],
    tmp_docs: vec![],
    num_bytes_per_dim,
    point_values,
    doc_id: doc_ids,
  };

  let config = BKDConfig::new(1, 1, num_bytes_per_dim, 2)?;
  let mut writer = BKDWriter::new(
    (num_values + 1) as i32,
    dir.as_ref(),
    "_temp",
    config,
    DEFAULT_MAX_MB_SORT_IN_HEAP as f64,
    num_values as i64,
  )?;

  let mut out = dir.create_output("bkd", IO_CONTEXT_DEFAULT.as_ref().map_err(Clone::clone)?)?;

  let error = match writer.write_field(&mut out, &mut reader, "") {
    Ok(_) => panic!("writing too many points must fail"),
    Err(error) => error,
  };
  assert!(error.is_illegal_state_error());
  assert_eq!(
    "totalPointCount=10 was passed when we were created, but we just hit 11 values",
    error.to_string()
  );

  Ok(())
}
struct CorruptingTempOutputDirectory<'a, D, F> {
  in_: &'a D,
  byte_to_corrupt: usize,
  corrupted: AtomicBool,
  should_corrupt: F,
}

impl<'a, D, F> CorruptingTempOutputDirectory<'a, D, F>
where
  D: Directory,
  F: Fn(&str, &str) -> bool + Send + Sync,
{
  fn new(in_: &'a D, byte_to_corrupt: usize, should_corrupt: F) -> Self {
    Self {
      in_,
      byte_to_corrupt,
      corrupted: AtomicBool::new(false),
      should_corrupt,
    }
  }
}

impl<D, F> Display for CorruptingTempOutputDirectory<'_, D, F>
where
  D: Directory,
  F: Fn(&str, &str) -> bool + Send + Sync,
{
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "CorruptingTempOutputDirectory({})", self.in_)
  }
}

impl<D, F> CloseableRef for CorruptingTempOutputDirectory<'_, D, F>
where
  D: Directory,
  F: Fn(&str, &str) -> bool + Send + Sync,
{
  fn close(&self) -> Result<()> {
    Ok(())
  }
}

impl<D, F> HasIdentity for CorruptingTempOutputDirectory<'_, D, F>
where
  D: Directory,
  F: Fn(&str, &str) -> bool + Send + Sync,
{
  fn identity(&self) -> &Identity {
    self.in_.identity()
  }
}

impl<'a, D, F> Directory for CorruptingTempOutputDirectory<'a, D, F>
where
  D: Directory,
  D::IndexInput: CloseableRef,
  F: Fn(&str, &str) -> bool + Send + Sync,
{
  fn list_all(&self) -> Result<Vec<String>> {
    self.in_.list_all()
  }

  fn delete_file(&self, name: &str) -> Result<()> {
    self.in_.delete_file(name)
  }

  fn file_length(&self, name: &str) -> Result<usize> {
    self.in_.file_length(name)
  }

  fn create_output(&self, name: &str, context: &IOContext) -> Result<Self::IndexOutput> {
    Ok(IndexOutputEnum2::A(self.in_.create_output(name, context)?))
  }

  type IndexOutput = IndexOutputEnum2<D::IndexOutput, CorruptingIndexOutput<'a, D>>;

  fn create_temp_output(
    &self,
    prefix: &str,
    suffix: &str,
    context: &IOContext,
  ) -> Result<Self::IndexOutput> {
    let out = self.in_.create_temp_output(prefix, suffix, context)?;
    if !self.corrupted.load(Ordering::SeqCst)
      && (self.should_corrupt)(prefix, suffix)
      && !self.corrupted.swap(true, Ordering::SeqCst)
    {
      Ok(IndexOutputEnum2::B(CorruptingIndexOutput::new(
        self.in_,
        self.byte_to_corrupt,
        out,
      )))
    } else {
      Ok(IndexOutputEnum2::A(out))
    }
  }

  fn sync(&self, names: &[String]) -> Result<()> {
    self.in_.sync(names)
  }

  fn sync_metadata(&self) -> Result<()> {
    self.in_.sync_metadata()
  }

  fn rename(&self, source: &str, dest: &str) -> Result<()> {
    self.in_.rename(source, dest)
  }

  type IndexInput = D::IndexInput;

  fn open_input(&self, name: &str, context: &IOContext) -> Result<Self::IndexInput> {
    self.in_.open_input(name, context)
  }

  type Lock = D::Lock;

  fn obtain_lock(&self, name: &str) -> Result<Self::Lock> {
    self.in_.obtain_lock(name)
  }

  fn copy_from<T>(&self, from: &T, src: &str, dest: &str, context: &IOContext) -> Result<()>
  where
    T: Directory + ?Sized,
  {
    self.in_.copy_from(from, src, dest, context)
  }

  fn get_pending_deletions(&self) -> Result<std::collections::HashSet<String>> {
    self.in_.get_pending_deletions()
  }

  #[cfg(test)]
  fn is_fs_directory(&self) -> bool {
    self.in_.is_fs_directory()
  }

  fn ensure_open(&self) -> Result<()> {
    self.in_.ensure_open()
  }
}