#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Key {
Str(String),
U64(u64),
Bytes(Vec<u8>),
}
impl Key {
const TAG_STR: u8 = 1;
const TAG_U64: u8 = 2;
const TAG_BYTES: u8 = 3;
#[must_use]
pub fn encode(&self) -> Vec<u8> {
match self {
Key::Str(s) => {
let mut out = Vec::with_capacity(1 + s.len());
out.push(Self::TAG_STR);
out.extend_from_slice(s.as_bytes());
out
}
Key::U64(n) => {
let mut out = Vec::with_capacity(1 + 8);
out.push(Self::TAG_U64);
out.extend_from_slice(&n.to_le_bytes());
out
}
Key::Bytes(b) => {
let mut out = Vec::with_capacity(1 + b.len());
out.push(Self::TAG_BYTES);
out.extend_from_slice(b);
out
}
}
}
#[must_use]
pub fn decode(bytes: &[u8]) -> Option<Key> {
let (&tag, rest) = bytes.split_first()?;
match tag {
Self::TAG_STR => String::from_utf8(rest.to_vec()).ok().map(Key::Str),
Self::TAG_U64 => {
let arr: [u8; 8] = rest.try_into().ok()?;
Some(Key::U64(u64::from_le_bytes(arr)))
}
Self::TAG_BYTES => Some(Key::Bytes(rest.to_vec())),
_ => None,
}
}
}
impl From<&str> for Key {
fn from(s: &str) -> Self {
Key::Str(s.to_owned())
}
}
impl From<String> for Key {
fn from(s: String) -> Self {
Key::Str(s)
}
}
impl From<u64> for Key {
fn from(n: u64) -> Self {
Key::U64(n)
}
}
impl From<&Key> for Key {
fn from(k: &Key) -> Self {
k.clone()
}
}
#[derive(Clone, Debug)]
pub enum Value<'a> {
Text(&'a str),
Vector(&'a [f32]),
}
#[derive(Clone, Debug, Default)]
pub struct Record<'a> {
pub(crate) fields: Vec<(&'a str, Value<'a>)>,
pub(crate) created_at: Option<i64>,
pub(crate) parent: Option<Key>,
}
impl<'a> Record<'a> {
#[must_use]
pub fn new() -> Self {
Self {
fields: Vec::new(),
created_at: None,
parent: None,
}
}
#[must_use]
pub fn text(mut self, field: &'a str, s: &'a str) -> Self {
self.fields.push((field, Value::Text(s)));
self
}
#[must_use]
pub fn vector(mut self, field: &'a str, v: &'a [f32]) -> Self {
self.fields.push((field, Value::Vector(v)));
self
}
#[must_use]
pub fn at(mut self, unix_secs: i64) -> Self {
self.created_at = Some(unix_secs);
self
}
#[must_use]
pub fn child_of(mut self, parent: Key) -> Self {
self.parent = Some(parent);
self
}
#[must_use]
pub fn created_at(&self) -> Option<i64> {
self.created_at
}
pub(crate) fn text_value(&self) -> Option<&'a str> {
self.fields.iter().find_map(|(_, v)| match v {
Value::Text(s) => Some(*s),
Value::Vector(_) => None,
})
}
pub(crate) fn vector_values(&self) -> impl Iterator<Item = (&'a str, &'a [f32])> {
self.fields.iter().filter_map(|(name, v)| match v {
Value::Vector(values) => Some((*name, *values)),
Value::Text(_) => None,
})
}
}
#[derive(Clone, Debug)]
pub struct Stored {
pub key: Key,
pub collection: String,
pub created_at: i64,
pub text: Option<String>,
pub vectors: Vec<(String, Vec<f32>)>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn key_roundtrip_all_variants() {
for k in [
Key::Str("hello/world".into()),
Key::Str(String::new()),
Key::U64(0),
Key::U64(u64::MAX),
Key::Bytes(vec![]),
Key::Bytes(vec![0, 1, 2, 255]),
] {
let encoded = k.encode();
assert_eq!(Key::decode(&encoded), Some(k));
}
}
#[test]
fn key_variants_never_collide() {
let u = Key::U64(0x6f6c6c6568).encode();
let s = Key::Str("hello".into()).encode();
assert_ne!(u, s);
}
#[test]
fn key_decode_rejects_garbage() {
assert_eq!(Key::decode(&[]), None);
assert_eq!(Key::decode(&[99, 1, 2]), None);
assert_eq!(Key::decode(&[Key::U64(0).encode()[0], 1, 2, 3]), None);
}
#[test]
fn record_builder_collects_fields() {
let v = [1.0f32, 2.0];
let r = Record::new()
.text("body", "hi")
.vector("dense", &v)
.at(42)
.child_of(Key::U64(7));
assert_eq!(r.text_value(), Some("hi"));
assert_eq!(r.created_at, Some(42));
assert_eq!(r.parent, Some(Key::U64(7)));
let vecs: Vec<_> = r.vector_values().collect();
assert_eq!(vecs.len(), 1);
assert_eq!(vecs[0].0, "dense");
}
}