pub enum MetricFunction {
B1X8Metric(*mut Box<dyn Fn(*const b1x8, *const b1x8) -> Distance + Send + Sync>),
I8Metric(*mut Box<dyn Fn(*const i8, *const i8) -> Distance + Send + Sync>),
F16Metric(*mut Box<dyn Fn(*const f16, *const f16) -> Distance + Send + Sync>),
F32Metric(*mut Box<dyn Fn(*const f32, *const f32) -> Distance + Send + Sync>),
F64Metric(*mut Box<dyn Fn(*const f64, *const f64) -> Distance + Send + Sync>),
}Expand description
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 inu8containers, represented here byb1x8.I8Metric: A metric function for vectors of 8-bit signed integers (i8).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.