Skip to main content

predsync_core/
opaque.rs

1//! Canonical opaque value representation for hold-last state and hashing.
2//!
3//! Canonical form:
4//! - Scalar/enum/bool: one u64 word = `Slot.0`.
5//! - String: bytes, length; hash is over len:u64 + each byte as u64 (legacy parity).
6//! - List: len:u64 + one u64 word per element.
7//!   Quantized numeric elements store integer q as sign-extended u64 bits.
8//!   Unquantized numeric elements store raw wire bits (f64/f32 bits, integer bits).
9
10use crate::{
11    Slot,
12    hash::{FNV1A64_OFFSET, fnv1a64_update},
13};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum OpaqueKind {
17    Scalar,
18    Str,
19    List,
20}
21
22/// A borrowed canonical opaque value.
23///
24/// Lists may arrive either as raw `u64` words or as `Slot`s. The two forms
25/// have identical canonical hashing and equality; keeping both avoids an
26/// allocation when an encoder is handed a borrowed list of `Slot`s.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum OpaqueRef<'a> {
29    Scalar(u64),
30    Str(&'a [u8]),
31    ListWords(&'a [u64]),
32    ListSlots(&'a [Slot]),
33}
34
35impl<'a> OpaqueRef<'a> {
36    pub fn scalar(word: u64) -> Self {
37        Self::Scalar(word)
38    }
39
40    pub fn str(bytes: &'a [u8]) -> Self {
41        Self::Str(bytes)
42    }
43
44    pub fn list(words: &'a [u64]) -> Self {
45        Self::ListWords(words)
46    }
47
48    pub fn list_slots(slots: &'a [Slot]) -> Self {
49        Self::ListSlots(slots)
50    }
51
52    pub fn kind(self) -> OpaqueKind {
53        match self {
54            Self::Scalar(_) => OpaqueKind::Scalar,
55            Self::Str(_) => OpaqueKind::Str,
56            Self::ListWords(_) | Self::ListSlots(_) => OpaqueKind::List,
57        }
58    }
59
60    pub fn words(self) -> Option<&'a [u64]> {
61        match self {
62            Self::ListWords(words) => Some(words),
63            _ => None,
64        }
65    }
66
67    pub fn bytes(self) -> Option<&'a [u8]> {
68        match self {
69            Self::Str(bytes) => Some(bytes),
70            _ => None,
71        }
72    }
73
74    /// Copy list words into `target`, returning the number copied.
75    pub fn copy_words_to(self, target: &mut [u64]) -> Option<usize> {
76        match self {
77            Self::ListWords(words) => {
78                if words.len() > target.len() {
79                    return None;
80                }
81                target[..words.len()].copy_from_slice(words);
82                Some(words.len())
83            }
84            Self::ListSlots(slots) => {
85                if slots.len() > target.len() {
86                    return None;
87                }
88                for (cell, slot) in target[..slots.len()].iter_mut().zip(slots) {
89                    *cell = slot.0;
90                }
91                Some(slots.len())
92            }
93            _ => None,
94        }
95    }
96
97    pub fn word_iter(self) -> WordIter<'a> {
98        WordIter {
99            scalar: match self {
100                Self::Scalar(word) => Some(word),
101                _ => None,
102            },
103            words: self.words(),
104            slots: match self {
105                Self::ListSlots(slots) => Some(slots),
106                _ => None,
107            },
108            pos: 0,
109        }
110    }
111}
112
113/// Iterator over the canonical `u64` words of an [`OpaqueRef`].
114pub struct WordIter<'a> {
115    scalar: Option<u64>,
116    words: Option<&'a [u64]>,
117    slots: Option<&'a [Slot]>,
118    pos: usize,
119}
120
121impl Iterator for WordIter<'_> {
122    type Item = u64;
123
124    fn next(&mut self) -> Option<u64> {
125        if let Some(word) = self.scalar.take() {
126            return Some(word);
127        }
128        if let Some(words) = self.words {
129            let value = words.get(self.pos).copied();
130            if value.is_some() {
131                self.pos += 1;
132            }
133            return value;
134        }
135        if let Some(slots) = self.slots {
136            let value = slots.get(self.pos).map(|slot| slot.0);
137            if value.is_some() {
138                self.pos += 1;
139            }
140            return value;
141        }
142        None
143    }
144}
145
146pub fn hash_opaque(value: OpaqueRef<'_>) -> u64 {
147    let mut hash = fnv1a64_update(FNV1A64_OFFSET, &[1]);
148    match value {
149        OpaqueRef::Scalar(word) => {
150            hash = fnv1a64_update(hash, &word.to_le_bytes());
151        }
152        OpaqueRef::Str(bytes) => {
153            hash = fnv1a64_update(hash, &(bytes.len() as u64).to_le_bytes());
154            for &byte in bytes {
155                hash = fnv1a64_update(hash, &u64::from(byte).to_le_bytes());
156            }
157        }
158        OpaqueRef::ListWords(words) => {
159            hash = fnv1a64_update(hash, &(words.len() as u64).to_le_bytes());
160            for &word in words {
161                hash = fnv1a64_update(hash, &word.to_le_bytes());
162            }
163        }
164        OpaqueRef::ListSlots(slots) => {
165            hash = fnv1a64_update(hash, &(slots.len() as u64).to_le_bytes());
166            for slot in slots {
167                hash = fnv1a64_update(hash, &slot.0.to_le_bytes());
168            }
169        }
170    }
171    hash
172}
173
174pub fn eq_opaque(a: OpaqueRef<'_>, b: OpaqueRef<'_>) -> bool {
175    if a.kind() != b.kind() {
176        return false;
177    }
178    match (a, b) {
179        (OpaqueRef::Scalar(a), OpaqueRef::Scalar(b)) => a == b,
180        (OpaqueRef::Str(a), OpaqueRef::Str(b)) => a == b,
181        (
182            OpaqueRef::ListWords(_) | OpaqueRef::ListSlots(_),
183            OpaqueRef::ListWords(_) | OpaqueRef::ListSlots(_),
184        ) => a.word_iter().eq(b.word_iter()),
185        _ => false,
186    }
187}
188
189#[cfg(feature = "alloc")]
190pub fn hash_value(value: &crate::Value) -> u64 {
191    let mut hash = fnv1a64_update(FNV1A64_OFFSET, &[1]);
192    match value {
193        crate::Value::Scalar(slot) => {
194            hash = fnv1a64_update(hash, &slot.0.to_le_bytes());
195        }
196        crate::Value::Str(text) => {
197            hash = fnv1a64_update(hash, &(text.len() as u64).to_le_bytes());
198            for &byte in text.as_bytes() {
199                hash = fnv1a64_update(hash, &u64::from(byte).to_le_bytes());
200            }
201        }
202        crate::Value::List(items) => {
203            hash = fnv1a64_update(hash, &(items.len() as u64).to_le_bytes());
204            for slot in items {
205                hash = fnv1a64_update(hash, &slot.0.to_le_bytes());
206            }
207        }
208    }
209    hash
210}
211
212/// Pool-backed canonical opaque hold-last state.
213/// `words` stores list elements (or one scalar word at index 0).
214/// `bytes` stores string bytes.
215#[derive(Debug)]
216pub struct OpaquePoolState<'a> {
217    pub kind: Option<OpaqueKind>,
218    pub words: &'a mut [u64],
219    pub bytes: &'a mut [u8],
220    pub len: usize,
221}
222
223impl<'a> OpaquePoolState<'a> {
224    pub fn new(words: &'a mut [u64], bytes: &'a mut [u8]) -> Self {
225        Self {
226            kind: None,
227            words,
228            bytes,
229            len: 0,
230        }
231    }
232
233    pub fn reset(&mut self) {
234        self.kind = None;
235        self.len = 0;
236    }
237
238    pub fn is_set(&self) -> bool {
239        self.kind.is_some()
240    }
241
242    pub fn as_ref(&self) -> Option<OpaqueRef<'_>> {
243        let kind = self.kind?;
244        Some(match kind {
245            OpaqueKind::Scalar => OpaqueRef::Scalar(self.words.first().copied().unwrap_or(0)),
246            OpaqueKind::List => OpaqueRef::ListWords(&self.words[..self.len]),
247            OpaqueKind::Str => OpaqueRef::Str(&self.bytes[..self.len]),
248        })
249    }
250
251    pub fn hash(&self) -> u64 {
252        match self.as_ref() {
253            Some(r) => hash_opaque(r),
254            None => fnv1a64_update(FNV1A64_OFFSET, &[0]),
255        }
256    }
257
258    pub fn matches(&self, value: OpaqueRef<'_>) -> bool {
259        self.as_ref().is_some_and(|r| eq_opaque(r, value))
260    }
261
262    #[allow(clippy::result_unit_err)]
263    pub fn set(&mut self, value: OpaqueRef<'_>) -> Result<(), ()> {
264        match value.kind() {
265            OpaqueKind::Scalar => {
266                if self.words.is_empty() {
267                    return Err(());
268                }
269                self.words[0] = value.word_iter().next().unwrap_or(0);
270                self.len = 1;
271            }
272            OpaqueKind::List => {
273                let count = value.word_iter().count();
274                if count > self.words.len() {
275                    return Err(());
276                }
277                for (target, word) in self.words[..count].iter_mut().zip(value.word_iter()) {
278                    *target = word;
279                }
280                self.len = count;
281            }
282            OpaqueKind::Str => {
283                let bytes = value.bytes().unwrap_or(&[]);
284                if bytes.len() > self.bytes.len() {
285                    return Err(());
286                }
287                self.bytes[..bytes.len()].copy_from_slice(bytes);
288                self.len = bytes.len();
289            }
290        }
291        self.kind = Some(value.kind());
292        Ok(())
293    }
294
295    pub fn predict_ref(&self) -> Option<OpaqueRef<'_>> {
296        self.as_ref()
297    }
298}
299
300/// Canonicalize a numeric list element. Quantized: sign-extended q as u64 bits.
301/// Unquantized: raw wire bits as stored in Slot.
302pub fn numeric_list_word(value: f64, q: Option<i64>, slot_ty: crate::slot::ScalarType) -> u64 {
303    if let Some(q) = q {
304        return q as u64;
305    }
306    match slot_ty {
307        crate::slot::ScalarType::Bool => crate::Slot::from_bool(value >= 0.5).0,
308        crate::slot::ScalarType::U8 => crate::Slot::from_u8(value as u8).0,
309        crate::slot::ScalarType::U16 => crate::Slot::from_u16(value as u16).0,
310        crate::slot::ScalarType::U32 => crate::Slot::from_u32(value as u32).0,
311        crate::slot::ScalarType::U64 => crate::Slot::from_u64(value as u64).0,
312        crate::slot::ScalarType::I8 => crate::Slot::from_i8(value as i8).0,
313        crate::slot::ScalarType::I16 => crate::Slot::from_i16(value as i16).0,
314        crate::slot::ScalarType::I32 => crate::Slot::from_i32(value as i32).0,
315        crate::slot::ScalarType::I64 => crate::Slot::from_i64(value as i64).0,
316        crate::slot::ScalarType::F32 => crate::Slot::from_f32(value as f32).0,
317        crate::slot::ScalarType::F64 => crate::Slot::from_f64(value).0,
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324    #[cfg(feature = "alloc")]
325    use crate::Value;
326    #[cfg(feature = "alloc")]
327    use alloc::{string::String, vec};
328
329    #[cfg(feature = "alloc")]
330    #[test]
331    fn canonical_hash_matches_legacy_value_hash() {
332        let cases = [
333            Value::Scalar(Slot(1)),
334            Value::Str(String::from("hi")),
335            Value::List(vec![Slot(1), Slot(2)]),
336            Value::List(vec![]),
337        ];
338        for value in cases {
339            let legacy = hash_value(&value);
340            let canonical = match &value {
341                Value::Scalar(s) => hash_opaque(OpaqueRef::Scalar(s.0)),
342                Value::Str(s) => hash_opaque(OpaqueRef::Str(s.as_bytes())),
343                Value::List(items) => hash_opaque(OpaqueRef::ListSlots(items)),
344            };
345            assert_eq!(legacy, canonical, "value {value:?}");
346        }
347    }
348
349    #[test]
350    fn canonical_hash_matches_known_opaque_hashes() {
351        assert_eq!(hash_opaque(OpaqueRef::Scalar(1)), 0x7194_F3E5_9AE4_7DCD);
352        assert_eq!(hash_opaque(OpaqueRef::Str(b"hi")), 0x2925_2532_49F8_900F);
353        assert_eq!(
354            hash_opaque(OpaqueRef::ListWords(&[1u64, 2u64])),
355            0x19EE_6800_0340_976D
356        );
357        assert_eq!(
358            hash_opaque(OpaqueRef::ListWords(&[])),
359            0x529A_2CDC_8FF5_33AC
360        );
361    }
362
363    #[test]
364    fn list_words_and_slots_hash_identically() {
365        let slots = [Slot(1), Slot(2)];
366        assert_eq!(
367            hash_opaque(OpaqueRef::ListSlots(&slots)),
368            hash_opaque(OpaqueRef::ListWords(&[1, 2]))
369        );
370        assert!(eq_opaque(
371            OpaqueRef::ListSlots(&slots),
372            OpaqueRef::ListWords(&[1, 2])
373        ));
374    }
375}