use std::fmt;
use crate::value::CypherValue;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub enum VectorCoords {
F32(Arc<[f32]>),
F64(Arc<[f64]>),
Int(Arc<[i64]>),
}
#[derive(Debug, Clone, Copy)]
pub enum Coord {
F(f64),
I(i64),
}
impl fmt::Display for Coord {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text())
}
}
impl PartialEq for Coord {
fn eq(&self, other: &Self) -> bool {
Coord::numeric_eq(*self, *other)
}
}
impl Coord {
pub fn text(&self) -> String {
match self {
Coord::F(v) => crate::value::float_text(*v),
Coord::I(i) => i.to_string(),
}
}
pub(crate) fn numeric_eq(a: Coord, b: Coord) -> bool {
match (a, b) {
(Coord::I(x), Coord::I(y)) => x == y,
(Coord::F(x), Coord::F(y)) => x == y,
(Coord::I(x), Coord::F(y)) => crate::canonical_key::eq_i64_f64(x, y),
(Coord::F(x), Coord::I(y)) => crate::canonical_key::eq_i64_f64(y, x),
}
}
pub fn to_le_bytes(self) -> [u8; 8] {
match self {
Coord::I(v) => v.to_le_bytes(),
Coord::F(v) => v.to_le_bytes(),
}
}
}
impl PartialEq for VectorCoords {
fn eq(&self, other: &Self) -> bool {
self.numeric_eq(other)
}
}
fn coord_conforms(kind: crate::value::VectorCoordKind, c: Coord) -> Result<(), String> {
match (c, kind) {
(Coord::I(n), kind) if kind.is_integer() => {
if kind.holds_int(n) {
Ok(())
} else {
Err(format!(
"coordinate {n} out of {} range",
kind.canonical_name()
))
}
}
(Coord::I(_), _) => Ok(()),
(Coord::F(f), kind) if !kind.is_integer() => {
if f.is_finite() && kind.is_exact(f) {
Ok(())
} else if !f.is_finite() {
Err(format!(
"non-finite {} coordinate {f}",
kind.canonical_name()
))
} else {
Err(format!(
"coordinate {f} loses precision in {}",
kind.canonical_name()
))
}
}
(Coord::F(f), kind) => Err(format!(
"float coordinate {f} under integer kind {}",
kind.canonical_name()
)),
}
}
fn family_of(coords: &VectorCoords) -> &'static str {
match coords {
VectorCoords::F32(_) => "F32",
VectorCoords::F64(_) => "F64",
VectorCoords::Int(_) => "Int",
}
}
fn kind_family(kind: crate::value::VectorCoordKind) -> &'static str {
use crate::value::VectorCoordKind;
match kind {
k if k.is_f32_family() => "F32",
VectorCoordKind::Float64 => "F64",
_ => "Int",
}
}
impl VectorCoords {
pub fn from_f32(coords: impl Into<Arc<[f32]>>) -> Self {
VectorCoords::F32(coords.into())
}
pub fn from_f64(coords: impl Into<Arc<[f64]>>) -> Self {
VectorCoords::F64(coords.into())
}
pub fn from_int(coords: impl Into<Arc<[i64]>>) -> Self {
VectorCoords::Int(coords.into())
}
pub fn len(&self) -> usize {
match self {
VectorCoords::F32(xs) => xs.len(),
VectorCoords::F64(xs) => xs.len(),
VectorCoords::Int(xs) => xs.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn element_bytes(&self) -> u64 {
match self {
VectorCoords::F32(_) => 4,
VectorCoords::F64(_) | VectorCoords::Int(_) => 8,
}
}
pub fn byte_len(&self) -> u64 {
(self.len() as u64) * self.element_bytes()
}
pub fn arc_id(&self) -> *const u8 {
match self {
VectorCoords::F32(xs) => xs.as_ptr() as *const u8,
VectorCoords::F64(xs) => xs.as_ptr() as *const u8,
VectorCoords::Int(xs) => xs.as_ptr() as *const u8,
}
}
pub fn arc_strong_count(&self) -> usize {
match self {
VectorCoords::F32(xs) => Arc::strong_count(xs),
VectorCoords::F64(xs) => Arc::strong_count(xs),
VectorCoords::Int(xs) => Arc::strong_count(xs),
}
}
pub fn is_unique(&self) -> bool {
self.arc_strong_count() == 1
}
pub fn to_f64_vec(&self) -> Vec<f64> {
match self {
VectorCoords::F32(xs) => xs.iter().map(|&x| f64::from(x)).collect(),
VectorCoords::F64(xs) => xs.to_vec(),
VectorCoords::Int(xs) => xs.iter().map(|&x| x as f64).collect(),
}
}
pub fn numeric_eq(&self, other: &VectorCoords) -> bool {
self.len() == other.len()
&& self
.iter()
.zip(other.iter())
.all(|(a, b)| Coord::numeric_eq(a, b))
}
pub fn coord_at(&self, i: usize) -> Coord {
match self {
VectorCoords::F32(xs) => Coord::F(xs[i] as f64),
VectorCoords::F64(xs) => Coord::F(xs[i]),
VectorCoords::Int(xs) => Coord::I(xs[i]),
}
}
pub fn coord_f64(&self, i: usize) -> f64 {
match self {
VectorCoords::F32(xs) => xs[i] as f64,
VectorCoords::F64(xs) => xs[i],
VectorCoords::Int(xs) => xs[i] as f64,
}
}
pub fn iter(&self) -> impl Iterator<Item = Coord> + '_ {
let len = self.len();
(0..len).map(move |i| self.coord_at(i))
}
pub fn from_coords(
coord: crate::value::VectorCoordKind,
coords: impl Iterator<Item = Coord>,
) -> Option<VectorCoords> {
use crate::value::VectorCoordKind;
let tokens = coords.collect::<Vec<_>>();
for c in &tokens {
coord_conforms(coord, *c).ok()?;
}
let mut ints: Option<Vec<i64>> = None;
let mut floats: Option<Vec<f64>> = None;
for c in tokens {
match c {
Coord::I(n) => ints.get_or_insert_with(Vec::new).push(n),
Coord::F(f) => floats.get_or_insert_with(Vec::new).push(f),
}
}
match (ints, floats) {
(None, None) if coord == VectorCoordKind::Float64 => {
Some(VectorCoords::from_f64(Vec::new()))
}
(None, None) if coord.is_integer() => Some(VectorCoords::from_int(Vec::new())),
(None, None) => Some(VectorCoords::from_f32(Vec::new())),
(Some(xs), None) => Some(VectorCoords::from_int(xs)),
(None, Some(xs)) if coord == VectorCoordKind::Float64 => {
Some(VectorCoords::from_f64(xs))
}
(None, Some(xs)) => Some(VectorCoords::from_f32(
xs.iter().map(|&f| f as f32).collect::<Vec<_>>(),
)),
_ => None,
}
}
pub fn from_cypher_values(
coord: crate::value::VectorCoordKind,
values: &[CypherValue],
) -> Option<VectorCoords> {
let tokens = values
.iter()
.map(|v| match v {
CypherValue::Int(n) => Some(Coord::I(*n)),
CypherValue::Float(f) => Some(Coord::F(*f)),
_ => None,
})
.collect::<Option<Vec<_>>>()?;
Self::from_coords(coord, tokens.into_iter())
}
pub fn assert_conforms(&self, coord: crate::value::VectorCoordKind) {
if let Err(message) = self.invariant_violation(coord) {
panic!("{message}");
}
}
pub fn invariant_violation(&self, coord: crate::value::VectorCoordKind) -> Result<(), String> {
if family_of(self) != kind_family(coord) && family_of(self) != "Int" {
return Err(format!(
"vector coordinate family does not match kind {}",
coord.canonical_name()
));
}
for c in self.iter() {
coord_conforms(coord, c)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn f32_family_round_trips_losslessly() {
let coords = VectorCoords::from_f32(vec![0.25f32, -1.5, 3.0]);
assert_eq!(coords.len(), 3);
assert_eq!(coords.coord_f64(0), 0.25);
assert_eq!(coords.coord_f64(1), -1.5);
assert_eq!(coords.coord_f64(2), 3.0);
}
#[test]
fn int_family_reads_as_f64_like_the_value_walk_did() {
let coords = VectorCoords::from_int(vec![7i64, -2]);
assert_eq!(coords.coord_f64(0), 7.0);
assert_eq!(coords.coord_f64(1), -2.0);
assert_eq!(coords.coord_at(0).to_string(), "7");
}
#[test]
fn display_keeps_the_int_float_distinction() {
let ints = VectorCoords::from_int(vec![5]);
let floats = VectorCoords::from_f32(vec![5.0]);
assert_eq!(ints.coord_at(0).to_string(), "5");
assert_eq!(floats.coord_at(0).to_string(), "5.0");
}
#[test]
fn equality_is_the_numeric_policy_like_the_value_walk() {
assert_eq!(
VectorCoords::from_f32(vec![0.5f32, 1.0]),
VectorCoords::from_f32(vec![0.5f32, 1.0])
);
assert_eq!(
VectorCoords::from_int(vec![1]),
VectorCoords::from_f64(vec![1.0])
);
}
}