Skip to main content

automotive_wire_codec/
encode.rs

1//! The [`Encode`] trait: serialize a value into a [`Sink`].
2
3use crate::sink::{CountingSink, Sink, SliceSink};
4use crate::write::WriteError;
5
6/// TX-side: serialize `self` into a [`Sink`].
7pub trait Encode {
8    /// Per-implementation error, constructible from a [`WriteError`] so every
9    /// write helper lifts through `?`.
10    ///
11    /// One `From` impl covers the whole write path — the sink, the fixed-width
12    /// helpers, and the variable-width [`write_be_uint`](crate::write_be_uint).
13    type Error: From<WriteError>;
14
15    /// Exact number of bytes [`encode`](Encode::encode) will write.
16    ///
17    /// The default runs `encode` against an infallible [`CountingSink`] and
18    /// returns the bytes actually written — correct by construction, so
19    /// hand-maintained sizes cannot drift from `encode`. Override only where a
20    /// closed-form size is cheaper on a hot path; an override MUST return
21    /// exactly the byte count a successful `encode` writes.
22    ///
23    /// An `encode` implementation that relies on this default must NOT call
24    /// `self.encoded_size()` (infinite recursion). Calling `encoded_size()` on
25    /// *nested fields* is fine, and is the intended pre-sizing pattern.
26    ///
27    /// This is no longer on the path to a decent error message — a bounded
28    /// sink reports [`WriteError::Insufficient`] directly — but it remains the
29    /// answer to "how big is this", and the only way to get an *exact* total
30    /// rather than the lower bound a failed write reports.
31    ///
32    /// # Errors
33    /// Whatever `encode` returns for a value that cannot be encoded; the
34    /// counting sink itself never fails.
35    ///
36    /// # Panics
37    /// In debug builds, if `encode` returns a byte count different from the
38    /// bytes it actually wrote — that is a bug in the `encode` impl
39    /// (`written == encoded_size()?` is a hard invariant).
40    fn encoded_size(&self) -> Result<usize, Self::Error> {
41        let mut sink = CountingSink::new();
42        let reported = self.encode(&mut sink)?;
43        debug_assert!(
44            reported == sink.count(),
45            "encode returned {reported} but wrote {} bytes",
46            sink.count()
47        );
48        Ok(sink.count())
49    }
50
51    /// Serialize into `sink`; return the number of bytes written.
52    ///
53    /// **`encode` must be a pure function of `&self`** — same bytes every
54    /// call, no observable side effects. The default
55    /// [`encoded_size`](Encode::encoded_size) invokes it a second time to
56    /// count. An implementation that mutates through interior mutability
57    /// (e.g. a rolling sequence counter) will have that side effect applied
58    /// per *invocation*, not per frame — advance such state outside `encode`,
59    /// then encode the snapshot.
60    ///
61    /// # Errors
62    /// `Self::Error` if the sink rejects a write or the value cannot be encoded.
63    fn encode(&self, sink: &mut impl Sink) -> Result<usize, Self::Error>;
64
65    /// Encode into a fixed slice; return the number of bytes written.
66    ///
67    /// A [`SliceSink`] knows its capacity, so a slice too small fails with
68    /// [`WriteError::Insufficient`] carrying `needed_at_least`/`available` —
69    /// lifted into `Self::Error` like any other write failure. There is no
70    /// separate error type and no sizing pass: `encode` runs exactly once
71    /// whether it succeeds or fails.
72    ///
73    /// `needed_at_least` is a lower bound, not the encode's total — the
74    /// encode stopped at the failing write, so what remained was never
75    /// measured. Call [`encoded_size`](Encode::encoded_size) for an exact
76    /// total.
77    ///
78    /// On error, `buf` may hold partially written bytes; on success, bytes
79    /// past the returned count are untouched.
80    ///
81    /// # Errors
82    /// `Self::Error` if `buf` is too small or the value cannot be encoded.
83    fn encode_to_slice(&self, buf: &mut [u8]) -> Result<usize, Self::Error> {
84        let mut sink = SliceSink::new(buf);
85        self.encode(&mut sink)
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use crate::error::InsufficientBuffer;
93    use crate::sink::Limited;
94    use crate::write::{WriteError, write_u16_be};
95
96    #[derive(Debug, Eq, PartialEq)]
97    enum TestErr {
98        Write(WriteError),
99        Value,
100    }
101    impl From<WriteError> for TestErr {
102        fn from(e: WriteError) -> Self {
103            TestErr::Write(e)
104        }
105    }
106
107    struct Val(u16);
108    impl Encode for Val {
109        type Error = TestErr;
110        fn encoded_size(&self) -> Result<usize, TestErr> {
111            Ok(2)
112        }
113        fn encode(&self, sink: &mut impl Sink) -> Result<usize, TestErr> {
114            Ok(write_u16_be(sink, self.0)?)
115        }
116    }
117
118    // Uses the default encoded_size - no hand-written size at all.
119    struct TwoVals(u16, u16);
120    impl Encode for TwoVals {
121        type Error = TestErr;
122        fn encode(&self, sink: &mut impl Sink) -> Result<usize, TestErr> {
123            let mut n = write_u16_be(sink, self.0)?;
124            n += write_u16_be(sink, self.1)?;
125            Ok(n)
126        }
127    }
128
129    // Fails for a VALUE reason: default encoded_size must surface it, not panic.
130    struct Rejecting;
131    impl Encode for Rejecting {
132        type Error = TestErr;
133        fn encode(&self, _sink: &mut impl Sink) -> Result<usize, TestErr> {
134            Err(TestErr::Value)
135        }
136    }
137
138    #[test]
139    fn encode_writes_and_counts() {
140        let mut buf = [0u8; 4];
141        let mut sink = SliceSink::new(&mut buf);
142        let n = Val(0xABCD).encode(&mut sink).unwrap();
143        assert_eq!(n, 2);
144        assert_eq!(&buf[..2], &[0xAB, 0xCD]);
145    }
146
147    #[test]
148    fn default_encoded_size_counts_actual_bytes() {
149        assert_eq!(TwoVals(1, 2).encoded_size().unwrap(), 4);
150    }
151
152    #[test]
153    fn default_encoded_size_surfaces_value_errors() {
154        assert_eq!(TwoVals(1, 2).encoded_size().unwrap(), 4);
155        assert_eq!(Rejecting.encoded_size(), Err(TestErr::Value));
156    }
157
158    #[test]
159    fn override_still_supported() {
160        assert_eq!(Val(0xABCD).encoded_size().unwrap(), 2);
161    }
162
163    #[test]
164    fn encode_to_slice_writes_and_counts() {
165        let mut buf = [0u8; 4];
166        assert_eq!(Val(0xABCD).encode_to_slice(&mut buf).unwrap(), 2);
167        assert_eq!(&buf[..2], &[0xAB, 0xCD]);
168    }
169
170    #[test]
171    fn encode_to_slice_too_small_reports_counts_in_self_error() {
172        // One error type on the encode path: no EncodeToSliceError.
173        let mut buf = [0u8; 1];
174        assert_eq!(
175            Val(0xABCD).encode_to_slice(&mut buf),
176            Err(TestErr::Write(WriteError::Insufficient(
177                InsufficientBuffer {
178                    needed_at_least: 2,
179                    available: 1
180                }
181            )))
182        );
183    }
184
185    #[test]
186    fn encode_to_slice_propagates_value_errors() {
187        let mut buf = [0u8; 8];
188        assert_eq!(Rejecting.encode_to_slice(&mut buf), Err(TestErr::Value));
189    }
190
191    // Counts encode() invocations; uses the default (counting) encoded_size.
192    struct CountsEncodes<'a>(&'a core::cell::Cell<u32>);
193    impl Encode for CountsEncodes<'_> {
194        type Error = TestErr;
195        fn encode(&self, sink: &mut impl Sink) -> Result<usize, TestErr> {
196            self.0.set(self.0.get() + 1);
197            Ok(write_u16_be(sink, 0xABCD)?)
198        }
199    }
200
201    #[test]
202    fn encode_to_slice_is_single_pass_on_success() {
203        let calls = core::cell::Cell::new(0);
204        let mut buf = [0u8; 4];
205        assert_eq!(CountsEncodes(&calls).encode_to_slice(&mut buf).unwrap(), 2);
206        assert_eq!(calls.get(), 1);
207    }
208
209    #[test]
210    fn encode_to_slice_is_single_pass_on_failure() {
211        // New in 0.4: the classify-after-failure pass is gone, so the failure
212        // path costs exactly one encode too.
213        let calls = core::cell::Cell::new(0);
214        let mut buf = [0u8; 1];
215        assert!(CountsEncodes(&calls).encode_to_slice(&mut buf).is_err());
216        assert_eq!(calls.get(), 1);
217    }
218
219    #[test]
220    fn counting_sink_backs_encode() {
221        let mut sink = CountingSink::new();
222        assert_eq!(Val(0xABCD).encode(&mut sink).unwrap(), 2);
223        assert_eq!(sink.count(), 2);
224        Val(0x0102).encode(&mut sink).unwrap();
225        assert_eq!(sink.count(), 4);
226    }
227
228    #[test]
229    fn encode_through_limited_fails_over_long_with_budget_as_available() {
230        // Spec acceptance: a `Limited` wrapping a larger buffer fails an
231        // over-long *encode*, not just a raw `write_all`. A transport driver
232        // turns this into `responseTooLong`.
233        let mut buf = [0u8; 64];
234        let budget = 1;
235        let mut sink = Limited::new(SliceSink::new(&mut buf), budget);
236        assert_eq!(
237            Val(0xABCD).encode(&mut sink),
238            Err(TestErr::Write(WriteError::Insufficient(
239                InsufficientBuffer {
240                    needed_at_least: 2,
241                    available: budget
242                }
243            )))
244        );
245    }
246}