2026-04-24 12:32:24 -06:00
|
|
|
//! Framed packet encoding and decoding.
|
2026-04-25 12:37:54 -06:00
|
|
|
use core::{fmt, mem};
|
2026-04-25 22:42:45 -06:00
|
|
|
use rkyv::{
|
|
|
|
|
Serialize, access, api::high::to_bytes_in, deserialize, rancor::Error, util::AlignedVec,
|
|
|
|
|
};
|
2026-04-24 12:32:24 -06:00
|
|
|
|
2026-04-24 13:37:30 -06:00
|
|
|
use super::types::{
|
2026-04-24 12:32:24 -06:00
|
|
|
ArchivedCallMessage, ArchivedDataMessage, ArchivedFaultMessage, ArchivedPacketHeader,
|
|
|
|
|
};
|
|
|
|
|
use crate::protocol::{CallMessage, DataMessage, FaultMessage, PacketHeader, PacketType};
|
|
|
|
|
|
2026-04-25 12:37:54 -06:00
|
|
|
/// Archived-section alignment guaranteed by the frame format.
|
|
|
|
|
pub const SECTION_ALIGN: usize = 16;
|
|
|
|
|
|
2026-04-24 12:32:24 -06:00
|
|
|
/// Owned framed packet bytes.
|
2026-04-25 12:37:54 -06:00
|
|
|
pub type FrameBytes = AlignedVec<SECTION_ALIGN>;
|
2026-04-24 12:32:24 -06:00
|
|
|
|
|
|
|
|
/// Framing or archive failure.
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
pub enum FrameError {
|
2026-04-26 01:53:37 -06:00
|
|
|
/// The byte slice ended before a full frame could be decoded.
|
2026-04-24 12:32:24 -06:00
|
|
|
Truncated,
|
2026-04-26 01:53:37 -06:00
|
|
|
/// The archived header bytes failed validation or deserialization.
|
2026-04-24 12:32:24 -06:00
|
|
|
InvalidHeader(Error),
|
2026-04-26 01:53:37 -06:00
|
|
|
/// The archived payload bytes failed validation or deserialization.
|
2026-04-24 12:32:24 -06:00
|
|
|
InvalidPayload(Error),
|
2026-04-26 01:53:37 -06:00
|
|
|
/// Serializing one header or payload section failed.
|
2026-04-24 12:32:24 -06:00
|
|
|
Serialize(Error),
|
2026-04-26 01:53:37 -06:00
|
|
|
/// One archived section grew beyond the `u32` length prefix supported by the format.
|
2026-04-24 12:32:24 -06:00
|
|
|
LengthOverflow,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl fmt::Display for FrameError {
|
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
|
match self {
|
|
|
|
|
Self::Truncated => f.write_str("truncated frame"),
|
|
|
|
|
Self::InvalidHeader(error) => write!(f, "invalid archived header: {error}"),
|
|
|
|
|
Self::InvalidPayload(error) => write!(f, "invalid archived payload: {error}"),
|
|
|
|
|
Self::Serialize(error) => write!(f, "serialization failed: {error}"),
|
|
|
|
|
Self::LengthOverflow => f.write_str("framed section exceeds u32 length"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-24 13:37:30 -06:00
|
|
|
impl core::error::Error for FrameError {}
|
2026-04-24 12:32:24 -06:00
|
|
|
|
2026-04-25 12:37:54 -06:00
|
|
|
/// Parsed frame with one owned header and a borrowed payload section.
|
2026-04-26 01:53:37 -06:00
|
|
|
///
|
|
|
|
|
/// The frame decoder eagerly materializes the routing header into owned Rust values, but keeps
|
|
|
|
|
/// the payload section borrowed so callers can choose which concrete payload type to decode.
|
2026-04-24 12:32:24 -06:00
|
|
|
pub struct ParsedFrame<'a> {
|
|
|
|
|
header: PacketHeader,
|
|
|
|
|
payload_bytes: &'a [u8],
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'a> ParsedFrame<'a> {
|
2026-04-25 11:11:19 -06:00
|
|
|
#[must_use]
|
2026-04-26 01:53:37 -06:00
|
|
|
/// Returns the decoded packet header.
|
2026-04-24 12:32:24 -06:00
|
|
|
pub fn header(&self) -> &PacketHeader {
|
|
|
|
|
&self.header
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-25 11:11:19 -06:00
|
|
|
#[must_use]
|
2026-04-26 01:53:37 -06:00
|
|
|
/// Returns the packet class from the decoded header.
|
2026-04-24 12:32:24 -06:00
|
|
|
pub fn packet_type(&self) -> PacketType {
|
|
|
|
|
self.header.packet_type
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-25 11:11:19 -06:00
|
|
|
#[must_use]
|
2026-04-26 01:53:37 -06:00
|
|
|
/// Returns the borrowed payload section bytes.
|
2026-04-24 12:32:24 -06:00
|
|
|
pub fn payload_bytes(&self) -> &'a [u8] {
|
|
|
|
|
self.payload_bytes
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-25 12:15:38 -06:00
|
|
|
#[must_use]
|
2026-04-26 01:53:37 -06:00
|
|
|
/// Splits the parsed frame into its owned header and borrowed payload bytes.
|
2026-04-25 12:15:38 -06:00
|
|
|
pub fn into_parts(self) -> (PacketHeader, &'a [u8]) {
|
|
|
|
|
(self.header, self.payload_bytes)
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-26 01:53:37 -06:00
|
|
|
/// Deserializes the payload section as a [`CallMessage`].
|
2026-04-24 12:32:24 -06:00
|
|
|
pub fn deserialize_call(&self) -> Result<CallMessage, FrameError> {
|
2026-04-26 01:53:37 -06:00
|
|
|
self.deserialize_payload::<ArchivedCallMessage, CallMessage>()
|
2026-04-24 12:32:24 -06:00
|
|
|
}
|
|
|
|
|
|
2026-04-26 01:53:37 -06:00
|
|
|
/// Deserializes the payload section as a [`DataMessage`].
|
2026-04-24 12:32:24 -06:00
|
|
|
pub fn deserialize_data(&self) -> Result<DataMessage, FrameError> {
|
2026-04-26 01:53:37 -06:00
|
|
|
self.deserialize_payload::<ArchivedDataMessage, DataMessage>()
|
2026-04-24 12:32:24 -06:00
|
|
|
}
|
|
|
|
|
|
2026-04-26 01:53:37 -06:00
|
|
|
/// Deserializes the payload section as a [`FaultMessage`].
|
2026-04-24 12:32:24 -06:00
|
|
|
pub fn deserialize_fault(&self) -> Result<FaultMessage, FrameError> {
|
2026-04-26 01:53:37 -06:00
|
|
|
self.deserialize_payload::<ArchivedFaultMessage, FaultMessage>()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn deserialize_payload<A, T>(&self) -> Result<T, FrameError>
|
|
|
|
|
where
|
|
|
|
|
A: rkyv::Portable
|
|
|
|
|
+ for<'b> rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'b, Error>>,
|
|
|
|
|
T: rkyv::Archive,
|
|
|
|
|
A: rkyv::Deserialize<T, rkyv::api::high::HighDeserializer<Error>>,
|
|
|
|
|
{
|
|
|
|
|
deserialize_archived_bytes::<A, T>(self.payload_bytes)
|
2026-04-24 12:32:24 -06:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-25 12:37:54 -06:00
|
|
|
/// Encodes a packet header and payload using the aligned two-section frame format.
|
2026-04-26 01:53:37 -06:00
|
|
|
///
|
|
|
|
|
/// The frame starts with two big-endian `u32` lengths, followed by an aligned archived header
|
|
|
|
|
/// section and an aligned archived payload section. Both sections use [`SECTION_ALIGN`] so the
|
|
|
|
|
/// archived bytes can usually be accessed without a fallback copy on decode.
|
2026-04-25 12:37:54 -06:00
|
|
|
pub fn encode_packet<P>(header: &PacketHeader, payload: &P) -> Result<FrameBytes, FrameError>
|
|
|
|
|
where
|
|
|
|
|
P: for<'a> Serialize<
|
2026-04-25 12:41:10 -06:00
|
|
|
rkyv::api::high::HighSerializer<AlignedVec, rkyv::ser::allocator::ArenaHandle<'a>, Error>,
|
2026-04-25 12:37:54 -06:00
|
|
|
>,
|
|
|
|
|
{
|
2026-04-25 13:28:20 -06:00
|
|
|
let header_start = align_up(8usize, SECTION_ALIGN);
|
2026-04-25 22:42:45 -06:00
|
|
|
// Reserve enough space for the framing prefix plus a typical header/payload pair so the
|
|
|
|
|
// common encode path avoids early growth reallocations inside `to_bytes_in`.
|
|
|
|
|
let mut frame = FrameBytes::with_capacity(header_start + 256);
|
2026-04-25 20:41:02 -06:00
|
|
|
frame.resize(header_start, 0);
|
|
|
|
|
frame = to_bytes_in::<_, Error>(header, frame).map_err(FrameError::Serialize)?;
|
2026-04-25 22:42:45 -06:00
|
|
|
let header_len =
|
|
|
|
|
u32::try_from(frame.len() - header_start).map_err(|_| FrameError::LengthOverflow)?;
|
2026-04-25 12:37:54 -06:00
|
|
|
|
2026-04-25 20:41:02 -06:00
|
|
|
let payload_start = align_up(frame.len(), SECTION_ALIGN);
|
|
|
|
|
frame.resize(payload_start, 0);
|
|
|
|
|
frame = to_bytes_in::<_, Error>(payload, frame).map_err(FrameError::Serialize)?;
|
2026-04-25 22:42:45 -06:00
|
|
|
let payload_len =
|
|
|
|
|
u32::try_from(frame.len() - payload_start).map_err(|_| FrameError::LengthOverflow)?;
|
2026-04-25 19:03:08 -06:00
|
|
|
|
|
|
|
|
frame[0..4].copy_from_slice(&header_len.to_be_bytes());
|
|
|
|
|
frame[4..8].copy_from_slice(&payload_len.to_be_bytes());
|
2026-04-25 12:37:54 -06:00
|
|
|
Ok(frame)
|
2026-04-24 13:37:30 -06:00
|
|
|
}
|
|
|
|
|
|
2026-04-25 12:37:54 -06:00
|
|
|
/// Decodes one aligned two-section frame.
|
2026-04-26 01:53:37 -06:00
|
|
|
///
|
|
|
|
|
/// This rejects trailing bytes instead of silently ignoring them, so callers can treat one byte
|
|
|
|
|
/// slice as exactly one protocol frame.
|
2026-04-25 12:37:54 -06:00
|
|
|
pub fn decode_frame(bytes: &[u8]) -> Result<ParsedFrame<'_>, FrameError> {
|
2026-04-25 22:42:45 -06:00
|
|
|
let (header_bytes, payload_bytes) = split_frame_sections(bytes)?;
|
2026-04-25 12:37:54 -06:00
|
|
|
let header = deserialize_section::<ArchivedPacketHeader, PacketHeader>(
|
2026-04-25 22:42:45 -06:00
|
|
|
header_bytes,
|
2026-04-25 12:37:54 -06:00
|
|
|
FrameError::InvalidHeader,
|
|
|
|
|
)?;
|
|
|
|
|
|
|
|
|
|
Ok(ParsedFrame {
|
|
|
|
|
header,
|
2026-04-25 22:42:45 -06:00
|
|
|
payload_bytes,
|
2026-04-25 12:37:54 -06:00
|
|
|
})
|
2026-04-24 13:37:30 -06:00
|
|
|
}
|
|
|
|
|
|
2026-04-25 12:37:54 -06:00
|
|
|
/// Deserializes one archived byte section.
|
2026-04-26 01:53:37 -06:00
|
|
|
///
|
|
|
|
|
/// Payload bytes normally come from [`decode_frame`] or one of [`ParsedFrame`]`'s`
|
|
|
|
|
/// `deserialize_*` helpers. This function remains public for callers that archive nested
|
|
|
|
|
/// application payloads inside protocol `data` fields.
|
2026-04-25 12:37:54 -06:00
|
|
|
pub fn deserialize_archived_bytes<A, T>(bytes: &[u8]) -> Result<T, FrameError>
|
2026-04-24 12:32:24 -06:00
|
|
|
where
|
2026-04-25 12:37:54 -06:00
|
|
|
A: rkyv::Portable
|
|
|
|
|
+ for<'b> rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'b, Error>>,
|
|
|
|
|
T: rkyv::Archive,
|
|
|
|
|
A: rkyv::Deserialize<T, rkyv::api::high::HighDeserializer<Error>>,
|
2026-04-24 12:32:24 -06:00
|
|
|
{
|
2026-04-25 12:37:54 -06:00
|
|
|
deserialize_section::<A, T>(bytes, FrameError::InvalidPayload)
|
2026-04-24 12:32:24 -06:00
|
|
|
}
|
|
|
|
|
|
2026-04-25 12:37:54 -06:00
|
|
|
fn read_u32(bytes: &[u8], start: usize) -> Result<u32, FrameError> {
|
|
|
|
|
let end = start + 4;
|
|
|
|
|
Ok(u32::from_be_bytes(
|
|
|
|
|
bytes
|
|
|
|
|
.get(start..end)
|
|
|
|
|
.ok_or(FrameError::Truncated)?
|
|
|
|
|
.try_into()
|
|
|
|
|
.expect("slice width checked"),
|
|
|
|
|
))
|
2026-04-24 12:32:24 -06:00
|
|
|
}
|
2026-04-25 22:42:45 -06:00
|
|
|
|
|
|
|
|
fn split_frame_sections(bytes: &[u8]) -> Result<(&[u8], &[u8]), FrameError> {
|
|
|
|
|
if bytes.len() < 8 {
|
|
|
|
|
return Err(FrameError::Truncated);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let header_len = read_u32(bytes, 0)? as usize;
|
|
|
|
|
let payload_len = read_u32(bytes, 4)? as usize;
|
|
|
|
|
let header_start = align_up(8usize, SECTION_ALIGN);
|
|
|
|
|
let header_end = header_start + header_len;
|
|
|
|
|
if header_end > bytes.len() {
|
|
|
|
|
return Err(FrameError::Truncated);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let payload_start = align_up(header_end, SECTION_ALIGN);
|
|
|
|
|
let payload_end = payload_start + payload_len;
|
|
|
|
|
if payload_end != bytes.len() {
|
2026-04-26 01:53:37 -06:00
|
|
|
// Framed packets do not permit trailing bytes. Treating the slice as exactly one frame
|
|
|
|
|
// keeps stream framing bugs visible instead of silently accepting concatenated payloads.
|
2026-04-25 22:42:45 -06:00
|
|
|
return Err(FrameError::Truncated);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Ok((
|
|
|
|
|
bytes
|
|
|
|
|
.get(header_start..header_end)
|
|
|
|
|
.ok_or(FrameError::Truncated)?,
|
|
|
|
|
bytes
|
|
|
|
|
.get(payload_start..payload_end)
|
|
|
|
|
.ok_or(FrameError::Truncated)?,
|
|
|
|
|
))
|
|
|
|
|
}
|
2026-04-25 12:37:54 -06:00
|
|
|
|
|
|
|
|
fn align_up(offset: usize, alignment: usize) -> usize {
|
|
|
|
|
let mask = alignment - 1;
|
|
|
|
|
(offset + mask) & !mask
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn deserialize_section<A, T>(
|
|
|
|
|
bytes: &[u8],
|
|
|
|
|
invalid: fn(Error) -> FrameError,
|
|
|
|
|
) -> Result<T, FrameError>
|
2026-04-24 12:32:24 -06:00
|
|
|
where
|
|
|
|
|
A: rkyv::Portable
|
|
|
|
|
+ for<'b> rkyv::bytecheck::CheckBytes<rkyv::api::high::HighValidator<'b, Error>>,
|
|
|
|
|
T: rkyv::Archive,
|
|
|
|
|
A: rkyv::Deserialize<T, rkyv::api::high::HighDeserializer<Error>>,
|
|
|
|
|
{
|
2026-04-25 12:37:54 -06:00
|
|
|
if is_aligned_for::<A>(bytes) {
|
|
|
|
|
let archived = access::<A, Error>(bytes).map_err(invalid)?;
|
|
|
|
|
return deserialize::<T, Error>(archived).map_err(invalid);
|
|
|
|
|
}
|
2026-04-24 12:32:24 -06:00
|
|
|
|
2026-04-26 01:53:37 -06:00
|
|
|
// Archived types may require stronger alignment than a borrowed byte slice can guarantee.
|
|
|
|
|
// Copy into an aligned buffer so callers can still decode valid frames from arbitrary input
|
|
|
|
|
// sources instead of rejecting them purely for allocation layout reasons.
|
2026-04-25 12:37:54 -06:00
|
|
|
let mut aligned: FrameBytes = FrameBytes::with_capacity(bytes.len());
|
2026-04-24 12:32:24 -06:00
|
|
|
aligned.extend_from_slice(bytes);
|
2026-04-25 12:37:54 -06:00
|
|
|
let archived = access::<A, Error>(&aligned).map_err(invalid)?;
|
|
|
|
|
deserialize::<T, Error>(archived).map_err(invalid)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn is_aligned_for<A>(bytes: &[u8]) -> bool {
|
|
|
|
|
let alignment = mem::align_of::<A>();
|
|
|
|
|
alignment <= 1 || (bytes.as_ptr() as usize).is_multiple_of(alignment)
|
2026-04-24 12:32:24 -06:00
|
|
|
}
|