usearch 2.25.1

Smaller & Faster Single-File Vector Search Engine from Unum
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
//! # USearch Crate for Rust
//!
//! `usearch` is a high-performance library for Approximate Nearest Neighbor (ANN) search in high-dimensional spaces.
//! It offers efficient and scalable solutions for indexing and querying dense vector spaces with support for multiple distance metrics and vector types.
//!
//! This crate wraps the native functionalities of USearch, providing Rust-friendly interfaces and integration capabilities.
//! It is designed to facilitate rapid development and deployment of applications requiring fast and accurate vector search functionalities, such as recommendation systems, image retrieval systems, and natural language processing tasks.
//!
//! ## Features
//!
//! - SIMD-accelerated distance calculations for various metrics.
//! - Support for `f32`, `f64`, `i8`, `u8`, custom `f16`, and binary (`b1x8`) vector types.
//! - Extensible with custom distance metrics and filtering predicates.
//! - Efficient serialization and deserialization for persistence and network transfers.
//!
//! ## Quick Start
//!
//! Refer to the `Index` struct for detailed usage examples.

/// Returns the version of the USearch crate.
pub fn version() -> &'static str {
    env!("CARGO_PKG_VERSION")
}

/// Returns a comma-separated list of ISAs compiled into this binary.
pub fn hardware_acceleration_compiled() -> String {
    use core::ffi::CStr;
    unsafe {
        CStr::from_ptr(ffi::hardware_acceleration_compiled())
            .to_string_lossy()
            .into_owned()
    }
}

/// Returns a comma-separated list of ISAs available at runtime (compiled AND supported by CPU).
pub fn hardware_acceleration_available() -> String {
    use core::ffi::CStr;
    unsafe {
        CStr::from_ptr(ffi::hardware_acceleration_available())
            .to_string_lossy()
            .into_owned()
    }
}

/// The key type used to identify vectors in the index.
/// It is a 64-bit unsigned integer.
pub type Key = u64;

/// The distance type used to represent the similarity between vectors.
/// It is a 32-bit floating-point number.
pub type Distance = f32;

/// Callback signature for custom metric functions, defined in the Rust layer and used in the C++ layer.
pub type StatefulMetric = unsafe extern "C" fn(
    *const std::ffi::c_void,
    *const std::ffi::c_void,
    *mut std::ffi::c_void,
) -> Distance;

/// Callback signature for custom predicate functions, defined in the Rust layer and used in the C++ layer.
pub type StatefulPredicate = unsafe extern "C" fn(Key, *mut std::ffi::c_void) -> bool;

/// Represents errors that can occur when addressing bits.
#[derive(Debug)]
pub enum BitAddressableError {
    /// Error indicating the specified index is out of the allowable range.
    IndexOutOfRange,
}

impl std::fmt::Display for BitAddressableError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match *self {
            BitAddressableError::IndexOutOfRange => write!(f, "Index out of range"),
        }
    }
}

impl std::error::Error for BitAddressableError {}

/// Trait for types that can be addressed at the bit level.
/// Provides methods to set and get individual bits within the implementing type.
pub trait BitAddressable {
    /// Sets a bit at the specified index.
    /// Returns an error if the index is out of range.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the bit to set.
    /// * `value` - The value to set the bit to (`true` for 1, `false` for 0).
    fn set_bit(&mut self, index: usize, value: bool) -> Result<(), BitAddressableError>;

    /// Gets the value of a bit at the specified index.
    /// Returns an error if the index is out of range.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the bit to retrieve.
    fn get_bit(&self, index: usize) -> Result<bool, BitAddressableError>;
}

/// A byte-wide bit vector type that provides low-level control over individual bits.
///
/// This struct represents a single byte (8 bits) and enables manipulation and
/// interpretation of individual bits via various utility functions.
#[repr(transparent)]
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct b1x8(pub u8);

impl b1x8 {
    /// Casts a slice of `u8` bytes to a slice of `b1x8`, allowing bit-level operations on byte slices.
    pub fn from_u8s(slice: &[u8]) -> &[Self] {
        unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const Self, slice.len()) }
    }

    /// Casts a mutable slice of `u8` bytes to a mutable slice of `b1x8`, enabling mutable
    /// bit-level operations on byte slices.
    pub fn from_mut_u8s(slice: &mut [u8]) -> &mut [Self] {
        unsafe { std::slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut Self, slice.len()) }
    }

    /// Converts a slice of `b1x8` back to a slice of `u8`, useful for reading bit-level manipulations
    /// in byte-oriented contexts.
    pub fn to_u8s(slice: &[Self]) -> &[u8] {
        unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len()) }
    }

    /// Converts a mutable slice of `b1x8` back to a mutable slice of `u8`, enabling further
    /// modifications on the original byte data after bit-level manipulations.
    pub fn to_mut_u8s(slice: &mut [Self]) -> &mut [u8] {
        unsafe { std::slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut u8, slice.len()) }
    }
}

/// A struct representing a half-precision floating-point number based on the IEEE 754 standard.
///
/// This struct uses an `i16` to store the half-precision floating-point data, which includes
/// 1 sign bit, 5 exponent bits, and 10 mantissa bits.
#[repr(transparent)]
#[allow(non_camel_case_types)]
#[derive(Clone, Copy)]
pub struct f16(i16);

impl f16 {
    /// Casts a slice of `i16` integers to a slice of `f16`, allowing operations on half-precision
    /// floating-point data stored in standard 16-bit integer arrays.
    pub fn from_i16s(slice: &[i16]) -> &[Self] {
        unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const Self, slice.len()) }
    }

    /// Casts a mutable slice of `i16` integers to a mutable slice of `f16`, enabling mutable operations
    /// on half-precision floating-point data.
    pub fn from_mut_i16s(slice: &mut [i16]) -> &mut [Self] {
        unsafe { std::slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut Self, slice.len()) }
    }

    /// Converts a slice of `f16` back to a slice of `i16`, useful for storage or manipulation in formats
    /// that require standard integer types.
    pub fn to_i16s(slice: &[Self]) -> &[i16] {
        unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const i16, slice.len()) }
    }

    /// Converts a mutable slice of `f16` back to a mutable slice of `i16`, enabling further
    /// modifications on the original integer data after operations involving half-precision
    /// floating-point numbers.
    pub fn to_mut_i16s(slice: &mut [Self]) -> &mut [i16] {
        unsafe { std::slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut i16, slice.len()) }
    }
}

impl BitAddressable for b1x8 {
    /// Sets a bit at a specific index within the byte.
    ///
    /// # Arguments
    ///
    /// * `index` - The 0-based index of the bit to set, ranging from 0 to 7.
    /// * `value` - The boolean value to assign to the bit (`true` for 1, `false` for 0).
    ///
    /// # Returns
    ///
    /// This method returns `Ok(())` if the bit was successfully set, or an `Err(BitAddressableError::IndexOutOfRange)`
    /// if the provided index is outside the valid range.
    fn set_bit(&mut self, index: usize, value: bool) -> Result<(), BitAddressableError> {
        if index >= 8 {
            Err(BitAddressableError::IndexOutOfRange)
        } else {
            if value {
                self.0 |= 1 << index;
            } else {
                self.0 &= !(1 << index);
            }
            Ok(())
        }
    }

    /// Retrieves the value of a bit at a specific index within the byte.
    ///
    /// # Arguments
    ///
    /// * `index` - The 0-based index of the bit to retrieve, ranging from 0 to 7.
    ///
    /// # Returns
    ///
    /// Returns `Ok(true)` if the bit is set (1), `Ok(false)` if the bit is not set (0),
    /// or an `Err(BitAddressableError::IndexOutOfRange)` if the provided index is outside
    /// the valid range.
    fn get_bit(&self, index: usize) -> Result<bool, BitAddressableError> {
        if index >= 8 {
            Err(BitAddressableError::IndexOutOfRange)
        } else {
            Ok(((self.0 >> index) & 1) == 1)
        }
    }
}

impl BitAddressable for [b1x8] {
    /// Sets a bit at a specific index across the slice of `b1x8`.
    fn set_bit(&mut self, index: usize, value: bool) -> Result<(), BitAddressableError> {
        let byte_index = index / 8;
        let bit_index = index % 8;
        if byte_index >= self.len() {
            Err(BitAddressableError::IndexOutOfRange)
        } else {
            self[byte_index].set_bit(bit_index, value)
        }
    }

    /// Gets a bit at a specific index across the slice of `b1x8`.
    fn get_bit(&self, index: usize) -> Result<bool, BitAddressableError> {
        let byte_index = index / 8;
        let bit_index = index % 8;
        if byte_index >= self.len() {
            Err(BitAddressableError::IndexOutOfRange)
        } else {
            self[byte_index].get_bit(bit_index)
        }
    }
}

impl PartialEq for f16 {
    fn eq(&self, other: &Self) -> bool {
        // Check for NaN values first (exponent all ones and non-zero mantissa)
        let nan_self = (self.0 & 0x7C00) == 0x7C00 && (self.0 & 0x03FF) != 0;
        let nan_other = (other.0 & 0x7C00) == 0x7C00 && (other.0 & 0x03FF) != 0;
        if nan_self || nan_other {
            return false;
        }

        self.0 == other.0
    }
}

impl std::fmt::Debug for b1x8 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:08b}", self.0)
    }
}

impl std::fmt::Debug for f16 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let bits = self.0;
        let sign = (bits >> 15) & 1;
        let exponent = (bits >> 10) & 0x1F;
        let mantissa = bits & 0x3FF;
        write!(f, "{}|{:05b}|{:010b}", sign, exponent, mantissa)
    }
}

#[cxx::bridge]
pub mod ffi {

    /// The metric kind used to differentiate built-in distance functions.
    #[derive(Debug)]
    #[repr(i32)]
    enum MetricKind {
        Unknown,
        /// The Inner Product metric, defined as `IP = 1 - sum(a[i] * b[i])`.
        IP,
        /// The squared Euclidean Distance metric, defined as `L2 = sum((a[i] - b[i])^2)`.
        L2sq,
        /// The Cosine Distance metric, defined as `Cos = 1 - sum(a[i] * b[i]) / (sqrt(sum(a[i]^2)) * sqrt(sum(b[i]^2)))`.
        Cos,
        /// The Pearson Correlation metric.
        Pearson,
        /// The Haversine (Great Circle) Distance metric.
        Haversine,
        /// The Jensen Shannon Divergence metric.
        Divergence,
        /// The bit-level Hamming Distance metric, defined as the number of differing bits.
        Hamming,
        /// The bit-level Tanimoto (Jaccard) metric, defined as the number of intersecting bits divided by the number of union bits.
        Tanimoto,
        /// The bit-level Sorensen metric.
        Sorensen,
    }

    /// The scalar kind used to differentiate built-in vector element types.
    #[derive(Debug)]
    #[repr(i32)]
    enum ScalarKind {
        Unknown,
        /// 64-bit double-precision IEEE 754 floating-point number.
        F64,
        /// 32-bit single-precision IEEE 754 floating-point number.
        F32,
        /// 16-bit brain floating-point number.
        BF16,
        /// 16-bit half-precision IEEE 754 floating-point number (different from `bf16`).
        F16,
        /// 8-bit floating point: 1 sign + 5 exponent + 2 mantissa.
        E5M2,
        /// 8-bit floating point: 1 sign + 4 exponent + 3 mantissa.
        E4M3,
        /// 8-bit floating point: 1 sign + 3 exponent + 2 mantissa, range +/-28.
        E3M2,
        /// 8-bit floating point: 1 sign + 2 exponent + 3 mantissa, range +/-7.5.
        E2M3,
        /// 8-bit signed integer.
        I8,
        /// 8-bit unsigned integer.
        U8,
        /// 1-bit binary value, packed 8 per byte.
        B1,
    }

    /// The resulting matches from a search operation.
    /// It contains the keys and distances of the closest vectors.
    #[derive(Debug)]
    struct Matches {
        keys: Vec<u64>,
        distances: Vec<f32>,
    }

    /// Detailed memory statistics with separate breakdowns for the graph
    /// and vectors allocator tapes.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    struct MemoryStats {
        /// Total memory allocated by the graph structure allocator, in bytes.
        graph_allocated: usize,
        /// Memory wasted due to alignment in the graph allocator, in bytes.
        graph_wasted: usize,
        /// Reserved but unused memory in the graph allocator, in bytes.
        graph_reserved: usize,
        /// Total memory allocated by the vectors data allocator, in bytes.
        vectors_allocated: usize,
        /// Memory wasted due to alignment in the vectors allocator, in bytes.
        vectors_wasted: usize,
        /// Reserved but unused memory in the vectors allocator, in bytes.
        vectors_reserved: usize,
    }

    /// The index options used to configure the dense index during creation.
    /// It contains the number of dimensions, the metric kind, the scalar kind,
    /// the connectivity, the expansion values, and the multi-flag.
    #[derive(Debug, PartialEq)]
    struct IndexOptions {
        dimensions: usize,
        metric: MetricKind,
        quantization: ScalarKind,
        connectivity: usize,
        expansion_add: usize,
        expansion_search: usize,
        multi: bool,
    }

    // C++ types and signatures exposed to Rust.
    unsafe extern "C++" {
        include!("lib.hpp");

        pub fn hardware_acceleration_compiled() -> *const c_char;
        pub fn hardware_acceleration_available() -> *const c_char;

        /// Low-level C++ interface that is further wrapped into the high-level `Index`
        type NativeIndex;

        pub fn expansion_add(self: &NativeIndex) -> usize;
        pub fn expansion_search(self: &NativeIndex) -> usize;
        pub fn change_expansion_add(self: &NativeIndex, n: usize);
        pub fn change_expansion_search(self: &NativeIndex, n: usize);
        pub fn change_metric_kind(self: &NativeIndex, metric: MetricKind);

        /// Changes the metric function used to calculate the distance between vectors.
        /// Avoids the `std::ffi::c_void` type and the `StatefulMetric` type, that the FFI
        /// does not support, replacing them with basic pointer-sized integer types.
        /// The first two arguments are the pointers to the vectors to compare, and the third
        /// argument is the `metric_state` propagated from the Rust layer.
        pub fn change_metric(self: &NativeIndex, metric: usize, metric_state: usize);

        pub fn new_native_index(options: &IndexOptions) -> Result<UniquePtr<NativeIndex>>;
        pub fn reserve(self: &NativeIndex, capacity: usize) -> Result<()>;
        pub fn reserve_capacity_and_threads(
            self: &NativeIndex,
            capacity: usize,
            threads: usize,
        ) -> Result<()>;

        pub fn dimensions(self: &NativeIndex) -> usize;
        pub fn connectivity(self: &NativeIndex) -> usize;
        pub fn size(self: &NativeIndex) -> usize;
        pub fn capacity(self: &NativeIndex) -> usize;
        pub fn serialized_length(self: &NativeIndex) -> usize;

        pub fn add_f64(self: &NativeIndex, key: u64, vector: &[f64]) -> Result<()>;
        pub fn add_f32(self: &NativeIndex, key: u64, vector: &[f32]) -> Result<()>;
        pub fn add_f16(self: &NativeIndex, key: u64, vector: &[i16]) -> Result<()>;
        pub fn add_i8(self: &NativeIndex, key: u64, vector: &[i8]) -> Result<()>;
        pub fn add_u8(self: &NativeIndex, key: u64, vector: &[u8]) -> Result<()>;
        pub fn add_b1x8(self: &NativeIndex, key: u64, vector: &[u8]) -> Result<()>;

        pub fn search_f64(self: &NativeIndex, query: &[f64], count: usize) -> Result<Matches>;
        pub fn search_f32(self: &NativeIndex, query: &[f32], count: usize) -> Result<Matches>;
        pub fn search_f16(self: &NativeIndex, query: &[i16], count: usize) -> Result<Matches>;
        pub fn search_i8(self: &NativeIndex, query: &[i8], count: usize) -> Result<Matches>;
        pub fn search_u8(self: &NativeIndex, query: &[u8], count: usize) -> Result<Matches>;
        pub fn search_b1x8(self: &NativeIndex, query: &[u8], count: usize) -> Result<Matches>;

        pub fn exact_search_f64(self: &NativeIndex, query: &[f64], count: usize)
            -> Result<Matches>;
        pub fn exact_search_f32(self: &NativeIndex, query: &[f32], count: usize)
            -> Result<Matches>;
        pub fn exact_search_f16(self: &NativeIndex, query: &[i16], count: usize)
            -> Result<Matches>;
        pub fn exact_search_i8(self: &NativeIndex, query: &[i8], count: usize) -> Result<Matches>;
        pub fn exact_search_u8(self: &NativeIndex, query: &[u8], count: usize) -> Result<Matches>;
        pub fn exact_search_b1x8(self: &NativeIndex, query: &[u8], count: usize)
            -> Result<Matches>;

        pub fn filtered_search_f64(
            self: &NativeIndex,
            query: &[f64],
            count: usize,
            filter: usize,
            filter_state: usize,
        ) -> Result<Matches>;
        pub fn filtered_search_f32(
            self: &NativeIndex,
            query: &[f32],
            count: usize,
            filter: usize,
            filter_state: usize,
        ) -> Result<Matches>;
        pub fn filtered_search_f16(
            self: &NativeIndex,
            query: &[i16],
            count: usize,
            filter: usize,
            filter_state: usize,
        ) -> Result<Matches>;
        pub fn filtered_search_i8(
            self: &NativeIndex,
            query: &[i8],
            count: usize,
            filter: usize,
            filter_state: usize,
        ) -> Result<Matches>;
        pub fn filtered_search_u8(
            self: &NativeIndex,
            query: &[u8],
            count: usize,
            filter: usize,
            filter_state: usize,
        ) -> Result<Matches>;
        pub fn filtered_search_b1x8(
            self: &NativeIndex,
            query: &[u8],
            count: usize,
            filter: usize,
            filter_state: usize,
        ) -> Result<Matches>;

        pub fn get_f64(self: &NativeIndex, key: u64, buffer: &mut [f64]) -> Result<usize>;
        pub fn get_f32(self: &NativeIndex, key: u64, buffer: &mut [f32]) -> Result<usize>;
        pub fn get_f16(self: &NativeIndex, key: u64, buffer: &mut [i16]) -> Result<usize>;
        pub fn get_i8(self: &NativeIndex, key: u64, buffer: &mut [i8]) -> Result<usize>;
        pub fn get_u8(self: &NativeIndex, key: u64, buffer: &mut [u8]) -> Result<usize>;
        pub fn get_b1x8(self: &NativeIndex, key: u64, buffer: &mut [u8]) -> Result<usize>;

        pub fn remove(self: &NativeIndex, key: u64) -> Result<usize>;
        pub fn rename(self: &NativeIndex, from: u64, to: u64) -> Result<usize>;
        pub fn contains(self: &NativeIndex, key: u64) -> bool;
        pub fn count(self: &NativeIndex, key: u64) -> usize;

        pub fn save(self: &NativeIndex, path: &str) -> Result<()>;
        pub fn load(self: &NativeIndex, path: &str) -> Result<()>;
        pub fn view(self: &NativeIndex, path: &str) -> Result<()>;
        pub fn reset(self: &NativeIndex) -> Result<()>;
        pub fn memory_usage(self: &NativeIndex) -> usize;
        pub fn memory_stats(self: &NativeIndex) -> MemoryStats;
        pub fn hardware_acceleration(self: &NativeIndex) -> *const c_char;

        pub fn save_to_buffer(self: &NativeIndex, buffer: &mut [u8]) -> Result<()>;
        pub fn load_from_buffer(self: &NativeIndex, buffer: &[u8]) -> Result<()>;
        pub fn view_from_buffer(self: &NativeIndex, buffer: &[u8]) -> Result<()>;
    }
}

// Re-export the FFI structs and enums at the crate root for easy access
pub use ffi::{IndexOptions, MemoryStats, MetricKind, ScalarKind};

/// Represents custom metric functions for calculating distances between vectors in various formats.
///
/// This enum allows the encapsulation of custom distance calculation logic for vectors of different
/// data types, facilitating the use of custom metrics in vector space operations. Each variant of this
/// enum holds a boxed function pointer (`std::boxed::Box<dyn Fn(...) -> Distance + Send + Sync>`) that defines
/// the distance calculation between two vectors of a specific type. The function returns a `Distance`, which
/// is typically a floating-point value representing the calculated distance between the two vectors.
///
/// # Variants
///
/// - `B1X8Metric`: A metric function for binary vectors packed in `u8` containers, represented here by `b1x8`.
/// - `I8Metric`: A metric function for vectors of 8-bit signed integers (`i8`).
/// - `U8Metric`: A metric function for vectors of 8-bit unsigned integers (`u8`).
/// - `F16Metric`: A metric function for vectors of 16-bit half-precision floating-point numbers (`f16`).
/// - `F32Metric`: A metric function for vectors of 32-bit floating-point numbers (`f32`).
/// - `F64Metric`: A metric function for vectors of 64-bit floating-point numbers (`f64`).
///
/// Each metric function takes two pointers to the vectors of the respective type and returns a `Distance`.
///
/// # Usage
///
/// Custom metric functions can be used to define how distances are calculated between vectors, enabling
/// the implementation of various distance metrics such as Euclidean distance, Manhattan distance, or
/// Cosine similarity, depending on the specific requirements of the application.
///
/// # Safety
///
/// Since these functions operate on raw pointers, care must be taken to ensure that the pointers are valid
/// and that the lifetime of the referenced data extends at least as long as the lifetime of the metric
/// function's use. Improper use of these functions can lead to undefined behavior.
///
/// # Examples
///
/// ```
/// use usearch::{Distance, f16, b1x8};
///
/// let euclidean_fn = Box::new(|a: *const f32, b: *const f32| -> f32 {
///     let dimensions = 256;
///     let a = unsafe { std::slice::from_raw_parts(a, dimensions) };
///     let b = unsafe { std::slice::from_raw_parts(b, dimensions) };
///     a.iter().zip(b.iter())
///         .map(|(a, b)| (*a - *b).powi(2))
///         .sum::<f32>()
///         .sqrt()
/// });
/// ```
///
/// In this example, `dimensions` should be defined and valid for the vectors `a` and `b`.
pub enum MetricFunction {
    B1X8Metric(*mut std::boxed::Box<dyn Fn(*const b1x8, *const b1x8) -> Distance + Send + Sync>),
    I8Metric(*mut std::boxed::Box<dyn Fn(*const i8, *const i8) -> Distance + Send + Sync>),
    U8Metric(*mut std::boxed::Box<dyn Fn(*const u8, *const u8) -> Distance + Send + Sync>),
    F16Metric(*mut std::boxed::Box<dyn Fn(*const f16, *const f16) -> Distance + Send + Sync>),
    F32Metric(*mut std::boxed::Box<dyn Fn(*const f32, *const f32) -> Distance + Send + Sync>),
    F64Metric(*mut std::boxed::Box<dyn Fn(*const f64, *const f64) -> Distance + Send + Sync>),
}

/// Approximate Nearest Neighbors search index for dense vectors.
///
/// The `Index` struct provides an abstraction over a dense vector space, allowing
/// for efficient addition, search, and management of high-dimensional vectors.
/// It supports various distance metrics and vector types through generic interfaces.
///
/// # Examples
///
/// Basic usage:
///
/// ```rust
/// use usearch::{Index, IndexOptions, MetricKind, ScalarKind};
///
/// let mut options = IndexOptions::default();
/// options.dimensions = 4; // Set the number of dimensions for vectors
/// options.metric = MetricKind::Cos; // Use cosine similarity for distance measurement
/// options.quantization = ScalarKind::F32; // Use 32-bit floating point numbers
///
/// let index = Index::new(&options).expect("Failed to create index.");
/// index.reserve(1000).expect("Failed to reserve capacity.");
///
/// // Add vectors to the index
/// let vector1: Vec<f32> = vec![0.0, 1.0, 0.0, 1.0];
/// let vector2: Vec<f32> = vec![1.0, 0.0, 1.0, 0.0];
/// index.add(1, &vector1).expect("Failed to add vector1.");
/// index.add(2, &vector2).expect("Failed to add vector2.");
///
/// // Search for the nearest neighbors to a query vector
/// let query: Vec<f32> = vec![0.5, 0.5, 0.5, 0.5];
/// let results = index.search(&query, 5).expect("Search failed.");
/// for (key, distance) in results.keys.iter().zip(results.distances.iter()) {
///     println!("Key: {}, Distance: {}", key, distance);
/// }
/// ```
/// For more examples, including how to add vectors to the index and perform searches,
/// refer to the individual method documentation.
pub struct Index {
    inner: cxx::UniquePtr<ffi::NativeIndex>,
    metric_fn: Option<MetricFunction>,
}

unsafe impl Send for Index {}
unsafe impl Sync for Index {}

impl Drop for Index {
    fn drop(&mut self) {
        if let Some(metric) = &self.metric_fn {
            match metric {
                MetricFunction::B1X8Metric(pointer) => unsafe {
                    drop(Box::from_raw(*pointer));
                },
                MetricFunction::I8Metric(pointer) => unsafe {
                    drop(Box::from_raw(*pointer));
                },
                MetricFunction::U8Metric(pointer) => unsafe {
                    drop(Box::from_raw(*pointer));
                },
                MetricFunction::F16Metric(pointer) => unsafe {
                    drop(Box::from_raw(*pointer));
                },
                MetricFunction::F32Metric(pointer) => unsafe {
                    drop(Box::from_raw(*pointer));
                },
                MetricFunction::F64Metric(pointer) => unsafe {
                    drop(Box::from_raw(*pointer));
                },
            }
        }
    }
}

impl Default for ffi::IndexOptions {
    fn default() -> Self {
        Self {
            dimensions: 256,
            metric: MetricKind::Cos,
            quantization: ScalarKind::BF16,
            connectivity: 0,
            expansion_add: 0,
            expansion_search: 0,
            multi: false,
        }
    }
}

impl Clone for ffi::IndexOptions {
    fn clone(&self) -> Self {
        ffi::IndexOptions {
            dimensions: (self.dimensions),
            metric: (self.metric),
            quantization: (self.quantization),
            connectivity: (self.connectivity),
            expansion_add: (self.expansion_add),
            expansion_search: (self.expansion_search),
            multi: (self.multi),
        }
    }
}

/// The `VectorType` trait defines operations for managing and querying vectors
/// in an index. It supports generic operations on vectors of different types,
/// allowing for the addition, retrieval, and search of vectors within an index.
pub trait VectorType {
    /// Adds a vector to the index under the specified key.
    ///
    /// # Parameters
    /// - `index`: A reference to the `Index` where the vector is to be added.
    /// - `key`: The key under which the vector should be stored.
    /// - `vector`: A slice representing the vector to be added.
    ///
    /// # Returns
    /// - `Ok(())` if the vector was successfully added to the index.
    /// - `Err(cxx::Exception)` if an error occurred during the operation.
    fn add(index: &Index, key: Key, vector: &[Self]) -> Result<(), cxx::Exception>
    where
        Self: Sized;

    /// Retrieves a vector from the index by its key.
    ///
    /// # Parameters
    /// - `index`: A reference to the `Index` from which the vector is to be retrieved.
    /// - `key`: The key of the vector to retrieve.
    /// - `buffer`: A mutable slice where the retrieved vector will be stored. The size of the
    ///   buffer determines the maximum number of elements that can be retrieved.
    ///
    /// # Returns
    /// - `Ok(usize)` indicating the number of elements actually written into the `buffer`.
    /// - `Err(cxx::Exception)` if an error occurred during the operation.
    fn get(index: &Index, key: Key, buffer: &mut [Self]) -> Result<usize, cxx::Exception>
    where
        Self: Sized;

    /// Performs a search in the index using the given query vector, returning
    /// up to `count` closest matches.
    ///
    /// # Parameters
    /// - `index`: A reference to the `Index` where the search is to be performed.
    /// - `query`: A slice representing the query vector.
    /// - `count`: The maximum number of matches to return.
    ///
    /// # Returns
    /// - `Ok(ffi::Matches)` containing the matches found.
    /// - `Err(cxx::Exception)` if an error occurred during the search operation.
    fn search(index: &Index, query: &[Self], count: usize) -> Result<ffi::Matches, cxx::Exception>
    where
        Self: Sized;

    /// Performs an exact (brute force) search in the index using the given query vector, returning
    /// up to `count` closest matches. This search checks all vectors in the index, guaranteeing to find
    /// the true nearest neighbors, but will be slower especially for large indices.
    ///
    /// # Parameters
    /// - `index`: A reference to the `Index` where the search is to be performed.
    /// - `query`: A slice representing the query vector.
    /// - `count`: The maximum number of matches to return.
    ///
    /// # Returns
    /// - `Ok(ffi::Matches)` containing the matches found.
    /// - `Err(cxx::Exception)` if an error occurred during the search operation.
    fn exact_search(
        index: &Index,
        query: &[Self],
        count: usize,
    ) -> Result<ffi::Matches, cxx::Exception>
    where
        Self: Sized;

    /// Performs a filtered search in the index using a query vector and a custom
    /// filter function, returning up to `count` matches that satisfy the filter.
    ///
    /// # Parameters
    /// - `index`: A reference to the `Index` where the search is to be performed.
    /// - `query`: A slice representing the query vector.
    /// - `count`: The maximum number of matches to return.
    /// - `filter`: A closure that takes a `Key` and returns `true` if the corresponding
    ///   vector should be included in the search results, or `false` otherwise.
    ///
    /// # Returns
    /// - `Ok(ffi::Matches)` containing the matches that satisfy the filter.
    /// - `Err(cxx::Exception)` if an error occurred during the filtered search operation.
    fn filtered_search<F>(
        index: &Index,
        query: &[Self],
        count: usize,
        filter: F,
    ) -> Result<ffi::Matches, cxx::Exception>
    where
        Self: Sized,
        F: Fn(Key) -> bool;

    /// Changes the metric used for distance calculations within the index.
    ///
    /// # Parameters
    /// - `index`: A mutable reference to the `Index` for which the metric is to be changed.
    /// - `metric`: A boxed closure that defines the new metric for distance calculation. The
    ///   closure must take two pointers to elements of type `Self` and return a `Distance`.
    ///
    /// # Returns
    /// - `Ok(())` if the metric was successfully changed.
    /// - `Err(cxx::Exception)` if an error occurred during the operation.
    fn change_metric(
        index: &mut Index,
        metric: std::boxed::Box<dyn Fn(*const Self, *const Self) -> Distance + Send + Sync>,
    ) -> Result<(), cxx::Exception>
    where
        Self: Sized;
}

impl VectorType for f32 {
    fn search(index: &Index, query: &[Self], count: usize) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.search_f32(query, count)
    }

    fn exact_search(
        index: &Index,
        query: &[Self],
        count: usize,
    ) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.exact_search_f32(query, count)
    }

    fn get(index: &Index, key: Key, vector: &mut [Self]) -> Result<usize, cxx::Exception> {
        index.inner.get_f32(key, vector)
    }

    fn add(index: &Index, key: Key, vector: &[Self]) -> Result<(), cxx::Exception> {
        index.inner.add_f32(key, vector)
    }

    fn filtered_search<F>(
        index: &Index,
        query: &[Self],
        count: usize,
        filter: F,
    ) -> Result<ffi::Matches, cxx::Exception>
    where
        Self: Sized,
        F: Fn(Key) -> bool,
    {
        // Trampoline is the function that knows how to call the Rust closure.
        extern "C" fn trampoline<F: Fn(u64) -> bool>(key: u64, closure_address: usize) -> bool {
            let closure = closure_address as *const F;
            unsafe { (*closure)(key) }
        }

        // Temporarily cast the closure to a raw pointer for passing.
        let trampoline_fn: usize = trampoline::<F> as *const () as usize;
        let closure_address: usize = &filter as *const F as usize;
        index
            .inner
            .filtered_search_f32(query, count, trampoline_fn, closure_address)
    }

    fn change_metric(
        index: &mut Index,
        metric: std::boxed::Box<dyn Fn(*const Self, *const Self) -> Distance + Send + Sync>,
    ) -> Result<(), cxx::Exception> {
        // Store the metric function in the Index.
        type MetricFn = Box<dyn Fn(*const f32, *const f32) -> Distance>;
        index.metric_fn = Some(MetricFunction::F32Metric(Box::into_raw(Box::new(metric))));

        // Trampoline is the function that knows how to call the Rust closure.
        // The `first` is a pointer to the first vector, `second` is a pointer to the second vector,
        // and `index_wrapper` is a pointer to the `index` itself, from which we can infer the metric function
        // and the number of dimensions.
        extern "C" fn trampoline(first: usize, second: usize, closure_address: usize) -> Distance {
            let first_ptr = first as *const f32;
            let second_ptr = second as *const f32;
            let closure: *mut MetricFn = closure_address as *mut MetricFn;
            unsafe { (*closure)(first_ptr, second_ptr) }
        }

        let trampoline_fn: usize = trampoline as *const () as usize;
        let closure_address = match index.metric_fn {
            Some(MetricFunction::F32Metric(metric)) => metric as *mut () as usize,
            _ => panic!("Expected F32Metric"),
        };
        index.inner.change_metric(trampoline_fn, closure_address);

        Ok(())
    }
}

impl VectorType for i8 {
    fn search(index: &Index, query: &[Self], count: usize) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.search_i8(query, count)
    }

    fn exact_search(
        index: &Index,
        query: &[Self],
        count: usize,
    ) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.exact_search_i8(query, count)
    }

    fn get(index: &Index, key: Key, vector: &mut [Self]) -> Result<usize, cxx::Exception> {
        index.inner.get_i8(key, vector)
    }

    fn add(index: &Index, key: Key, vector: &[Self]) -> Result<(), cxx::Exception> {
        index.inner.add_i8(key, vector)
    }

    fn filtered_search<F>(
        index: &Index,
        query: &[Self],
        count: usize,
        filter: F,
    ) -> Result<ffi::Matches, cxx::Exception>
    where
        Self: Sized,
        F: Fn(Key) -> bool,
    {
        // Trampoline is the function that knows how to call the Rust closure.
        extern "C" fn trampoline<F: Fn(u64) -> bool>(key: u64, closure_address: usize) -> bool {
            let closure = closure_address as *const F;
            unsafe { (*closure)(key) }
        }

        // Temporarily cast the closure to a raw pointer for passing.
        let trampoline_fn: usize = trampoline::<F> as *const () as usize;
        let closure_address: usize = &filter as *const F as usize;
        index
            .inner
            .filtered_search_i8(query, count, trampoline_fn, closure_address)
    }
    fn change_metric(
        index: &mut Index,
        metric: std::boxed::Box<dyn Fn(*const Self, *const Self) -> Distance + Send + Sync>,
    ) -> Result<(), cxx::Exception> {
        // Store the metric function in the Index.
        type MetricFn = Box<dyn Fn(*const i8, *const i8) -> Distance>;
        index.metric_fn = Some(MetricFunction::I8Metric(Box::into_raw(Box::new(metric))));

        // Trampoline is the function that knows how to call the Rust closure.
        // The `first` is a pointer to the first vector, `second` is a pointer to the second vector,
        // and `index_wrapper` is a pointer to the `index` itself, from which we can infer the metric function
        // and the number of dimensions.
        extern "C" fn trampoline(first: usize, second: usize, closure_address: usize) -> Distance {
            let first_ptr = first as *const i8;
            let second_ptr = second as *const i8;
            let closure: *mut MetricFn = closure_address as *mut MetricFn;
            unsafe { (*closure)(first_ptr, second_ptr) }
        }

        let trampoline_fn: usize = trampoline as *const () as usize;
        let closure_address = match index.metric_fn {
            Some(MetricFunction::I8Metric(metric)) => metric as *mut () as usize,
            _ => panic!("Expected I8Metric"),
        };
        index.inner.change_metric(trampoline_fn, closure_address);

        Ok(())
    }
}

impl VectorType for u8 {
    fn search(index: &Index, query: &[Self], count: usize) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.search_u8(query, count)
    }

    fn exact_search(
        index: &Index,
        query: &[Self],
        count: usize,
    ) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.exact_search_u8(query, count)
    }

    fn get(index: &Index, key: Key, vector: &mut [Self]) -> Result<usize, cxx::Exception> {
        index.inner.get_u8(key, vector)
    }

    fn add(index: &Index, key: Key, vector: &[Self]) -> Result<(), cxx::Exception> {
        index.inner.add_u8(key, vector)
    }

    fn filtered_search<F>(
        index: &Index,
        query: &[Self],
        count: usize,
        filter: F,
    ) -> Result<ffi::Matches, cxx::Exception>
    where
        Self: Sized,
        F: Fn(Key) -> bool,
    {
        extern "C" fn trampoline<F: Fn(u64) -> bool>(key: u64, closure_address: usize) -> bool {
            let closure = closure_address as *const F;
            unsafe { (*closure)(key) }
        }

        let trampoline_fn: usize = trampoline::<F> as *const () as usize;
        let closure_address: usize = &filter as *const F as usize;
        index
            .inner
            .filtered_search_u8(query, count, trampoline_fn, closure_address)
    }
    fn change_metric(
        index: &mut Index,
        metric: std::boxed::Box<dyn Fn(*const Self, *const Self) -> Distance + Send + Sync>,
    ) -> Result<(), cxx::Exception> {
        type MetricFn = Box<dyn Fn(*const u8, *const u8) -> Distance>;
        index.metric_fn = Some(MetricFunction::U8Metric(Box::into_raw(Box::new(metric))));

        extern "C" fn trampoline(first: usize, second: usize, closure_address: usize) -> Distance {
            let first_ptr = first as *const u8;
            let second_ptr = second as *const u8;
            let closure: *mut MetricFn = closure_address as *mut MetricFn;
            unsafe { (*closure)(first_ptr, second_ptr) }
        }

        let trampoline_fn: usize = trampoline as *const () as usize;
        let closure_address = match index.metric_fn {
            Some(MetricFunction::U8Metric(metric)) => metric as *mut () as usize,
            _ => panic!("Expected U8Metric"),
        };
        index.inner.change_metric(trampoline_fn, closure_address);

        Ok(())
    }
}

impl VectorType for f64 {
    fn search(index: &Index, query: &[Self], count: usize) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.search_f64(query, count)
    }

    fn exact_search(
        index: &Index,
        query: &[Self],
        count: usize,
    ) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.exact_search_f64(query, count)
    }

    fn get(index: &Index, key: Key, vector: &mut [Self]) -> Result<usize, cxx::Exception> {
        index.inner.get_f64(key, vector)
    }

    fn add(index: &Index, key: Key, vector: &[Self]) -> Result<(), cxx::Exception> {
        index.inner.add_f64(key, vector)
    }

    fn filtered_search<F>(
        index: &Index,
        query: &[Self],
        count: usize,
        filter: F,
    ) -> Result<ffi::Matches, cxx::Exception>
    where
        Self: Sized,
        F: Fn(Key) -> bool,
    {
        // Trampoline is the function that knows how to call the Rust closure.
        extern "C" fn trampoline<F: Fn(u64) -> bool>(key: u64, closure_address: usize) -> bool {
            let closure = closure_address as *const F;
            unsafe { (*closure)(key) }
        }

        // Temporarily cast the closure to a raw pointer for passing.
        let trampoline_fn: usize = trampoline::<F> as *const () as usize;
        let closure_address: usize = &filter as *const F as usize;
        index
            .inner
            .filtered_search_f64(query, count, trampoline_fn, closure_address)
    }
    fn change_metric(
        index: &mut Index,
        metric: std::boxed::Box<dyn Fn(*const Self, *const Self) -> Distance + Send + Sync>,
    ) -> Result<(), cxx::Exception> {
        // Store the metric function in the Index.
        type MetricFn = Box<dyn Fn(*const f64, *const f64) -> Distance>;
        index.metric_fn = Some(MetricFunction::F64Metric(Box::into_raw(Box::new(metric))));

        // Trampoline is the function that knows how to call the Rust closure.
        // The `first` is a pointer to the first vector, `second` is a pointer to the second vector,
        // and `index_wrapper` is a pointer to the `index` itself, from which we can infer the metric function
        // and the number of dimensions.
        extern "C" fn trampoline(first: usize, second: usize, closure_address: usize) -> Distance {
            let first_ptr = first as *const f64;
            let second_ptr = second as *const f64;
            let closure: *mut MetricFn = closure_address as *mut MetricFn;
            unsafe { (*closure)(first_ptr, second_ptr) }
        }

        let trampoline_fn: usize = trampoline as *const () as usize;
        let closure_address = match index.metric_fn {
            Some(MetricFunction::F64Metric(metric)) => metric as *mut () as usize,
            _ => panic!("Expected F64Metric"),
        };
        index.inner.change_metric(trampoline_fn, closure_address);

        Ok(())
    }
}

impl VectorType for f16 {
    fn search(index: &Index, query: &[Self], count: usize) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.search_f16(f16::to_i16s(query), count)
    }

    fn exact_search(
        index: &Index,
        query: &[Self],
        count: usize,
    ) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.exact_search_f16(f16::to_i16s(query), count)
    }

    fn get(index: &Index, key: Key, vector: &mut [Self]) -> Result<usize, cxx::Exception> {
        index.inner.get_f16(key, f16::to_mut_i16s(vector))
    }

    fn add(index: &Index, key: Key, vector: &[Self]) -> Result<(), cxx::Exception> {
        index.inner.add_f16(key, f16::to_i16s(vector))
    }

    fn filtered_search<F>(
        index: &Index,
        query: &[Self],
        count: usize,
        filter: F,
    ) -> Result<ffi::Matches, cxx::Exception>
    where
        Self: Sized,
        F: Fn(Key) -> bool,
    {
        // Trampoline is the function that knows how to call the Rust closure.
        extern "C" fn trampoline<F: Fn(u64) -> bool>(key: u64, closure_address: usize) -> bool {
            let closure = closure_address as *const F;
            unsafe { (*closure)(key) }
        }

        // Temporarily cast the closure to a raw pointer for passing.
        let trampoline_fn: usize = trampoline::<F> as *const () as usize;
        let closure_address: usize = &filter as *const F as usize;
        index
            .inner
            .filtered_search_f16(f16::to_i16s(query), count, trampoline_fn, closure_address)
    }

    fn change_metric(
        index: &mut Index,
        metric: std::boxed::Box<dyn Fn(*const Self, *const Self) -> Distance + Send + Sync>,
    ) -> Result<(), cxx::Exception> {
        // Store the metric function in the Index.
        type MetricFn = Box<dyn Fn(*const f16, *const f16) -> Distance>;
        index.metric_fn = Some(MetricFunction::F16Metric(Box::into_raw(Box::new(metric))));

        // Trampoline is the function that knows how to call the Rust closure.
        // The `first` is a pointer to the first vector, `second` is a pointer to the second vector,
        // and `index_wrapper` is a pointer to the `index` itself, from which we can infer the metric function
        // and the number of dimensions.
        extern "C" fn trampoline(first: usize, second: usize, closure_address: usize) -> Distance {
            let first_ptr = first as *const f16;
            let second_ptr = second as *const f16;
            let closure: *mut MetricFn = closure_address as *mut MetricFn;
            unsafe { (*closure)(first_ptr, second_ptr) }
        }

        let trampoline_fn: usize = trampoline as *const () as usize;
        let closure_address = match index.metric_fn {
            Some(MetricFunction::F16Metric(metric)) => metric as *mut () as usize,
            _ => panic!("Expected F16Metric"),
        };
        index.inner.change_metric(trampoline_fn, closure_address);

        Ok(())
    }
}

impl VectorType for b1x8 {
    fn search(index: &Index, query: &[Self], count: usize) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.search_b1x8(b1x8::to_u8s(query), count)
    }

    fn exact_search(
        index: &Index,
        query: &[Self],
        count: usize,
    ) -> Result<ffi::Matches, cxx::Exception> {
        index.inner.exact_search_b1x8(b1x8::to_u8s(query), count)
    }

    fn get(index: &Index, key: Key, vector: &mut [Self]) -> Result<usize, cxx::Exception> {
        index.inner.get_b1x8(key, b1x8::to_mut_u8s(vector))
    }

    fn add(index: &Index, key: Key, vector: &[Self]) -> Result<(), cxx::Exception> {
        index.inner.add_b1x8(key, b1x8::to_u8s(vector))
    }

    fn filtered_search<F>(
        index: &Index,
        query: &[Self],
        count: usize,
        filter: F,
    ) -> Result<ffi::Matches, cxx::Exception>
    where
        Self: Sized,
        F: Fn(Key) -> bool,
    {
        // Trampoline is the function that knows how to call the Rust closure.
        extern "C" fn trampoline<F: Fn(u64) -> bool>(key: u64, closure_address: usize) -> bool {
            let closure = closure_address as *const F;
            unsafe { (*closure)(key) }
        }

        // Temporarily cast the closure to a raw pointer for passing.
        let trampoline_fn: usize = trampoline::<F> as *const () as usize;
        let closure_address: usize = &filter as *const F as usize;
        index
            .inner
            .filtered_search_b1x8(b1x8::to_u8s(query), count, trampoline_fn, closure_address)
    }

    fn change_metric(
        index: &mut Index,
        metric: std::boxed::Box<dyn Fn(*const Self, *const Self) -> Distance + Send + Sync>,
    ) -> Result<(), cxx::Exception> {
        // Store the metric function in the Index.
        type MetricFn = Box<dyn Fn(*const b1x8, *const b1x8) -> Distance>;
        index.metric_fn = Some(MetricFunction::B1X8Metric(Box::into_raw(Box::new(metric))));

        // Trampoline is the function that knows how to call the Rust closure.
        // The `first` is a pointer to the first vector, `second` is a pointer to the second vector,
        // and `index_wrapper` is a pointer to the `index` itself, from which we can infer the metric function
        // and the number of dimensions.
        extern "C" fn trampoline(first: usize, second: usize, closure_address: usize) -> Distance {
            let first_ptr = first as *const b1x8;
            let second_ptr = second as *const b1x8;
            let closure: *mut MetricFn = closure_address as *mut MetricFn;
            unsafe { (*closure)(first_ptr, second_ptr) }
        }

        let trampoline_fn: usize = trampoline as *const () as usize;
        let closure_address = match index.metric_fn {
            Some(MetricFunction::B1X8Metric(metric)) => metric as *mut () as usize,
            _ => panic!("Expected F1X8Metric"),
        };
        index.inner.change_metric(trampoline_fn, closure_address);

        Ok(())
    }
}

impl Index {
    pub fn new(options: &ffi::IndexOptions) -> Result<Self, cxx::Exception> {
        match ffi::new_native_index(options) {
            Ok(inner) => Result::Ok(Self {
                inner,
                metric_fn: None,
            }),
            Err(err) => Err(err),
        }
    }

    /// Retrieves the expansion value used during index creation.
    pub fn expansion_add(self: &Index) -> usize {
        self.inner.expansion_add()
    }

    /// Retrieves the expansion value used during search.
    pub fn expansion_search(self: &Index) -> usize {
        self.inner.expansion_search()
    }

    /// Updates the expansion value used during index creation. Rarely used.
    pub fn change_expansion_add(self: &Index, n: usize) {
        self.inner.change_expansion_add(n)
    }

    /// Updates the expansion value used during search operations.
    pub fn change_expansion_search(self: &Index, n: usize) {
        self.inner.change_expansion_search(n)
    }

    /// Changes the metric kind used to calculate the distance between vectors.
    pub fn change_metric_kind(self: &Index, metric: ffi::MetricKind) {
        self.inner.change_metric_kind(metric)
    }

    /// Overrides the metric function used to calculate the distance between vectors.
    pub fn change_metric<T: VectorType>(
        self: &mut Index,
        metric: std::boxed::Box<dyn Fn(*const T, *const T) -> Distance + Send + Sync>,
    ) {
        T::change_metric(self, metric).unwrap();
    }

    /// Retrieves the hardware acceleration information.
    pub fn hardware_acceleration(&self) -> String {
        use core::ffi::CStr;
        unsafe {
            let c_str = CStr::from_ptr(self.inner.hardware_acceleration());
            c_str.to_string_lossy().into_owned()
        }
    }

    /// Performs k-Approximate Nearest Neighbors (kANN) Search for closest vectors to the provided query.
    ///
    /// # Arguments
    ///
    /// * `query` - A slice containing the query vector data.
    /// * `count` - The maximum number of neighbors to search for.
    ///
    /// # Returns
    ///
    /// A `Result` containing the matches found.
    pub fn search<T: VectorType>(
        self: &Index,
        query: &[T],
        count: usize,
    ) -> Result<ffi::Matches, cxx::Exception> {
        T::search(self, query, count)
    }

    /// Performs exact (brute force) Nearest Neighbors Search for closest vectors to the provided query.
    /// This search checks all vectors in the index, guaranteeing to find the true nearest neighbors,
    /// but may be slower for large indices.
    ///
    /// # Arguments
    ///
    /// * `query` - A slice containing the query vector data.
    /// * `count` - The maximum number of neighbors to search for.
    ///
    /// # Returns
    ///
    /// A `Result` containing the matches found.
    pub fn exact_search<T: VectorType>(
        self: &Index,
        query: &[T],
        count: usize,
    ) -> Result<ffi::Matches, cxx::Exception> {
        T::exact_search(self, query, count)
    }

    /// Performs k-Approximate Nearest Neighbors (kANN) Search for closest vectors to the provided query
    /// satisfying a custom filter function.
    ///
    /// # Arguments
    ///
    /// * `query` - A slice containing the query vector data.
    /// * `count` - The maximum number of neighbors to search for.
    /// * `filter` - A closure that takes a `Key` and returns `true` if the corresponding vector should be included in the search results, or `false` otherwise.
    ///
    /// # Returns
    ///
    /// A `Result` containing the matches found.
    pub fn filtered_search<T: VectorType, F>(
        self: &Index,
        query: &[T],
        count: usize,
        filter: F,
    ) -> Result<ffi::Matches, cxx::Exception>
    where
        F: Fn(Key) -> bool,
    {
        T::filtered_search(self, query, count, filter)
    }

    /// Adds a vector with a specified key to the index.
    ///
    /// # Arguments
    ///
    /// * `key` - The key associated with the vector.
    /// * `vector` - A slice containing the vector data.
    pub fn add<T: VectorType>(self: &Index, key: Key, vector: &[T]) -> Result<(), cxx::Exception> {
        T::add(self, key, vector)
    }

    /// Extracts one or more vectors matching the specified key.
    /// The `vector` slice must be a multiple of the number of dimensions in the index.
    /// After the execution, return the number `X` of vectors found.
    /// The vector slice's first `X * dimensions` elements will be filled.
    ///
    /// If you are a novice user, consider `export`.
    ///
    /// # Arguments
    ///
    /// * `key` - The key associated with the vector.
    /// * `vector` - A slice containing the vector data.
    pub fn get<T: VectorType>(
        self: &Index,
        key: Key,
        vector: &mut [T],
    ) -> Result<usize, cxx::Exception> {
        T::get(self, key, vector)
    }

    /// Extracts one or more vectors matching specified key into supplied resizable vector.
    /// The `vector` is resized to a multiple of the number of dimensions in the index.
    ///
    /// # Arguments
    ///
    /// * `key` - The key associated with the vector.
    /// * `vector` - A mutable vector containing the vector data.
    pub fn export<T: VectorType + Default + Clone>(
        self: &Index,
        key: Key,
        vector: &mut Vec<T>,
    ) -> Result<usize, cxx::Exception> {
        let dim = self.dimensions();
        let max_matches = self.count(key);
        vector.resize(dim * max_matches, T::default());
        let matches = T::get(self, key, &mut vector[..])?;
        vector.resize(dim * matches, T::default());
        Ok(matches)
    }

    /// Reserves memory for a specified number of incoming vectors.
    ///
    /// # Arguments
    ///
    /// * `capacity` - The desired total capacity, including the current size.
    pub fn reserve(self: &Index, capacity: usize) -> Result<(), cxx::Exception> {
        self.inner.reserve(capacity)
    }

    /// Reserves memory for a specified number of incoming vectors & active threads.
    ///
    /// # Arguments
    ///
    /// * `capacity` - The desired total capacity, including the current size.
    /// * `threads` - The number of threads to use for the operation.
    pub fn reserve_capacity_and_threads(
        self: &Index,
        capacity: usize,
        threads: usize,
    ) -> Result<(), cxx::Exception> {
        self.inner.reserve_capacity_and_threads(capacity, threads)
    }

    /// Retrieves the number of dimensions in the vectors indexed.
    pub fn dimensions(self: &Index) -> usize {
        self.inner.dimensions()
    }

    /// Retrieves the connectivity parameter that limits connections-per-node in the graph.
    pub fn connectivity(self: &Index) -> usize {
        self.inner.connectivity()
    }

    /// Retrieves the current number of vectors in the index.
    pub fn size(self: &Index) -> usize {
        self.inner.size()
    }

    /// Retrieves the total capacity of the index, including reserved space.
    pub fn capacity(self: &Index) -> usize {
        self.inner.capacity()
    }

    /// Reports expected file size after serialization.
    pub fn serialized_length(self: &Index) -> usize {
        self.inner.serialized_length()
    }

    /// Removes all vectors associated with the given key from the index.
    /// In a multi-index, a single key may map to several vectors; this removes all of them.
    ///
    /// # Arguments
    ///
    /// * `key` - The key of the vector(s) to be removed.
    ///
    /// # Returns
    ///
    /// The number of vectors that were removed. Zero when the key is absent.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// index.add(42, &vec)?;
    /// assert_eq!(index.remove(42)?, 1);
    /// assert_eq!(index.remove(42)?, 0); // already gone
    /// ```
    pub fn remove(self: &Index, key: Key) -> Result<usize, cxx::Exception> {
        self.inner.remove(key)
    }

    /// Reassigns every vector stored under `from` to the new key `to`.
    /// The original key is freed and subsequent lookups should use `to`.
    ///
    /// # Arguments
    ///
    /// * `from` - The current key.
    /// * `to`   - The key that will replace it.
    ///
    /// # Returns
    ///
    /// The number of vectors that were reassigned. Zero when `from` is absent.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// index.add(1, &vec)?;
    /// assert_eq!(index.rename(1, 2)?, 1);
    /// assert!(!index.contains(1));
    /// assert!(index.contains(2));
    /// ```
    pub fn rename(self: &Index, from: Key, to: Key) -> Result<usize, cxx::Exception> {
        self.inner.rename(from, to)
    }

    /// Checks whether at least one vector with the given key exists in the index.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to look up.
    pub fn contains(self: &Index, key: Key) -> bool {
        self.inner.contains(key)
    }

    /// Returns the number of vectors stored under the given key.
    /// Always 0 or 1 for a unique index; may be greater than 1 when `multi` is enabled.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to look up.
    pub fn count(self: &Index, key: Key) -> usize {
        self.inner.count(key)
    }

    /// Saves the index to a specified file.
    ///
    /// # Arguments
    ///
    /// * `path` - The file path where the index will be saved.
    pub fn save(self: &Index, path: &str) -> Result<(), cxx::Exception> {
        self.inner.save(path)
    }

    /// Loads the index from a specified file.
    ///
    /// # Arguments
    ///
    /// * `path` - The file path from where the index will be loaded.
    pub fn load(self: &Index, path: &str) -> Result<(), cxx::Exception> {
        self.inner.load(path)
    }

    /// Creates a view of the index from a file without loading it into memory.
    ///
    /// # Arguments
    ///
    /// * `path` - The file path from where the view will be created.
    pub fn view(self: &Index, path: &str) -> Result<(), cxx::Exception> {
        self.inner.view(path)
    }

    /// Erases all members from the index, closes files, and returns RAM to OS.
    pub fn reset(self: &Index) -> Result<(), cxx::Exception> {
        self.inner.reset()
    }

    /// A relatively accurate lower bound on the amount of memory consumed by the system.
    /// In practice, its error will be below 10%.
    pub fn memory_usage(self: &Index) -> usize {
        self.inner.memory_usage()
    }

    /// Returns detailed memory statistics with separate breakdowns for the graph
    /// and vectors allocator tapes.
    pub fn memory_stats(self: &Index) -> ffi::MemoryStats {
        self.inner.memory_stats()
    }

    /// Saves the index to a specified file.
    ///
    /// # Arguments
    ///
    /// * `buffer` - The buffer where the index will be saved.
    pub fn save_to_buffer(self: &Index, buffer: &mut [u8]) -> Result<(), cxx::Exception> {
        self.inner.save_to_buffer(buffer)
    }

    /// Loads the index from a specified file.
    ///
    /// # Arguments
    ///
    /// * `buffer` - The buffer from where the index will be loaded.
    pub fn load_from_buffer(self: &Index, buffer: &[u8]) -> Result<(), cxx::Exception> {
        self.inner.load_from_buffer(buffer)
    }

    /// Creates a view of the index from a file without loading it into memory.
    ///
    /// # Arguments
    ///
    /// * `buffer` - The buffer from where the view will be created.
    ///
    /// # Safety
    ///
    /// This function is marked as `unsafe` because it stores a pointer to the input buffer.
    /// The caller must ensure that the buffer outlives the index and is not dropped
    /// or modified for the duration of the index's use. Dereferencing a pointer to a
    /// temporary buffer after it has been dropped can lead to undefined behavior,
    /// which violates Rust's memory safety guarantees.
    ///
    /// Example of misuse:
    ///
    /// ```rust,ignore
    /// let index: usearch::Index = usearch::new_index(&usearch::IndexOptions::default()).unwrap();
    ///
    /// let temporary = vec![0u8; 100];
    /// index.view_from_buffer(&temporary);
    /// std::mem::drop(temporary);
    ///
    /// let query = vec![0.0; 256];
    /// let results = index.search(&query, 5).unwrap();
    /// ```
    ///
    /// The above example would result in use-after-free and undefined behavior.
    pub unsafe fn view_from_buffer(self: &Index, buffer: &[u8]) -> Result<(), cxx::Exception> {
        self.inner.view_from_buffer(buffer)
    }
}

pub fn new_index(options: &ffi::IndexOptions) -> Result<Index, cxx::Exception> {
    Index::new(options)
}

#[cfg(test)]
mod tests {
    use crate::ffi::IndexOptions;
    use crate::ffi::MetricKind;
    use crate::ffi::ScalarKind;

    use crate::b1x8;
    use crate::new_index;
    use crate::Index;
    use crate::Key;

    use std::env;

    #[test]
    fn print_specs() {
        println!("--------------------------------------------------");
        println!("OS: {}", env::consts::OS);
        println!(
            "Rust version: {}",
            env::var("RUST_VERSION").unwrap_or_else(|_| "unknown".into())
        );

        // Create indexes with different configurations, ordered by descending dynamic range
        let f64_index = Index::new(&IndexOptions {
            dimensions: 256,
            metric: MetricKind::Cos,
            quantization: ScalarKind::F64,
            ..Default::default()
        })
        .unwrap();

        let f32_index = Index::new(&IndexOptions {
            dimensions: 256,
            metric: MetricKind::Cos,
            quantization: ScalarKind::F32,
            ..Default::default()
        })
        .unwrap();

        let bf16_index = Index::new(&IndexOptions {
            dimensions: 256,
            metric: MetricKind::Cos,
            quantization: ScalarKind::BF16,
            ..Default::default()
        })
        .unwrap();

        let f16_index = Index::new(&IndexOptions {
            dimensions: 256,
            metric: MetricKind::Cos,
            quantization: ScalarKind::F16,
            ..Default::default()
        })
        .unwrap();

        let e5m2_index = Index::new(&IndexOptions {
            dimensions: 256,
            metric: MetricKind::Cos,
            quantization: ScalarKind::E5M2,
            ..Default::default()
        })
        .unwrap();

        let e4m3_index = Index::new(&IndexOptions {
            dimensions: 256,
            metric: MetricKind::Cos,
            quantization: ScalarKind::E4M3,
            ..Default::default()
        })
        .unwrap();

        let i8_index = Index::new(&IndexOptions {
            dimensions: 256,
            metric: MetricKind::Cos,
            quantization: ScalarKind::I8,
            ..Default::default()
        })
        .unwrap();

        let u8_index = Index::new(&IndexOptions {
            dimensions: 256,
            metric: MetricKind::Cos,
            quantization: ScalarKind::U8,
            ..Default::default()
        })
        .unwrap();

        let b1_index = Index::new(&IndexOptions {
            dimensions: 256,
            metric: MetricKind::Hamming,
            quantization: ScalarKind::B1,
            ..Default::default()
        })
        .unwrap();

        println!(
            "f64 hardware acceleration: {}",
            f64_index.hardware_acceleration()
        );
        println!(
            "f32 hardware acceleration: {}",
            f32_index.hardware_acceleration()
        );
        println!(
            "bf16 hardware acceleration: {}",
            bf16_index.hardware_acceleration()
        );
        println!(
            "f16 hardware acceleration: {}",
            f16_index.hardware_acceleration()
        );
        println!(
            "e5m2 hardware acceleration: {}",
            e5m2_index.hardware_acceleration()
        );
        println!(
            "e4m3 hardware acceleration: {}",
            e4m3_index.hardware_acceleration()
        );
        println!(
            "i8 hardware acceleration: {}",
            i8_index.hardware_acceleration()
        );
        println!(
            "u8 hardware acceleration: {}",
            u8_index.hardware_acceleration()
        );
        println!(
            "b1 hardware acceleration: {}",
            b1_index.hardware_acceleration()
        );
        println!("--------------------------------------------------");
    }

    #[test]
    fn new_index_does_not_preallocate_members() {
        let options = IndexOptions {
            dimensions: 8,
            quantization: ScalarKind::F32,
            ..Default::default()
        };
        let index = Index::new(&options).unwrap();

        // Regression check: constructor should preserve `index_limits_t{}` behavior
        // and avoid reserving member slots up front.
        assert_eq!(index.capacity(), 0);
    }

    #[test]
    fn index_survives_box_and_arc_moves_after_construction() {
        let options = IndexOptions {
            dimensions: 4,
            quantization: ScalarKind::F32,
            ..Default::default()
        };
        let vector = [0.25f32, 0.5, 0.75, 1.0];

        let boxed = Box::new(Index::new(&options).unwrap());
        boxed.reserve(8).unwrap();
        boxed.add(7, &vector).unwrap();
        let boxed_matches = boxed.search(&vector, 1).unwrap();
        assert_eq!(boxed_matches.keys.first().copied(), Some(7));

        let arc = std::sync::Arc::new(Index::new(&options).unwrap());
        let moved_arc = std::sync::Arc::clone(&arc);
        moved_arc.reserve_capacity_and_threads(8, 2).unwrap();
        moved_arc.add(9, &vector).unwrap();
        let arc_matches = arc.search(&vector, 1).unwrap();
        assert_eq!(arc_matches.keys.first().copied(), Some(9));
    }

    #[test]
    fn add_get_vector() {
        let options = IndexOptions {
            dimensions: 5,
            quantization: ScalarKind::F32,
            ..Default::default()
        };
        let index = Index::new(&options).unwrap();
        assert!(index.reserve(10).is_ok());

        let first: [f32; 5] = [0.2, 0.1, 0.2, 0.1, 0.3];
        let second: [f32; 5] = [0.3, 0.2, 0.4, 0.0, 0.1];
        let too_long: [f32; 6] = [0.3, 0.2, 0.4, 0.0, 0.1, 0.1];
        let too_short: [f32; 4] = [0.3, 0.2, 0.4, 0.0];
        assert!(index.add(1, &first).is_ok());
        assert!(index.add(2, &second).is_ok());
        assert!(index.add(3, &too_long).is_err());
        assert!(index.add(4, &too_short).is_err());
        assert_eq!(index.size(), 2);

        // Test using Vec<T>
        let mut found_vec: Vec<f32> = Vec::new();
        assert_eq!(index.export(1, &mut found_vec).unwrap(), 1);
        assert_eq!(found_vec.len(), 5);
        assert_eq!(found_vec, first.to_vec());

        // Test using slice
        let mut found_slice = [0.0f32; 5];
        assert_eq!(index.get(1, &mut found_slice).unwrap(), 1);
        assert_eq!(found_slice, first);

        // Create a slice with incorrect size
        let mut found = [0.0f32; 6]; // This isn't a multiple of the index's dimensions.
        let result = index.get(1, &mut found);
        assert!(result.is_err());
    }

    #[test]
    fn quantized_add_search() {
        // Metrics × quantizations: every scalar kind that accepts f32 input,
        // tested under each distance metric. Dimensions are kept at 64 —
        // high enough for SIMD paths to kick in, low enough to stay fast.
        let metrics = [MetricKind::Cos, MetricKind::L2sq, MetricKind::IP];
        let quantizations = [
            ScalarKind::F32,
            ScalarKind::F64,
            ScalarKind::F16,
            ScalarKind::BF16,
            ScalarKind::I8,
            ScalarKind::E5M2,
            ScalarKind::E4M3,
            ScalarKind::E3M2,
            ScalarKind::E2M3,
        ];
        let dimensions: usize = 64;
        let first: Vec<f32> = (0..dimensions).map(|i| (i as f32) * 0.1).collect();
        let second: Vec<f32> = (0..dimensions)
            .map(|i| ((dimensions - i) as f32) * 0.1)
            .collect();

        for metric in metrics {
            for quantization in quantizations {
                let index = Index::new(&IndexOptions {
                    dimensions,
                    metric,
                    quantization,
                    ..Default::default()
                })
                .unwrap();
                assert!(index.reserve(10).is_ok());
                assert!(index.add(1, &first).is_ok());
                assert!(index.add(2, &second).is_ok());
                assert_eq!(index.size(), 2, "{metric:?}/{quantization:?}: wrong size");
                let results = index.search(&first, 2).unwrap();
                assert_eq!(
                    results.keys[0], 1,
                    "self-match failed for {metric:?}/{quantization:?}"
                );
            }
        }
    }

    #[test]
    fn search_vector() {
        let options = IndexOptions {
            dimensions: 5,
            quantization: ScalarKind::F32,
            ..Default::default()
        };
        let index = Index::new(&options).unwrap();
        assert!(index.reserve(10).is_ok());

        let first: [f32; 5] = [0.2, 0.1, 0.2, 0.1, 0.3];
        let second: [f32; 5] = [0.3, 0.2, 0.4, 0.0, 0.1];
        let too_long: [f32; 6] = [0.3, 0.2, 0.4, 0.0, 0.1, 0.1];
        let too_short: [f32; 4] = [0.3, 0.2, 0.4, 0.0];

        // Search on empty index should return zero results
        let empty_results = index.search(&first, 10).unwrap();
        assert_eq!(empty_results.keys.len(), 0);

        assert!(index.add(1, &first).is_ok());
        assert!(index.add(2, &second).is_ok());
        assert_eq!(index.size(), 2);

        // Vectors that were not added - shouldn't be visible!
        // assert!(index.add(3, &too_long).is_err());
        // assert!(index.add(4, &too_short).is_err());
        assert!(index.search(&too_long, 1).is_err());
        assert!(index.search(&too_short, 1).is_err());
    }

    #[test]
    fn add_remove_vector() {
        let options = IndexOptions {
            dimensions: 4,
            metric: MetricKind::IP,
            quantization: ScalarKind::F64,
            connectivity: 10,
            expansion_add: 128,
            expansion_search: 3,
            ..Default::default()
        };
        let index = Index::new(&options).unwrap();
        assert!(index.reserve(10).is_ok());
        assert!(index.capacity() >= 10);

        let first: [f32; 4] = [0.2, 0.1, 0.2, 0.1];
        let second: [f32; 4] = [0.3, 0.2, 0.4, 0.0];

        // IDs until 18446744073709551615 should be fine:
        let id1 = 483367403120493160;
        let id2 = 483367403120558696;
        let id3 = 483367403120624232;
        let id4 = 483367403120624233;

        // Add and verify contains/count
        assert!(!index.contains(id1));
        assert_eq!(index.count(id1), 0);
        assert!(index.add(id1, &first).is_ok());
        assert!(index.contains(id1));
        assert_eq!(index.count(id1), 1);

        // Rename id1 → id2 and verify the move
        assert_eq!(index.rename(id1, id2).unwrap(), 1);
        assert!(!index.contains(id1));
        assert!(index.contains(id2));
        let mut found_slice = [0.0f32; 4];
        assert_eq!(index.get(id2, &mut found_slice).unwrap(), 1);
        assert_eq!(found_slice, first);

        // Remove and verify
        assert!(index.remove(id2).is_ok());
        assert!(!index.contains(id2));
        assert_eq!(index.count(id2), 0);

        assert!(index.add(id3, &second).is_ok());
        let mut found_slice = [0.0f32; 4];
        assert_eq!(index.get(id3, &mut found_slice).unwrap(), 1);
        assert!(index.remove(id3).is_ok());

        assert!(index.add(id4, &second).is_ok());
        let mut found_slice = [0.0f32; 4];
        assert_eq!(index.get(id4, &mut found_slice).unwrap(), 1);
        assert!(index.remove(id4).is_ok());

        assert_eq!(index.size(), 0);
    }

    #[test]
    fn integration() {
        let mut options = IndexOptions {
            dimensions: 5,
            ..Default::default()
        };

        let index = Index::new(&options).unwrap();

        assert!(index.expansion_add() > 0);
        assert!(index.expansion_search() > 0);

        assert!(index.reserve(10).is_ok());
        assert!(index.capacity() >= 10);
        assert!(index.connectivity() != 0);
        assert_eq!(index.dimensions(), 5);
        assert_eq!(index.size(), 0);

        let first: [f32; 5] = [0.2, 0.1, 0.2, 0.1, 0.3];
        let second: [f32; 5] = [0.3, 0.2, 0.4, 0.0, 0.1];

        println!("--------------------------------------------------");
        println!(
            "before add, memory_usage: {} \
            cap: {} \
            ",
            index.memory_usage(),
            index.capacity(),
        );
        index.change_expansion_add(10);
        assert_eq!(index.expansion_add(), 10);
        assert!(index.add(42, &first).is_ok());
        index.change_expansion_add(12);
        assert_eq!(index.expansion_add(), 12);
        assert!(index.add(43, &second).is_ok());
        assert_eq!(index.size(), 2);
        println!(
            "after add, memory_usage: {} \
            cap: {} \
            ",
            index.memory_usage(),
            index.capacity(),
        );

        index.change_expansion_search(10);
        assert_eq!(index.expansion_search(), 10);
        // Read back the tags
        let results = index.search(&first, 10).unwrap();
        println!("{:?}", results);
        assert_eq!(results.keys.len(), 2);

        index.change_expansion_search(12);
        assert_eq!(index.expansion_search(), 12);
        let results = index.search(&first, 10).unwrap();
        println!("{:?}", results);
        assert_eq!(results.keys.len(), 2);
        println!("--------------------------------------------------");

        let stats = index.memory_stats();
        assert!(
            stats.vectors_allocated > 0,
            "vectors should have allocated memory"
        );

        // Validate serialization with round-trip content checks
        assert!(index.save("index.rust.usearch").is_ok());
        assert!(index.load("index.rust.usearch").is_ok());
        let results = index.search(&first, 10).unwrap();
        assert!(results.keys.contains(&42), "key 42 survives save/load");
        assert!(index.view("index.rust.usearch").is_ok());

        // Make sure every function is called at least once
        assert!(new_index(&options).is_ok());
        options.metric = MetricKind::L2sq;
        assert!(new_index(&options).is_ok());
        options.metric = MetricKind::Cos;
        assert!(new_index(&options).is_ok());
        options.metric = MetricKind::Haversine;
        options.quantization = ScalarKind::F32;
        options.dimensions = 2;
        assert!(new_index(&options).is_ok());

        // Buffer serialization with round-trip content checks
        let mut serialization_buffer = vec![0; index.serialized_length()];
        assert!(index.save_to_buffer(&mut serialization_buffer).is_ok());

        let deserialized_index = new_index(&options).unwrap();
        assert!(deserialized_index
            .load_from_buffer(&serialization_buffer)
            .is_ok());
        assert_eq!(index.size(), deserialized_index.size());
        let results = deserialized_index.search(&first, 10).unwrap();
        assert!(
            results.keys.contains(&42),
            "key 42 survives buffer round-trip"
        );

        // Borrow the buffer as a read-only view instead of deserializing
        let viewed_index = Index::new(&IndexOptions {
            dimensions: 5,
            ..Default::default()
        })
        .unwrap();
        assert!(unsafe { viewed_index.view_from_buffer(&serialization_buffer) }.is_ok());
        assert_eq!(viewed_index.size(), index.size());
        let results = viewed_index.search(&first, 10).unwrap();
        assert!(
            results.keys.contains(&42),
            "key 42 visible via view_from_buffer"
        );

        // After a full reset the index must be reusable from scratch
        assert_ne!(index.memory_usage(), 0);
        assert!(index.reset().is_ok());
        assert_eq!(index.size(), 0);
        assert_eq!(index.memory_usage(), 0);

        assert!(index.reserve(10).is_ok());
        assert!(index.add(100, &first).is_ok());
        assert!(index.add(101, &second).is_ok());
        assert_eq!(index.size(), 2);
        let results = index.search(&first, 10).unwrap();
        assert_eq!(results.keys.len(), 2);

        // Clone
        options.metric = MetricKind::Haversine;
        let mut opts = options.clone();
        assert_eq!(opts.metric, options.metric);
        assert_eq!(opts.quantization, options.quantization);
        assert_eq!(opts, options);
        opts.metric = MetricKind::Cos;
        assert_ne!(opts.metric, options.metric);
        assert!(new_index(&opts).is_ok());
    }

    #[test]
    fn search_with_stateless_filter() {
        let options = IndexOptions {
            dimensions: 5,
            ..Default::default()
        };
        let index = Index::new(&options).unwrap();
        index.reserve(10).unwrap();

        // Adding sample vectors to the index
        let first: [f32; 5] = [0.2, 0.1, 0.2, 0.1, 0.3];
        let second: [f32; 5] = [0.3, 0.2, 0.4, 0.0, 0.1];
        index.add(1, &first).unwrap();
        index.add(2, &second).unwrap();

        // Stateless filter: checks if the key is odd
        let is_odd = |key: Key| key % 2 == 1;
        let query = vec![0.2, 0.1, 0.2, 0.1, 0.3]; // Example query vector
        let results = index.filtered_search(&query, 10, is_odd).unwrap();
        assert!(
            results.keys.iter().all(|&key| key % 2 == 1),
            "All keys must be odd"
        );
    }

    #[test]
    fn search_with_stateful_filter() {
        use std::collections::HashSet;

        let options = IndexOptions {
            dimensions: 5,
            ..Default::default()
        };
        let index = Index::new(&options).unwrap();
        index.reserve(10).unwrap();

        // Adding sample vectors to the index
        let first: [f32; 5] = [0.2, 0.1, 0.2, 0.1, 0.3];
        index.add(1, &first).unwrap();
        index.add(2, &first).unwrap();

        let allowed_keys = vec![1, 2, 3].into_iter().collect::<HashSet<Key>>();
        // Clone `allowed_keys` for use in the closure
        let filter_keys = allowed_keys.clone();
        let stateful_filter = move |key: Key| filter_keys.contains(&key);

        let query = vec![0.2, 0.1, 0.2, 0.1, 0.3]; // Example query vector
        let results = index.filtered_search(&query, 10, stateful_filter).unwrap();

        // Use the original `allowed_keys` for assertion
        assert!(
            results.keys.iter().all(|&key| allowed_keys.contains(&key)),
            "All keys must be in the allowed set"
        );
    }

    #[test]
    fn zero_distances() {
        let options = IndexOptions {
            dimensions: 8,
            metric: MetricKind::L2sq,
            quantization: ScalarKind::F16,
            ..Default::default()
        };

        let index = new_index(&options).unwrap();
        index.reserve(10).unwrap();
        index
            .add(0, &[0.4, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0])
            .unwrap();
        index
            .add(1, &[0.5, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0])
            .unwrap();
        index
            .add(2, &[0.6, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0])
            .unwrap();

        // Make sure non of the distances are zeros
        let matches = index
            .search(&[0.05, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0], 2)
            .unwrap();
        for distance in matches.distances.iter() {
            assert_ne!(*distance, 0.0);
        }
    }

    #[test]
    fn exact_search() {
        use std::collections::HashSet;

        // Create an index with many vectors
        let options = IndexOptions {
            dimensions: 4,
            metric: MetricKind::L2sq,
            quantization: ScalarKind::F32,
            ..Default::default()
        };
        let index = new_index(&options).unwrap();
        index.reserve(100).unwrap();
        // Add 100 vectors to the index
        for i in 0..100 {
            let vec = vec![
                i as f32 * 0.1,
                (i as f32 * 0.05).sin(),
                (i as f32 * 0.05).cos(),
                0.0,
            ];
            index.add(i, &vec).unwrap();
        }
        // Query vector
        let query = vec![4.5, 0.0, 1.0, 0.0];
        // Compare approximate and exact search results
        let approx_matches = index.search(&query, 10).unwrap();
        let exact_matches = index.exact_search(&query, 10).unwrap();
        // Collect the keys from both result sets
        let approx_keys: HashSet<Key> = approx_matches.keys.iter().cloned().collect();
        let exact_keys: HashSet<Key> = exact_matches.keys.iter().cloned().collect();
        // Check that both methods return 10 results
        assert_eq!(approx_matches.keys.len(), 10);
        assert_eq!(exact_matches.keys.len(), 10);

        // The exact search should find the true nearest neighbors
        // Verify that the minimum distance in exact results is <= minimum distance in approximate results
        assert!(exact_matches.distances[0] <= approx_matches.distances[0]);
        // The nearest neighbor according to exact search might be different from approximate search
        println!(
            "Approximate search first match: key={}, distance={}",
            approx_matches.keys[0], approx_matches.distances[0]
        );
        println!(
            "Exact search first match: key={}, distance={}",
            exact_matches.keys[0], exact_matches.distances[0]
        );
        // Results from both should be mostly similar, but may differ due to approximation
        let intersection: HashSet<_> = approx_keys.intersection(&exact_keys).collect();
        println!(
            "Number of common results between approximate and exact search: {}",
            intersection.len()
        );
    }

    #[test]
    fn change_distance_function() {
        let options = IndexOptions {
            dimensions: 2, // Adjusted for simplicity in creating test vectors
            ..Default::default()
        };
        let mut index = Index::new(&options).unwrap();
        index.reserve(10).unwrap();

        // Adding a simple vector to test the distance function changes
        let vector: [f32; 2] = [1.0, 0.0];
        index.add(1, &vector).unwrap();

        // Stateful distance function with adjustments for pointer to slice conversion
        let first_factor: f32 = 2.0;
        let second_factor: f32 = 0.7;
        let stateful_distance = Box::new(move |a: *const f32, b: *const f32| unsafe {
            let a_slice = std::slice::from_raw_parts(a, 2);
            let b_slice = std::slice::from_raw_parts(b, 2);
            (a_slice[0] - b_slice[0]).abs() * first_factor
                + (a_slice[1] - b_slice[1]).abs() * second_factor
        });
        index.change_metric(stateful_distance);

        let another_vector: [f32; 2] = [0.0, 1.0];
        index.add(2, &another_vector).unwrap();
    }

    #[test]
    fn binary_vectors_and_hamming_distance() {
        let index = Index::new(&IndexOptions {
            dimensions: 8,
            metric: MetricKind::Hamming,
            quantization: ScalarKind::B1,
            ..Default::default()
        })
        .unwrap();

        // Binary vectors represented as `b1x8` slices
        let vector42: Vec<b1x8> = vec![b1x8(0b00001111)];
        let vector43: Vec<b1x8> = vec![b1x8(0b11110000)];
        let query: Vec<b1x8> = vec![b1x8(0b01111000)];

        // Adding binary vectors to the index
        index.reserve(10).unwrap();
        index.add(42, &vector42).unwrap();
        index.add(43, &vector43).unwrap();

        let results = index.search(&query, 5).unwrap();

        // Validate the search results based on Hamming distance
        assert_eq!(results.keys.len(), 2);
        assert_eq!(results.keys[0], 43);
        assert_eq!(results.distances[0], 2.0);
        assert_eq!(results.keys[1], 42);
        assert_eq!(results.distances[1], 6.0);
    }

    #[test]
    fn multi_index() {
        let options = IndexOptions {
            dimensions: 4,
            metric: MetricKind::L2sq,
            quantization: ScalarKind::F32,
            multi: true,
            ..Default::default()
        };
        let index = Index::new(&options).unwrap();
        index.reserve(10).unwrap();

        let vec_a: [f32; 4] = [1.0, 0.0, 0.0, 0.0];
        let vec_b: [f32; 4] = [0.0, 1.0, 0.0, 0.0];
        let key: Key = 42;

        // Two vectors under the same key
        index.add(key, &vec_a).unwrap();
        index.add(key, &vec_b).unwrap();
        assert_eq!(index.size(), 2);
        assert_eq!(index.count(key), 2);
        assert!(index.contains(key));

        // Retrieve both vectors
        let mut buf = [0.0f32; 8]; // 2 * dims
        let found = index.get(key, &mut buf).unwrap();
        assert_eq!(found, 2);

        // Export convenience
        let mut exported: Vec<f32> = Vec::new();
        assert_eq!(index.export(key, &mut exported).unwrap(), 2);
        assert_eq!(exported.len(), 8);

        // Search should find the key
        let results = index.search(&vec_a, 5).unwrap();
        assert!(results.keys.contains(&key));
    }

    #[test]
    fn concurrency() {
        use fork_union as fu;
        use rand::{RngExt, SeedableRng};
        use rand_chacha::ChaCha8Rng;
        use rand_distr::Uniform;
        use std::sync::Arc;

        const DIMENSIONS: usize = 128;
        const VECTOR_COUNT: usize = 1000;
        const THREAD_COUNT: usize = 4;

        let options = IndexOptions {
            dimensions: DIMENSIONS,
            metric: MetricKind::Cos,
            quantization: ScalarKind::F32,
            ..Default::default()
        };

        let index = Arc::new(Index::new(&options).unwrap());
        index
            .reserve_capacity_and_threads(VECTOR_COUNT, THREAD_COUNT)
            .unwrap();

        // Generate deterministic vectors using rand crate for reproducible testing
        let seed = 42; // Fixed seed for reproducibility
        let mut rng = ChaCha8Rng::seed_from_u64(seed);
        let uniform = Uniform::new(-1.0f32, 1.0f32).unwrap();

        // Store reference vectors for validation
        let mut reference_vectors: Vec<[f32; DIMENSIONS]> = Vec::with_capacity(VECTOR_COUNT);
        for _ in 0..VECTOR_COUNT {
            let mut vector = [0.0f32; DIMENSIONS];
            // Fill with random values in [-1, 1]
            for item in vector.iter_mut().take(DIMENSIONS) {
                *item = rng.sample(uniform);
            }
            reference_vectors.push(vector);
        }

        let mut pool = fu::spawn(THREAD_COUNT);

        // Concurrent indexing
        pool.for_n(VECTOR_COUNT, |prong| {
            let index_clone = Arc::clone(&index);
            let i = prong.task_index;
            let vector = reference_vectors[i];
            index_clone.add(i as u64, &vector).unwrap();
        });

        assert_eq!(index.size(), VECTOR_COUNT);

        // Concurrent retrieval and validation
        let mut pool = fu::spawn(THREAD_COUNT);
        let validation_results = Arc::new(std::sync::Mutex::new(Vec::new()));

        pool.for_n(VECTOR_COUNT, |prong| {
            let index_clone = Arc::clone(&index);
            let results_clone = Arc::clone(&validation_results);
            let i = prong.task_index;
            let expected_vector = &reference_vectors[i];

            let mut retrieved_vector = [0.0f32; DIMENSIONS];
            let count = index_clone.get(i as u64, &mut retrieved_vector).unwrap();
            assert_eq!(count, 1);

            // Validate retrieved vector matches expected
            let matches = retrieved_vector
                .iter()
                .zip(expected_vector.iter())
                .all(|(a, b)| (a - b).abs() < 1e-6);

            let mut results = results_clone.lock().unwrap();
            results.push(matches);
        });

        let validation_results = validation_results.lock().unwrap();
        assert_eq!(validation_results.len(), VECTOR_COUNT);
        assert!(
            validation_results.iter().all(|&x| x),
            "All retrieved vectors should match the original ones"
        );

        // Concurrent search testing
        let mut pool = fu::spawn(THREAD_COUNT);
        let search_results = Arc::new(std::sync::Mutex::new(Vec::new()));

        pool.for_n(100, |prong| {
            // Test 100 searches
            let index_clone = Arc::clone(&index);
            let results_clone = Arc::clone(&search_results);
            let query_idx = prong.task_index % VECTOR_COUNT;
            let query_vector = &reference_vectors[query_idx];

            let matches = index_clone.exact_search(query_vector, 10).unwrap();

            // The first result should be the exact match with distance ~0
            let exact_match_found = !matches.keys.is_empty()
                && matches.keys[0] == query_idx as u64
                && matches.distances[0] < 1e-6;

            let mut results = results_clone.lock().unwrap();
            results.push(exact_match_found);
        });

        let search_results = search_results.lock().unwrap();
        assert_eq!(search_results.len(), 100);
        assert!(
            search_results.iter().all(|&x| x),
            "All searches should find exact matches"
        );
    }
}