ferravex_net/
delta.rs

1//! Versioned byte snapshot differences. Callers acknowledge exact baselines before using a delta.
2//!
3//! The inner bytes remain `[length: u16 LE, tag: u8, body...]`: tag 0 stores
4//! the full snapshot, tag 1 stores ordered `[index: u16 LE, value: u8]` entries.
5//! Construction chooses sparse only when its body is strictly smaller. The
6//! checked buffer methods allocate nothing, validate before writing, and leave
7//! unused destination tails untouched. Safe Rust requires disjoint input and
8//! output borrows; these methods do not support overlapping/in-place application.
9//! No method authenticates a baseline's contents, session, ACK or tick ordering.
10//!
11//! This runnable acknowledged-base recipe uses the actual v5 snapshot, ACK and
12//! delta packet codecs. It models one already-installed baseline, not a retention
13//! or ACK-authorization policy. Outer packet codecs still allocate and enforce
14//! their own tighter size and tick-order limits; fall back to a full snapshot if
15//! delta construction or packet encoding fails in a real sender.
16//!
17//! ```
18//! use ferravex_net::{
19//!     ClientExtension, ClientPacket, ServerExtension, ServerPacket, Snapshot,
20//!     MAX_PACKET_BYTES, decode_client, decode_server, encode_client, encode_server,
21//!     delta::Delta,
22//! };
23//!
24//! fn main() -> Result<(), Box<dyn std::error::Error>> {
25//!     let baseline = Snapshot { session: 7, tick: 40, ..Snapshot::default() };
26//!     let base = encode_server(&ServerPacket::Snapshot(baseline.clone()))?;
27//!     // The receiver validates and installs the full snapshot before ACKing it.
28//!     assert_eq!(decode_server(&base)?, ServerPacket::Snapshot(baseline.clone()));
29//!     let ack = encode_client(&ClientPacket::Extension(ClientExtension::SnapshotAck {
30//!         session: baseline.session, tick: Some(baseline.tick),
31//!     }))?;
32//!     let ClientPacket::Extension(ClientExtension::SnapshotAck {
33//!         session: 7, tick: Some(40),
34//!     }) = decode_client(&ack)? else { panic!("unexpected ACK") };
35//!     // The sender selects these exact retained bytes for that acknowledged tick.
36//!     let mut next = baseline;
37//!     next.tick = 41;
38//!     let full = encode_server(&ServerPacket::Snapshot(next.clone()))?;
39//!     let mut delta = Delta { base_tick: 0, tick: 0,
40//!         bytes: Vec::with_capacity(MAX_PACKET_BYTES) };
41//!     delta.between_into(40, &base, 41, &full)?;
42//!     let packet = encode_server(&ServerPacket::Extension(
43//!         ServerExtension::SnapshotDelta { session: 7, delta },
44//!     ))?;
45//!     let ServerPacket::Extension(ServerExtension::SnapshotDelta {
46//!         session: 7, delta,
47//!     }) = decode_server(&packet)? else { panic!("unexpected delta") };
48//!     let mut output = [0; MAX_PACKET_BYTES];
49//!     let len = delta.applied_len(40, &base)?;
50//!     assert_eq!(delta.apply_into(40, &base, &mut output)?, len);
51//!     let ServerPacket::Snapshot(recovered) = decode_server(&output[..len])?
52//!         else { panic!("unexpected reconstructed packet") };
53//!     assert_eq!(recovered.session, 7);
54//!     assert_eq!(recovered.tick, delta.tick);
55//!     assert_eq!(recovered, next); // Publish/ACK only after these checks.
56//!     Ok(())
57//! }
58//! ```
59use crate::{MAX_PACKET_BYTES, ProtocolError};
60
61const MAX_SNAPSHOT_BYTES: usize = MAX_PACKET_BYTES - 11;
62const MAX_DELTA_BYTES: usize = MAX_PACKET_BYTES - 8;
63
64/// Exact rejection from the checked delta APIs. All indices are zero based and
65/// lengths/capacities are bytes. Legacy methods map every rejection to
66/// [`ProtocolError::Invalid`].
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub enum DeltaError {
69    LengthMismatch {
70        base: usize,
71        next: usize,
72    },
73    SnapshotTooLarge {
74        len: usize,
75        max: usize,
76    },
77    Capacity {
78        required: usize,
79        available: usize,
80    },
81    /// Expected is the delta's base tick; actual is the supplied base tick.
82    BaseTickMismatch {
83        expected: u32,
84        actual: u32,
85    },
86    TruncatedHeader {
87        len: usize,
88    },
89    EncodedTooLarge {
90        len: usize,
91        max: usize,
92    },
93    /// Expected is the encoded snapshot length; actual is the supplied base length.
94    BaseLengthMismatch {
95        expected: usize,
96        actual: usize,
97    },
98    InvalidTag {
99        tag: u8,
100    },
101    DenseLengthMismatch {
102        expected: usize,
103        actual: usize,
104    },
105    /// Sparse body length is not a multiple of the three-byte entry size.
106    TruncatedEntry {
107        body_len: usize,
108    },
109    EntryOutOfRange {
110        entry: usize,
111        index: usize,
112        len: usize,
113    },
114    EntryOrder {
115        entry: usize,
116        previous: usize,
117        index: usize,
118    },
119}
120impl std::fmt::Display for DeltaError {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        write!(f, "invalid Ferravex delta: {self:?}")
123    }
124}
125impl std::error::Error for DeltaError {}
126
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct Delta {
129    pub base_tick: u32,
130    pub tick: u32,
131    pub bytes: Vec<u8>,
132}
133impl Delta {
134    /// Plan the exact inner wire length without allocating. Equal lengths and
135    /// the historical snapshot limit (`MAX_PACKET_BYTES - 11`) are checked before
136    /// counting changes, so all size arithmetic is bounded. This does not plan
137    /// the outer `ServerExtension::SnapshotDelta` envelope (24 more bytes).
138    ///
139    /// ```
140    /// use ferravex_net::delta::{Delta, DeltaError};
141    /// assert_eq!(Delta::encoded_len(&[0; 10], &[1; 10]), Ok(13));
142    /// assert_eq!(Delta::encoded_len(&[0; 10], &[0; 10]), Ok(3));
143    /// assert_eq!(Delta::encoded_len(&[0], &[]),
144    ///     Err(DeltaError::LengthMismatch { base: 1, next: 0 }));
145    /// ```
146    pub fn encoded_len(base: &[u8], next: &[u8]) -> Result<usize, DeltaError> {
147        validate_snapshot_pair(base, next)?;
148        let len = next.len();
149        let dense_limit = len.div_ceil(3);
150        let changes = count_changes_capped(base, next, dense_limit);
151        Ok(3 + (changes * 3).min(len))
152    }
153
154    /// Encode just [`Delta::bytes`] into a caller slice, returning its written
155    /// prefix length. Snapshot validation precedes capacity validation. Every
156    /// error preserves the entire destination; success preserves the tail.
157    /// Uses the slice's length, not any backing Vec's capacity.
158    ///
159    /// ```
160    /// use ferravex_net::delta::Delta;
161    /// let mut output = [99; 20];
162    /// let n = Delta::encode_into(&[0; 10], &[1; 10], &mut output).unwrap();
163    /// assert_eq!(&output[..n], Delta::between(1, &[0; 10], 2, &[1; 10]).unwrap().bytes);
164    /// assert_eq!(&output[n..], &[99; 7]);
165    /// ```
166    pub fn encode_into(
167        base: &[u8],
168        next: &[u8],
169        destination: &mut [u8],
170    ) -> Result<usize, DeltaError> {
171        let required = Self::encoded_len(base, next)?;
172        check_capacity(required, destination.len())?;
173        encode_validated(base, next, &mut destination[..required]);
174        Ok(required)
175    }
176
177    /// Replace this delta using its existing Vec capacity, with no allocation.
178    /// On error, ticks, bytes, length and capacity are unchanged. On success,
179    /// bytes are replaced (never appended); unused Vec capacity is not scrubbed.
180    /// Reserve outside the hot path. This deliberately allows any tick pair,
181    /// matching [`Self::between`]; the outer wire codec checks serial ordering.
182    ///
183    /// ```
184    /// use ferravex_net::delta::Delta;
185    /// let mut delta = Delta { base_tick: 0, tick: 0, bytes: Vec::with_capacity(20) };
186    /// delta.between_into(7, &[0; 10], 8, &[1; 10]).unwrap();
187    /// delta.between_into(8, &[1; 10], 9, &[1; 10]).unwrap();
188    /// assert_eq!(delta.bytes, [10, 0, 1]); // Dense storage was replaced by sparse.
189    /// assert_eq!(delta.apply(8, &[1; 10]).unwrap(), [1; 10]);
190    /// ```
191    pub fn between_into(
192        &mut self,
193        base_tick: u32,
194        base: &[u8],
195        tick: u32,
196        next: &[u8],
197    ) -> Result<(), DeltaError> {
198        let required = Self::encoded_len(base, next)?;
199        check_capacity(required, self.bytes.capacity())?;
200        self.bytes.clear();
201        encode_into_vec(base, next, required, &mut self.bytes);
202        self.base_tick = base_tick;
203        self.tick = tick;
204        Ok(())
205    }
206
207    pub fn between(
208        base_tick: u32,
209        base: &[u8],
210        tick: u32,
211        next: &[u8],
212    ) -> Result<Self, ProtocolError> {
213        let required = Self::encoded_len(base, next).map_err(|_| ProtocolError::Invalid)?;
214        let mut bytes = Vec::with_capacity(required);
215        encode_into_vec(base, next, required, &mut bytes);
216        Ok(Self {
217            base_tick,
218            tick,
219            bytes,
220        })
221    }
222    /// Validate the entire delta and return the reconstructed snapshot length,
223    /// without allocation or writes. Checks run in this order: base tick,
224    /// header availability, base limit, encoded limit, encoded/base length,
225    /// tag/body shape, then each sparse range and order. No canonical sparse
226    /// density or value-change requirement is imposed, preserving legacy apply.
227    /// See the module's runnable snapshot recipe and [`Self::apply_into`].
228    pub fn applied_len(&self, base_tick: u32, base: &[u8]) -> Result<usize, DeltaError> {
229        if self.base_tick != base_tick {
230            return Err(DeltaError::BaseTickMismatch {
231                expected: self.base_tick,
232                actual: base_tick,
233            });
234        }
235        if self.bytes.len() < 3 {
236            return Err(DeltaError::TruncatedHeader {
237                len: self.bytes.len(),
238            });
239        }
240        if base.len() > MAX_SNAPSHOT_BYTES {
241            return Err(DeltaError::SnapshotTooLarge {
242                len: base.len(),
243                max: MAX_SNAPSHOT_BYTES,
244            });
245        }
246        if self.bytes.len() > MAX_DELTA_BYTES {
247            return Err(DeltaError::EncodedTooLarge {
248                len: self.bytes.len(),
249                max: MAX_DELTA_BYTES,
250            });
251        }
252        let len = u16::from_le_bytes([self.bytes[0], self.bytes[1]]) as usize;
253        if len != base.len() {
254            return Err(DeltaError::BaseLengthMismatch {
255                expected: len,
256                actual: base.len(),
257            });
258        }
259        let body = &self.bytes[3..];
260        match self.bytes[2] {
261            0 if body.len() != len => {
262                return Err(DeltaError::DenseLengthMismatch {
263                    expected: len,
264                    actual: body.len(),
265                });
266            }
267            0 => {}
268            1 => {
269                if !body.len().is_multiple_of(3) {
270                    return Err(DeltaError::TruncatedEntry {
271                        body_len: body.len(),
272                    });
273                }
274                let mut previous = None;
275                for (entry, bytes) in body.as_chunks::<3>().0.iter().enumerate() {
276                    let index = u16::from_le_bytes([bytes[0], bytes[1]]) as usize;
277                    if index >= len {
278                        return Err(DeltaError::EntryOutOfRange { entry, index, len });
279                    }
280                    if let Some(previous) = previous
281                        && index <= previous
282                    {
283                        return Err(DeltaError::EntryOrder {
284                            entry,
285                            previous,
286                            index,
287                        });
288                    }
289                    previous = Some(index);
290                }
291            }
292            tag => return Err(DeltaError::InvalidTag { tag }),
293        }
294        Ok(len)
295    }
296
297    /// Apply into a caller slice without allocating. Complete validation via
298    /// [`Self::applied_len`] precedes destination capacity checking and all writes.
299    /// Every error preserves the entire destination, even a late corrupt entry.
300    /// Success replaces only the returned prefix; the tail is untouched. Input
301    /// and destination must be disjoint. Matching ticks alone cannot verify the
302    /// baseline contents: select the exact retained bytes at the session layer.
303    ///
304    /// ```
305    /// use ferravex_net::delta::{Delta, DeltaError};
306    /// let delta = Delta::between(4, &[0; 10], 5, &[1; 10]).unwrap();
307    /// let mut output = [99; 12];
308    /// assert_eq!(delta.apply_into(3, &[0; 10], &mut output),
309    ///     Err(DeltaError::BaseTickMismatch { expected: 4, actual: 3 }));
310    /// assert_eq!(output, [99; 12]);
311    /// assert_eq!(delta.apply_into(4, &[0; 10], &mut output), Ok(10));
312    /// assert_eq!(output, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 99, 99]);
313    /// ```
314    pub fn apply_into(
315        &self,
316        base_tick: u32,
317        base: &[u8],
318        destination: &mut [u8],
319    ) -> Result<usize, DeltaError> {
320        let required = self.applied_len(base_tick, base)?;
321        check_capacity(required, destination.len())?;
322        self.apply_validated(base, &mut destination[..required]);
323        Ok(required)
324    }
325
326    pub fn apply(&self, base_tick: u32, base: &[u8]) -> Result<Vec<u8>, ProtocolError> {
327        let required = self
328            .applied_len(base_tick, base)
329            .map_err(|_| ProtocolError::Invalid)?;
330        let mut result = vec![0; required];
331        self.apply_validated(base, &mut result);
332        Ok(result)
333    }
334
335    fn apply_validated(&self, base: &[u8], destination: &mut [u8]) {
336        let body = &self.bytes[3..];
337        if self.bytes[2] == 0 {
338            destination.copy_from_slice(body);
339        } else {
340            destination.copy_from_slice(base);
341            for entry in body.as_chunks::<3>().0 {
342                let index = u16::from_le_bytes([entry[0], entry[1]]) as usize;
343                destination[index] = entry[2];
344            }
345        }
346    }
347}
348
349fn check_capacity(required: usize, available: usize) -> Result<(), DeltaError> {
350    if required > available {
351        Err(DeltaError::Capacity {
352            required,
353            available,
354        })
355    } else {
356        Ok(())
357    }
358}
359
360fn validate_snapshot_pair(base: &[u8], next: &[u8]) -> Result<(), DeltaError> {
361    if base.len() != next.len() {
362        return Err(DeltaError::LengthMismatch {
363            base: base.len(),
364            next: next.len(),
365        });
366    }
367    if next.len() > MAX_SNAPSHOT_BYTES {
368        return Err(DeltaError::SnapshotTooLarge {
369            len: next.len(),
370            max: MAX_SNAPSHOT_BYTES,
371        });
372    }
373    Ok(())
374}
375
376/// Counts differing bytes up to `cap`, comparing 8 bytes per word with SWAR popcount.
377#[inline]
378fn count_changes_capped(base: &[u8], next: &[u8], cap: usize) -> usize {
379    if cap == 0 {
380        return 0;
381    }
382    let mut changes = 0_usize;
383    let a_chunks = base.chunks_exact(8);
384    let b_chunks = next.chunks_exact(8);
385    let a_rem = a_chunks.remainder();
386    let b_rem = b_chunks.remainder();
387    for (ac, bc) in a_chunks.zip(b_chunks) {
388        let diff = u64::from_ne_bytes([ac[0], ac[1], ac[2], ac[3], ac[4], ac[5], ac[6], ac[7]])
389            ^ u64::from_ne_bytes([bc[0], bc[1], bc[2], bc[3], bc[4], bc[5], bc[6], bc[7]]);
390        if diff != 0 {
391            let d = diff | (diff >> 4);
392            let d = d | (d >> 2);
393            let d = (d | (d >> 1)) & 0x0101_0101_0101_0101;
394            changes += d.count_ones() as usize;
395            if changes >= cap {
396                return cap;
397            }
398        }
399    }
400    for (&a, &b) in a_rem.iter().zip(b_rem) {
401        changes += usize::from(a != b);
402    }
403    changes.min(cap)
404}
405
406/// Word-wise sparse/dense encoder into an already-sized destination slice.
407#[inline]
408fn encode_validated(base: &[u8], next: &[u8], destination: &mut [u8]) {
409    let sparse = destination.len() - 3 < next.len();
410    destination[..2].copy_from_slice(&(next.len() as u16).to_le_bytes());
411    destination[2] = u8::from(sparse);
412    if !sparse {
413        destination[3..].copy_from_slice(next);
414        return;
415    }
416    if destination.len() == 3 {
417        return;
418    }
419    let mut offset = 3_usize;
420    let mut index = 0_usize;
421    let a_chunks = base.chunks_exact(8);
422    let b_chunks = next.chunks_exact(8);
423    let a_rem = a_chunks.remainder();
424    let b_rem = b_chunks.remainder();
425    for (ac, bc) in a_chunks.zip(b_chunks) {
426        let diff = u64::from_le_bytes([ac[0], ac[1], ac[2], ac[3], ac[4], ac[5], ac[6], ac[7]])
427            ^ u64::from_le_bytes([bc[0], bc[1], bc[2], bc[3], bc[4], bc[5], bc[6], bc[7]]);
428        if diff != 0 {
429            let d = diff | (diff >> 4);
430            let d = d | (d >> 2);
431            let mut mask = (d | (d >> 1)) & 0x0101_0101_0101_0101;
432            while mask != 0 {
433                let lane = (mask.trailing_zeros() >> 3) as usize;
434                mask &= mask - 1;
435                let le = ((index + lane) as u16).to_le_bytes();
436                destination[offset] = le[0];
437                destination[offset + 1] = le[1];
438                destination[offset + 2] = bc[lane];
439                offset += 3;
440            }
441        }
442        index += 8;
443    }
444    for (lane, (&a, &b)) in a_rem.iter().zip(b_rem).enumerate() {
445        if a != b {
446            let le = ((index + lane) as u16).to_le_bytes();
447            destination[offset] = le[0];
448            destination[offset + 1] = le[1];
449            destination[offset + 2] = b;
450            offset += 3;
451        }
452    }
453}
454
455#[inline]
456fn encode_into_vec(base: &[u8], next: &[u8], required: usize, out: &mut Vec<u8>) {
457    let sparse = required - 3 < next.len();
458    out.extend_from_slice(&(next.len() as u16).to_le_bytes());
459    out.push(u8::from(sparse));
460    if !sparse {
461        out.extend_from_slice(next);
462        return;
463    }
464    if required == 3 {
465        return;
466    }
467    let mut index = 0_usize;
468    let a_chunks = base.chunks_exact(8);
469    let b_chunks = next.chunks_exact(8);
470    let a_rem = a_chunks.remainder();
471    let b_rem = b_chunks.remainder();
472    for (ac, bc) in a_chunks.zip(b_chunks) {
473        let diff = u64::from_le_bytes([ac[0], ac[1], ac[2], ac[3], ac[4], ac[5], ac[6], ac[7]])
474            ^ u64::from_le_bytes([bc[0], bc[1], bc[2], bc[3], bc[4], bc[5], bc[6], bc[7]]);
475        if diff != 0 {
476            let d = diff | (diff >> 4);
477            let d = d | (d >> 2);
478            let mut mask = (d | (d >> 1)) & 0x0101_0101_0101_0101;
479            while mask != 0 {
480                let lane = (mask.trailing_zeros() >> 3) as usize;
481                mask &= mask - 1;
482                let le = ((index + lane) as u16).to_le_bytes();
483                out.extend_from_slice(&[le[0], le[1], bc[lane]]);
484            }
485        }
486        index += 8;
487    }
488    for (lane, (&a, &b)) in a_rem.iter().zip(b_rem).enumerate() {
489        if a != b {
490            let le = ((index + lane) as u16).to_le_bytes();
491            out.extend_from_slice(&[le[0], le[1], b]);
492        }
493    }
494}
495/// Centimeter precision for a fixed world range; invalid or out-of-range values fail explicitly.
496pub fn quantize_position(value: f32) -> Option<i32> {
497    if !value.is_finite() || value.abs() > 32768.0 {
498        return None;
499    }
500    Some((value * 100.0).round() as i32)
501}
502pub fn dequantize_position(value: i32) -> Option<f32> {
503    (-3_276_800..=3_276_800)
504        .contains(&value)
505        .then_some(value as f32 / 100.0)
506}
507#[cfg(test)]
508mod tests {
509    use super::*;
510    #[test]
511    fn acknowledged_baseline_is_required_and_sparse_data_shrinks() {
512        let base = vec![0; 1000];
513        let mut next = base.clone();
514        next[20] = 4;
515        next[999] = 9;
516        let delta = Delta::between(1, &base, 2, &next).unwrap();
517        assert!(delta.bytes.len() < 20);
518        assert_eq!(delta.apply(1, &base).unwrap(), next);
519        assert!(delta.apply(0, &base).is_err());
520        let dense = Delta::between(1, &base, 2, &vec![4; 1000]).unwrap();
521        assert_eq!(dense.bytes.len(), 1003);
522        assert_eq!(dense.apply(1, &base).unwrap(), vec![4; 1000]);
523    }
524    #[test]
525    fn representation_boundaries_preserve_wire_bytes_and_packet_limit() {
526        for len in [0, 1, 2, 3, 4, 10, MAX_PACKET_BYTES - 11] {
527            let base = vec![7; len];
528            for changed in [0, len / 3, (len / 3 + 1).min(len), len] {
529                let mut next = base.clone();
530                next[..changed].fill(9);
531                let delta = Delta::between(3, &base, 4, &next).unwrap();
532                assert_eq!(delta.apply(3, &base).unwrap(), next);
533                let sparse = changed * 3 < len;
534                assert_eq!(delta.bytes[2], u8::from(sparse));
535                let mut expected = (len as u16).to_le_bytes().to_vec();
536                expected.push(u8::from(sparse));
537                if sparse {
538                    for i in 0..changed {
539                        expected.extend_from_slice(&(i as u16).to_le_bytes());
540                        expected.push(9);
541                    }
542                } else {
543                    expected.extend_from_slice(&next);
544                }
545                assert_eq!(delta.bytes, expected);
546                assert!(delta.bytes.len() <= len + 3);
547            }
548        }
549        assert!(
550            Delta::between(
551                0,
552                &[0; MAX_PACKET_BYTES - 10],
553                1,
554                &[0; MAX_PACKET_BYTES - 10]
555            )
556            .is_err()
557        );
558    }
559    #[test]
560    fn malformed_deltas_never_write_out_of_bounds() {
561        for bytes in [
562            vec![1, 0, 1, 2, 0, 9],
563            vec![1, 0, 1, 0, 0, 1, 0, 0, 2],
564            vec![1, 0, 2],
565            vec![],
566        ] {
567            assert!(
568                Delta {
569                    base_tick: 0,
570                    tick: 1,
571                    bytes
572                }
573                .apply(0, &[0])
574                .is_err()
575            );
576        }
577        assert!(quantize_position(f32::NAN).is_none());
578        assert!(
579            (dequantize_position(quantize_position(12.345).unwrap()).unwrap() - 12.345).abs()
580                <= 0.0051
581        );
582    }
583}