1use 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#[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 BaseTickMismatch {
83 expected: u32,
84 actual: u32,
85 },
86 TruncatedHeader {
87 len: usize,
88 },
89 EncodedTooLarge {
90 len: usize,
91 max: usize,
92 },
93 BaseLengthMismatch {
95 expected: usize,
96 actual: usize,
97 },
98 InvalidTag {
99 tag: u8,
100 },
101 DenseLengthMismatch {
102 expected: usize,
103 actual: usize,
104 },
105 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 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 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 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 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 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#[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#[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}
495pub 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}