Skip to main content

kevy_index/
value.rs

1//! [`IndexValue`] — the three scalar types an index can hold, with a
2//! total order (f64 via `total_cmp`, so NaN coerce-fails upstream and
3//! never enters a segment).
4
5use crate::catalog::ValType;
6use std::cmp::Ordering;
7
8/// One indexed scalar. Ordering is total within a type; the catalog
9/// guarantees a segment only ever holds one variant.
10#[derive(Debug, Clone, PartialEq)]
11pub enum IndexValue {
12    /// `TYPE i64`.
13    I64(i64),
14    /// `TYPE f64` (never NaN — coercion rejects it).
15    F64(f64),
16    /// `TYPE str` (raw bytes, memcmp order).
17    Str(Vec<u8>),
18}
19
20impl Eq for IndexValue {}
21
22impl Ord for IndexValue {
23    fn cmp(&self, other: &Self) -> Ordering {
24        match (self, other) {
25            (IndexValue::I64(a), IndexValue::I64(b)) => a.cmp(b),
26            (IndexValue::F64(a), IndexValue::F64(b)) => a.total_cmp(b),
27            (IndexValue::Str(a), IndexValue::Str(b)) => a.cmp(b),
28            // Cross-variant comparison means a catalog bug; order by
29            // discriminant to stay total rather than panic in a
30            // B-tree.
31            (a, b) => disc(a).cmp(&disc(b)),
32        }
33    }
34}
35
36impl PartialOrd for IndexValue {
37    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
38        Some(self.cmp(other))
39    }
40}
41
42fn disc(v: &IndexValue) -> u8 {
43    match v {
44        IndexValue::I64(_) => 0,
45        IndexValue::F64(_) => 1,
46        IndexValue::Str(_) => 2,
47    }
48}
49
50impl IndexValue {
51    /// Coerce raw field bytes per the declared type. `None` = the row
52    /// is excluded from the index (and counted as a coerce failure).
53    pub fn coerce(ty: crate::ValType, raw: &[u8]) -> Option<IndexValue> {
54        match ty {
55            // ANN kinds never coerce through IndexValue.
56            crate::ValType::Vector => None,
57            crate::ValType::I64 => std::str::from_utf8(raw)
58                .ok()?
59                .trim()
60                .parse::<i64>()
61                .ok()
62                .map(IndexValue::I64),
63            crate::ValType::F64 => {
64                let f = std::str::from_utf8(raw).ok()?.trim().parse::<f64>().ok()?;
65                if f.is_nan() {
66                    return None;
67                }
68                Some(IndexValue::F64(f))
69            }
70            crate::ValType::Str => Some(IndexValue::Str(raw.to_vec())),
71        }
72    }
73
74    /// Parse a query-side literal (same rules as [`Self::coerce`]).
75    pub fn parse_literal(ty: crate::ValType, raw: &[u8]) -> Option<IndexValue> {
76        Self::coerce(ty, raw)
77    }
78
79    /// Numeric view for aggregation (Str = 0.0; agg kinds only admit
80    /// numeric types at CREATE, so this arm is unreachable there).
81    pub fn as_f64(&self) -> f64 {
82        match self {
83            IndexValue::I64(v) => *v as f64,
84            IndexValue::F64(v) => *v,
85            IndexValue::Str(_) => 0.0,
86        }
87    }
88
89    /// Approximate heap bytes (for the memory formula / IDX.LIST).
90    pub fn approx_bytes(&self) -> usize {
91        match self {
92            IndexValue::I64(_) | IndexValue::F64(_) => 8,
93            IndexValue::Str(s) => s.len(),
94        }
95    }
96}
97
98/// A comparison over a stored value's raw bytes, built once from the
99/// type the field was declared as.
100///
101/// `EQ` is the degenerate range `[v, v]`: stored values are totally
102/// ordered, so equality needs no second code path — and one path cannot
103/// disagree with itself about what a bound means.
104#[derive(Debug, Clone, PartialEq)]
105pub struct ValueTest {
106    ty: ValType,
107    lo: IndexValue,
108    hi: IndexValue,
109}
110
111impl ValueTest {
112    /// `RANGE min max` on a field declared as `ty`. `None` when a bound
113    /// is not of that type — a bound the index cannot interpret is an
114    /// error, not an empty result.
115    pub fn range(ty: ValType, min: &[u8], max: &[u8]) -> Option<ValueTest> {
116        Some(ValueTest { ty, lo: IndexValue::coerce(ty, min)?, hi: IndexValue::coerce(ty, max)? })
117    }
118
119    /// `EQ v` on a field declared as `ty`.
120    pub fn eq(ty: ValType, v: &[u8]) -> Option<ValueTest> {
121        let v = IndexValue::coerce(ty, v)?;
122        Some(ValueTest { ty, lo: v.clone(), hi: v })
123    }
124
125    /// Whether a stored value's bytes satisfy the test.
126    ///
127    /// A value that does not coerce fails: text sitting in a field
128    /// declared numeric is not inside any numeric range, and passing it
129    /// would be the accept-and-ignore shape this surface keeps refusing.
130    pub fn passes(&self, raw: &[u8]) -> bool {
131        IndexValue::coerce(self.ty, raw).is_some_and(|v| v >= self.lo && v <= self.hi)
132    }
133}
134
135/// An order-preserving byte encoding of a coerced value.
136///
137/// Two values' encodings compare with `memcmp` exactly as the values
138/// themselves compare. That is what lets `kevy-text` sort by a stored
139/// value without learning what a number is: the caller encodes once per
140/// candidate, and the segment compares bytes.
141///
142/// `None` when the raw bytes are not of that type — a document whose
143/// stored value does not coerce has no place in the order, and is sorted
144/// as missing rather than guessed at.
145pub fn order_key(ty: ValType, raw: &[u8]) -> Option<Vec<u8>> {
146    match IndexValue::coerce(ty, raw)? {
147        // Bytes already compare as themselves.
148        IndexValue::Str(v) => Some(v),
149        // Flip the sign bit: two's complement negatives have the high bit
150        // set and would otherwise sort above every positive.
151        IndexValue::I64(v) => Some(((v as u64) ^ (1 << 63)).to_be_bytes().to_vec()),
152        // The standard IEEE total-order transform. A negative float's
153        // magnitude grows with its bit pattern, so inverting every bit
154        // reverses that and drops it below the positives (whose sign bit
155        // is set instead). Coercion rejects NaN, so there is none to
156        // place.
157        IndexValue::F64(v) => {
158            let b = v.to_bits();
159            let m = if b >> 63 == 1 { !b } else { b | (1 << 63) };
160            Some(m.to_be_bytes().to_vec())
161        }
162    }
163}
164
165#[cfg(test)]
166mod order_key_tests {
167    use super::*;
168
169    /// The encoding must agree with `IndexValue`'s own order on every
170    /// pair — including across zero, which is where a naive big-endian
171    /// encoding of a signed number gets it backwards.
172    fn agrees(ty: ValType, raws: &[&str]) {
173        let mut vals: Vec<(IndexValue, Vec<u8>)> = raws
174            .iter()
175            .map(|r| {
176                (
177                    IndexValue::coerce(ty, r.as_bytes()).expect("coerces"),
178                    order_key(ty, r.as_bytes()).expect("encodes"),
179                )
180            })
181            .collect();
182        vals.sort_by(|a, b| a.1.cmp(&b.1));
183        for w in vals.windows(2) {
184            assert!(w[0].0 <= w[1].0, "{:?} then {:?} for {ty:?}", w[0].0, w[1].0);
185        }
186    }
187
188    #[test]
189    fn byte_order_matches_value_order() {
190        agrees(ValType::I64, &["-9223372036854775808", "-5", "-1", "0", "1", "5", "9223372036854775807"]);
191        agrees(ValType::F64, &["-1e308", "-1.5", "-0.5", "0", "0.5", "1.5", "1e308"]);
192        agrees(ValType::Str, &["", "a", "ab", "b", "z"]);
193    }
194
195    #[test]
196    fn a_value_that_does_not_coerce_has_no_key() {
197        assert!(order_key(ValType::I64, b"cheap").is_none());
198        assert!(order_key(ValType::F64, b"").is_none());
199        assert_eq!(order_key(ValType::Str, b"anything"), Some(b"anything".to_vec()));
200    }
201}