Skip to main content

predsync_core/predictor/
hold_last.rs

1//! Hold-last predictors for numeric and opaque fields.
2
3use super::{Predictor, PredictorError};
4#[cfg(feature = "alloc")]
5use crate::Value;
6use crate::hash::{FNV1A64_OFFSET, fnv1a64_update, state_hash_u64_pair_slice};
7use crate::opaque::{OpaqueKind, OpaqueRef, eq_opaque, hash_opaque};
8
9/// Hold-last predictor for numeric fields.
10#[derive(Debug, Clone)]
11pub struct HoldLastPredictor {
12    window: usize,
13    samples: heapless::Vec<(u64, f64), { predsync_schema::MAX_WINDOW as usize }>,
14}
15
16impl HoldLastPredictor {
17    pub const MIN_SAMPLES: usize = 1;
18
19    pub fn new(window: usize) -> Self {
20        Self {
21            window,
22            samples: heapless::Vec::new(),
23        }
24    }
25
26    pub fn update(&mut self, t: u64, x: f64) -> Result<(), PredictorError> {
27        if let Some(&(last_t, _)) = self.samples.last()
28            && t <= last_t
29        {
30            return Err(PredictorError::NonMonotonic);
31        }
32        let _ = self.samples.push((t, x));
33        if self.samples.len() > self.window {
34            self.samples.remove(0);
35        }
36        Ok(())
37    }
38
39    pub fn reset(&mut self) {
40        self.samples.clear();
41    }
42    pub fn samples(&self) -> &[(u64, f64)] {
43        &self.samples
44    }
45    pub fn state_hash(&self) -> u64 {
46        state_hash_u64_pair_slice(&self.samples)
47    }
48    pub fn predict(&self, _t: u64) -> Option<f64> {
49        self.samples.last().map(|&(_, x)| x)
50    }
51}
52
53impl Predictor for HoldLastPredictor {
54    fn reset(&mut self) {
55        HoldLastPredictor::reset(self);
56    }
57    fn update(&mut self, t: u64, x: f64) -> Result<(), PredictorError> {
58        HoldLastPredictor::update(self, t, x)
59    }
60    fn predict(&self, t: u64) -> Option<f64> {
61        HoldLastPredictor::predict(self, t)
62    }
63    fn state_hash(&self) -> u64 {
64        HoldLastPredictor::state_hash(self)
65    }
66}
67
68/// Hold-last predictor for bool, enum, string and list fields.
69/// Alloc mode keeps owned Value for compatibility; pool fields enable no-alloc migration.
70#[derive(Debug)]
71pub struct OpaqueHoldLast {
72    #[cfg(feature = "alloc")]
73    value: Option<Value>,
74    pub kind: Option<OpaqueKind>,
75    pub word_off: usize,
76    pub byte_off: usize,
77    pub len: usize,
78}
79
80impl OpaqueHoldLast {
81    pub fn new() -> Self {
82        Self {
83            #[cfg(feature = "alloc")]
84            value: None,
85            kind: None,
86            word_off: 0,
87            byte_off: 0,
88            len: 0,
89        }
90    }
91
92    #[cfg(feature = "alloc")]
93    pub fn update(&mut self, value: Value) {
94        self.value = Some(value);
95    }
96
97    pub fn reset(&mut self) {
98        #[cfg(feature = "alloc")]
99        {
100            self.value = None;
101        }
102        self.kind = None;
103        self.len = 0;
104        // word_off/byte_off are fixed slot configuration
105    }
106
107    #[cfg(feature = "alloc")]
108    pub fn predict(&self) -> Option<&Value> {
109        self.value.as_ref()
110    }
111
112    #[cfg(feature = "alloc")]
113    pub fn matches(&self, value: &Value) -> bool {
114        self.value.as_ref() == Some(value)
115    }
116
117    pub fn state_hash(&self) -> u64 {
118        #[cfg(feature = "alloc")]
119        if let Some(value) = &self.value {
120            return crate::opaque::hash_value(value);
121        }
122        fnv1a64_update(FNV1A64_OFFSET, &[0])
123    }
124
125    /// Configure the fixed pool slot used by this predictor instance.
126    pub fn configure_opaque_pool(&mut self, word_off: usize, byte_off: usize) {
127        self.word_off = word_off;
128        self.byte_off = byte_off;
129        self.kind = None;
130        self.len = 0;
131    }
132
133    // Pool-backed API
134    pub fn as_ref<'a>(&self, words: &'a [u64], bytes: &'a [u8]) -> Option<OpaqueRef<'a>> {
135        let kind = self.kind?;
136        Some(match kind {
137            OpaqueKind::Scalar => OpaqueRef::Scalar(words.get(self.word_off).copied()?),
138            OpaqueKind::List => {
139                OpaqueRef::ListWords(words.get(self.word_off..self.word_off + self.len)?)
140            }
141            OpaqueKind::Str => OpaqueRef::Str(bytes.get(self.byte_off..self.byte_off + self.len)?),
142        })
143    }
144
145    pub fn matches_ref(&self, value: OpaqueRef<'_>, words: &[u64], bytes: &[u8]) -> bool {
146        self.as_ref(words, bytes)
147            .is_some_and(|r| eq_opaque(r, value))
148    }
149
150    pub fn update_ref(
151        &mut self,
152        value: OpaqueRef<'_>,
153        words: &mut [u64],
154        bytes: &mut [u8],
155    ) -> bool {
156        match value.kind() {
157            OpaqueKind::Scalar => {
158                let Some(end) = self.word_off.checked_add(1) else {
159                    return false;
160                };
161                if end > words.len() {
162                    return false;
163                }
164                words[self.word_off] = value.word_iter().next().unwrap_or(0);
165                self.len = 1;
166            }
167            OpaqueKind::List => {
168                let Some(end) = self.word_off.checked_add(value.word_iter().count()) else {
169                    return false;
170                };
171                if end > words.len() {
172                    return false;
173                }
174                let Some(len) = value.copy_words_to(&mut words[self.word_off..end]) else {
175                    return false;
176                };
177                self.len = len;
178            }
179            OpaqueKind::Str => {
180                let value_bytes = value.bytes().unwrap_or(&[]);
181                let Some(end) = self.byte_off.checked_add(value_bytes.len()) else {
182                    return false;
183                };
184                if end > bytes.len() {
185                    return false;
186                }
187                bytes[self.byte_off..end].copy_from_slice(value_bytes);
188                self.len = value_bytes.len();
189            }
190        }
191        self.kind = Some(value.kind());
192        #[cfg(feature = "alloc")]
193        {
194            self.value = None;
195        }
196        true
197    }
198
199    pub fn state_hash_pool(&self, words: &[u64], bytes: &[u8]) -> u64 {
200        match self.as_ref(words, bytes) {
201            Some(r) => hash_opaque(r),
202            None => self.state_hash(),
203        }
204    }
205
206    #[cfg(feature = "alloc")]
207    pub fn predict_value(&self, words: &[u64], bytes: &[u8]) -> Option<Value> {
208        let r = self.as_ref(words, bytes)?;
209        Some(match r {
210            OpaqueRef::Scalar(word) => Value::Scalar(crate::Slot(word)),
211            OpaqueRef::Str(bytes) => {
212                Value::Str(alloc::string::String::from_utf8_lossy(bytes).into_owned())
213            }
214            OpaqueRef::ListWords(words) => {
215                Value::List(words.iter().map(|&w| crate::Slot(w)).collect())
216            }
217            OpaqueRef::ListSlots(slots) => Value::List(slots.to_vec()),
218        })
219    }
220
221    #[cfg(feature = "alloc")]
222    pub fn update_value(&mut self, value: &Value, words: &mut [u64], bytes: &mut [u8]) {
223        match value {
224            Value::Scalar(s) => {
225                let w = [s.0];
226                let _ = self.update_ref(OpaqueRef::Scalar(w[0]), words, bytes);
227            }
228            Value::Str(s) => {
229                let _ = self.update_ref(OpaqueRef::Str(s.as_bytes()), words, bytes);
230            }
231            Value::List(items) => {
232                let _ = self.update_ref(OpaqueRef::ListSlots(items), words, bytes);
233            }
234        }
235    }
236}
237
238impl Default for OpaqueHoldLast {
239    fn default() -> Self {
240        Self::new()
241    }
242}
243
244impl Predictor for OpaqueHoldLast {
245    fn reset(&mut self) {
246        OpaqueHoldLast::reset(self);
247    }
248    fn update(&mut self, _t: u64, _x: f64) -> Result<(), PredictorError> {
249        Ok(())
250    }
251    fn predict(&self, _t: u64) -> Option<f64> {
252        None
253    }
254    fn state_hash(&self) -> u64 {
255        OpaqueHoldLast::state_hash(self)
256    }
257}
258
259#[cfg(all(test, feature = "alloc"))]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn hold_last_predict_newest_value() {
265        let mut predictor = HoldLastPredictor::new(2);
266        predictor.update(0, 1.0).unwrap();
267        predictor.update(1, 2.0).unwrap();
268        assert_eq!(predictor.predict(9), Some(2.0));
269    }
270
271    #[test]
272    fn opaque_pool_state_hash_matches_legacy() {
273        let mut words = [0u64; 8];
274        let mut bytes = [0u8; 8];
275        let mut p = OpaqueHoldLast::new();
276        let w = [1u64];
277        assert!(p.update_ref(OpaqueRef::Scalar(w[0]), &mut words, &mut bytes,));
278        assert_eq!(p.state_hash_pool(&words, &bytes), 0x7194_F3E5_9AE4_7DCD);
279
280        let mut p = OpaqueHoldLast::new();
281        assert!(p.update_ref(OpaqueRef::Str(b"hi"), &mut words, &mut bytes,));
282        assert_eq!(p.state_hash_pool(&words, &bytes), 0x2925_2532_49F8_900F);
283    }
284}