Skip to main content

macrame/vector/
embedding.rs

1use crate::error::{DbError, Result};
2
3/// Codec for converting between Vec<f32> and libSQL F32_BLOB byte vectors with dimension validation (§4.1).
4pub struct EmbeddingCodec;
5
6impl EmbeddingCodec {
7    /// Encode a float slice into a little-endian F32_BLOB byte vector, validating dimension against model declaration.
8    pub fn encode(vec: &[f32], expected_dim: usize, model_name: &str) -> Result<Vec<u8>> {
9        if vec.len() != expected_dim {
10            return Err(DbError::DimMismatch {
11                got: vec.len(),
12                expected: expected_dim,
13                model: model_name.to_string(),
14            });
15        }
16        let mut bytes = Vec::with_capacity(vec.len() * 4);
17        for &val in vec {
18            bytes.extend_from_slice(&val.to_le_bytes());
19        }
20        Ok(bytes)
21    }
22
23    /// Decode an F32_BLOB byte vector back into Vec<f32>.
24    pub fn decode(bytes: &[u8]) -> Result<Vec<f32>> {
25        if !bytes.len().is_multiple_of(4) {
26            return Err(DbError::ReplayCorrupt {
27                seq: 0,
28                reason: "Invalid F32_BLOB byte length".to_string(),
29            });
30        }
31        let mut vec = Vec::with_capacity(bytes.len() / 4);
32        for chunk in bytes.chunks_exact(4) {
33            let val = f32::from_le_bytes(chunk.try_into().unwrap());
34            vec.push(val);
35        }
36        Ok(vec)
37    }
38}