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
111/// One query BOUND's value: [`IndexValue::parse_literal`] plus the
112/// `@` time expressions on i64 fields (`@now`, `@now-7d`,
113/// a calendar literal, per [`kevy_time::eval`]) — only ever called on
114/// bound bytes, never on row data (a row whose field holds "@now" is
115/// data, not an expression, and the write path never comes here).
116/// Non-i64 fields pass through untouched, so a str field matching a
117/// literal "@…" value stays unambiguous.
118pub fn parse_literal_bound(ty: ValType, raw: &[u8], now: i64) -> Option<IndexValue> {
119    if ty == ValType::I64 && raw.first() == Some(&b'@') {
120        return kevy_time::eval(raw, now).map(IndexValue::I64);
121    }
122    IndexValue::parse_literal(ty, raw)
123}
124
125/// [`parse_literal_bound`]'s coercing sibling for FILTER bounds.
126pub fn coerce_bound(ty: ValType, raw: &[u8], now: i64) -> Option<IndexValue> {
127    if ty == ValType::I64 && raw.first() == Some(&b'@') {
128        return kevy_time::eval(raw, now).map(IndexValue::I64);
129    }
130    IndexValue::coerce(ty, raw)
131}
132
133impl ValueTest {
134    /// `RANGE min max` on a field declared as `ty`. `None` when a bound
135    /// is not of that type — a bound the index cannot interpret is an
136    /// error, not an empty result.
137    pub fn range(ty: ValType, min: &[u8], max: &[u8]) -> Option<ValueTest> {
138        Some(ValueTest { ty, lo: IndexValue::coerce(ty, min)?, hi: IndexValue::coerce(ty, max)? })
139    }
140
141    /// [`ValueTest::range`] for query bounds: `@` time expressions
142    /// resolve against `now` on i64 fields.
143    pub fn range_at(ty: ValType, min: &[u8], max: &[u8], now: i64) -> Option<ValueTest> {
144        Some(ValueTest { ty, lo: coerce_bound(ty, min, now)?, hi: coerce_bound(ty, max, now)? })
145    }
146
147    /// `EQ v` on a field declared as `ty`.
148    pub fn eq(ty: ValType, v: &[u8]) -> Option<ValueTest> {
149        let v = IndexValue::coerce(ty, v)?;
150        Some(ValueTest { ty, lo: v.clone(), hi: v })
151    }
152
153    /// [`ValueTest::eq`] for query bounds: `@` time expressions
154    /// resolve against `now` on i64 fields.
155    pub fn eq_at(ty: ValType, v: &[u8], now: i64) -> Option<ValueTest> {
156        let v = coerce_bound(ty, v, now)?;
157        Some(ValueTest { ty, lo: v.clone(), hi: v })
158    }
159
160    /// Whether a stored value's bytes satisfy the test.
161    ///
162    /// A value that does not coerce fails: text sitting in a field
163    /// declared numeric is not inside any numeric range, and passing it
164    /// would be the accept-and-ignore shape this surface keeps refusing.
165    pub fn passes(&self, raw: &[u8]) -> bool {
166        IndexValue::coerce(self.ty, raw).is_some_and(|v| v >= self.lo && v <= self.hi)
167    }
168}
169
170/// An order-preserving byte encoding of a coerced value.
171///
172/// Two values' encodings compare with `memcmp` exactly as the values
173/// themselves compare. That is what lets `kevy-text` sort by a stored
174/// value without learning what a number is: the caller encodes once per
175/// candidate, and the segment compares bytes.
176///
177/// `None` when the raw bytes are not of that type — a document whose
178/// stored value does not coerce has no place in the order, and is sorted
179/// as missing rather than guessed at.
180pub fn order_key(ty: ValType, raw: &[u8]) -> Option<Vec<u8>> {
181    match IndexValue::coerce(ty, raw)? {
182        // Bytes already compare as themselves.
183        IndexValue::Str(v) => Some(v),
184        // Flip the sign bit: two's complement negatives have the high bit
185        // set and would otherwise sort above every positive.
186        IndexValue::I64(v) => Some(((v as u64) ^ (1 << 63)).to_be_bytes().to_vec()),
187        // The standard IEEE total-order transform. A negative float's
188        // magnitude grows with its bit pattern, so inverting every bit
189        // reverses that and drops it below the positives (whose sign bit
190        // is set instead). Coercion rejects NaN, so there is none to
191        // place.
192        IndexValue::F64(v) => {
193            let b = v.to_bits();
194            let m = if b >> 63 == 1 { !b } else { b | (1 << 63) };
195            Some(m.to_be_bytes().to_vec())
196        }
197    }
198}
199
200#[cfg(test)]
201mod order_key_tests {
202    use super::*;
203
204    /// The encoding must agree with `IndexValue`'s own order on every
205    /// pair — including across zero, which is where a naive big-endian
206    /// encoding of a signed number gets it backwards.
207    fn agrees(ty: ValType, raws: &[&str]) {
208        let mut vals: Vec<(IndexValue, Vec<u8>)> = raws
209            .iter()
210            .map(|r| {
211                (
212                    IndexValue::coerce(ty, r.as_bytes()).expect("coerces"),
213                    order_key(ty, r.as_bytes()).expect("encodes"),
214                )
215            })
216            .collect();
217        vals.sort_by(|a, b| a.1.cmp(&b.1));
218        for w in vals.windows(2) {
219            assert!(w[0].0 <= w[1].0, "{:?} then {:?} for {ty:?}", w[0].0, w[1].0);
220        }
221    }
222
223    #[test]
224    fn byte_order_matches_value_order() {
225        agrees(ValType::I64, &["-9223372036854775808", "-5", "-1", "0", "1", "5", "9223372036854775807"]);
226        agrees(ValType::F64, &["-1e308", "-1.5", "-0.5", "0", "0.5", "1.5", "1e308"]);
227        agrees(ValType::Str, &["", "a", "ab", "b", "z"]);
228    }
229
230    #[test]
231    fn a_value_that_does_not_coerce_has_no_key() {
232        assert!(order_key(ValType::I64, b"cheap").is_none());
233        assert!(order_key(ValType::F64, b"").is_none());
234        assert_eq!(order_key(ValType::Str, b"anything"), Some(b"anything".to_vec()));
235    }
236}