moq_lite/lite/
message.rs

1use bytes::{Buf, BufMut};
2
3use crate::coding::{Decode, DecodeError, Encode, Sizer};
4
5/// A trait for messages that are automatically size-prefixed during encoding/decoding.
6///
7/// This trait wraps the existing Encode/Decode traits and automatically handles:
8/// - Prefixing messages with their encoded size during encoding
9/// - Reading the size prefix and validating exact consumption during decoding
10/// - Ensuring no bytes are left over or missing after decoding
11pub trait Message: Sized {
12	/// Encode this message with a size prefix.
13	fn encode<W: BufMut>(&self, w: &mut W);
14
15	/// Decode a size-prefixed message, ensuring exact size consumption.
16	fn decode<B: Buf>(buf: &mut B) -> Result<Self, DecodeError>;
17}
18
19// Blanket implementation for all types that implement Encode + Decode
20impl<T: Message> Encode for T {
21	fn encode<W: BufMut>(&self, w: &mut W) {
22		let mut sizer = Sizer::default();
23		Message::encode(self, &mut sizer);
24		sizer.size.encode(w);
25		Message::encode(self, w);
26	}
27}
28
29impl<T: Message> Decode for T {
30	fn decode<B: Buf>(buf: &mut B) -> Result<Self, DecodeError> {
31		let size = usize::decode(buf)?;
32		let mut limited = buf.take(size);
33		let result = Message::decode(&mut limited)?;
34		if limited.remaining() > 0 {
35			return Err(DecodeError::Long);
36		}
37
38		Ok(result)
39	}
40}