pub trait Decoder: Send {
type Output: Send;
fn decode(&mut self, raw_data: &[u8]) -> Option<Self::Output>;
}
#[derive(Debug, Clone, Default, PartialEq)]
#[cfg_attr(feature = "json", derive(serde::Serialize, serde::Deserialize))]
pub struct TelemetryPacket {
pub position: [f32; 3],
pub rotation: [f32; 3],
pub timestamp_ms: u64,
}
#[cfg(feature = "json")]
pub struct JsonDecoder;
#[cfg(feature = "json")]
impl Decoder for JsonDecoder {
type Output = TelemetryPacket;
fn decode(&mut self, raw_data: &[u8]) -> Option<TelemetryPacket> {
serde_json::from_slice(raw_data).ok()
}
}
pub struct BinaryDecoder;
impl Decoder for BinaryDecoder {
type Output = TelemetryPacket;
fn decode(&mut self, raw_data: &[u8]) -> Option<TelemetryPacket> {
const LEN: usize = 28;
if raw_data.len() < LEN {
return None;
}
let read_f32 = |offset: usize| -> f32 {
let bytes: [u8; 4] = raw_data[offset..offset + 4].try_into().unwrap();
f32::from_le_bytes(bytes)
};
let read_u32 = |offset: usize| -> u32 {
let bytes: [u8; 4] = raw_data[offset..offset + 4].try_into().unwrap();
u32::from_le_bytes(bytes)
};
Some(TelemetryPacket {
position: [read_f32(0), read_f32(4), read_f32(8)],
rotation: [read_f32(12), read_f32(16), read_f32(20)],
timestamp_ms: read_u32(24) as u64,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn binary_decoder_rejects_short_frames() {
assert_eq!(BinaryDecoder.decode(&[0u8; 10]), None);
}
#[test]
fn binary_decoder_round_trip() {
let mut raw = Vec::new();
for v in [1.0f32, 2.0, 3.0, 0.1, 0.2, 0.3] {
raw.extend_from_slice(&v.to_le_bytes());
}
raw.extend_from_slice(&42u32.to_le_bytes());
let packet = BinaryDecoder.decode(&raw).expect("trame valide");
assert_eq!(packet.position, [1.0, 2.0, 3.0]);
assert_eq!(packet.rotation, [0.1, 0.2, 0.3]);
assert_eq!(packet.timestamp_ms, 42);
}
}