1#[cfg(test)]
2mod tests;
3
4use crate::{Error, Limits, Wire};
5use alloc::vec::Vec;
6use core::{cell::Cell, marker::PhantomData};
7use postcard::ser_flavors::Flavor;
8
9pub(crate) const HEADER: usize = 11;
10
11pub trait Method {
14 type Request: Wire;
17 type Response: Wire;
19 const ID: u64;
21 const NAME: &'static str;
23 const REQUEST_LIMITS: Limits;
25 const RESPONSE_LIMITS: Limits;
27}
28
29macro_rules! retained {
30 ($name:ident) => {
31 pub struct $name<M: Method> {
34 bytes: Vec<u8>,
35 method: PhantomData<fn() -> M>,
36 }
37 impl<M: Method> $name<M> {
38 pub fn as_bytes(&self) -> &[u8] {
40 &self.bytes
41 }
42 pub fn into_bytes(self) -> Vec<u8> {
44 self.bytes
45 }
46 }
47 };
48}
49retained!(RequestBytes);
50retained!(ResponseBytes);
51
52pub(crate) fn admit<T: Wire>(limits: Limits) -> Result<usize, Error> {
53 let shape = T::SHAPE;
54 if [shape.bytes, shape.heap, shape.nodes, shape.depth].contains(&usize::MAX) {
55 return Err(Error::SchemaLimit);
56 }
57 let size = shape.bytes.checked_add(HEADER).ok_or(Error::SchemaLimit)?;
58 let allocation = shape.heap.checked_add(size).ok_or(Error::SchemaLimit)?;
59 if size > limits.bytes
60 || allocation > limits.allocation
61 || shape.nodes > limits.nodes
62 || shape.depth > limits.depth
63 {
64 return Err(Error::SchemaLimit);
65 }
66 Ok(size)
67}
68
69pub(crate) struct Output {
72 pub(crate) bytes: Vec<u8>,
73 pub(crate) limit: usize,
74}
75impl Flavor for Output {
76 type Output = Vec<u8>;
77 fn try_push(&mut self, byte: u8) -> postcard::Result<()> {
78 if self.bytes.len() == self.limit {
79 return Err(postcard::Error::SerializeBufferFull);
80 }
81 self.bytes.push(byte);
82 Ok(())
83 }
84 fn try_extend(&mut self, bytes: &[u8]) -> postcard::Result<()> {
85 if bytes.len() > self.limit - self.bytes.len() {
86 return Err(postcard::Error::SerializeBufferFull);
87 }
88 self.bytes.extend_from_slice(bytes);
89 Ok(())
90 }
91 fn finalize(self) -> postcard::Result<Self::Output> {
92 Ok(self.bytes)
93 }
94}
95
96struct GrowingOutput<'a> {
99 output: Output,
100 allocation_failed: &'a Cell<bool>,
101}
102impl GrowingOutput<'_> {
103 #[cold]
104 #[inline(never)]
105 fn reserve(&mut self, additional: usize) -> postcard::Result<()> {
106 let bytes = &mut self.output.bytes;
107 if additional > self.output.limit - bytes.len() {
108 return Err(postcard::Error::SerializeBufferFull);
109 }
110 let required = bytes.len() + additional;
111 if required > bytes.capacity() {
112 let capacity = if required > self.output.limit / 4 {
115 self.output.limit
116 } else {
117 required
118 .max(bytes.capacity().saturating_mul(2).max(64))
119 .min(self.output.limit)
120 };
121 bytes
122 .try_reserve_exact(capacity - bytes.len())
123 .map_err(|_| {
124 self.allocation_failed.set(true);
125 postcard::Error::SerializeBufferFull
126 })?;
127 }
128 Ok(())
129 }
130}
131impl Flavor for GrowingOutput<'_> {
132 type Output = Vec<u8>;
133 #[inline(always)]
134 fn try_push(&mut self, byte: u8) -> postcard::Result<()> {
135 if self.output.bytes.len() == self.output.limit {
136 return Err(postcard::Error::SerializeBufferFull);
137 }
138 if self.output.bytes.len() == self.output.bytes.capacity() {
139 self.reserve(1)?;
140 }
141 self.output.bytes.push(byte);
142 Ok(())
143 }
144 #[inline(always)]
145 fn try_extend(&mut self, bytes: &[u8]) -> postcard::Result<()> {
146 if bytes.len() > self.output.limit - self.output.bytes.len() {
147 return Err(postcard::Error::SerializeBufferFull);
148 }
149 if bytes.len() > self.output.bytes.capacity() - self.output.bytes.len() {
150 self.reserve(bytes.len())?;
151 }
152 self.output.bytes.extend_from_slice(bytes);
153 Ok(())
154 }
155 fn finalize(self) -> postcard::Result<Self::Output> {
156 Ok(self.output.bytes)
157 }
158}
159
160struct Size {
162 bytes: usize,
163 limit: usize,
164}
165impl Flavor for Size {
166 type Output = usize;
167 fn try_push(&mut self, _: u8) -> postcard::Result<()> {
168 self.try_extend(&[0])
169 }
170 fn try_extend(&mut self, bytes: &[u8]) -> postcard::Result<()> {
171 if bytes.len() > self.limit - self.bytes {
172 return Err(postcard::Error::SerializeBufferFull);
173 }
174 self.bytes += bytes.len();
175 Ok(())
176 }
177 fn finalize(self) -> postcard::Result<usize> {
178 Ok(self.bytes)
179 }
180}
181
182fn encoded_len<T: Wire>(limits: Limits, value: &T) -> Result<usize, Error> {
183 let limit = admit::<T>(limits)?;
184 postcard::serialize_with_flavor(
185 value,
186 Size {
187 bytes: HEADER,
188 limit,
189 },
190 )
191 .map_err(|_| Error::Malformed)
192}
193
194pub(crate) struct Compare<'a> {
197 pub(crate) remaining: &'a [u8],
198 pub(crate) allowance: usize,
199 pub(crate) equal: bool,
200}
201impl Flavor for Compare<'_> {
202 type Output = bool;
203 #[inline(always)]
204 fn try_push(&mut self, byte: u8) -> postcard::Result<()> {
205 if self.allowance == 0 {
206 return Err(postcard::Error::SerializeBufferFull);
207 }
208 self.allowance -= 1;
209 if let Some((first, rest)) = self.remaining.split_first() {
210 self.equal &= *first == byte;
211 self.remaining = rest;
212 } else {
213 self.equal = false;
214 }
215 Ok(())
216 }
217 fn try_extend(&mut self, bytes: &[u8]) -> postcard::Result<()> {
218 if let [byte] = bytes {
219 return self.try_push(*byte);
220 }
221 if bytes.len() > self.allowance {
222 return Err(postcard::Error::SerializeBufferFull);
223 }
224 self.allowance -= bytes.len();
225 if let Some((prefix, rest)) = self.remaining.split_at_checked(bytes.len()) {
226 self.equal &= if core::ptr::eq(prefix.as_ptr(), bytes.as_ptr()) {
230 true
234 } else if cfg!(any(target_arch = "wasm32", test)) && bytes.len() >= 8 {
235 if bytes.len() >= 64 {
241 let (left, left_tail) = prefix.as_chunks::<32>();
242 let (right, right_tail) = bytes.as_chunks::<32>();
243 left.iter().zip(right).fold(0_u128, |difference, (a, b)| {
244 let (a0, a1) = a.split_at(16);
245 let (b0, b1) = b.split_at(16);
246 difference
247 | (u128::from_ne_bytes(a0.try_into().unwrap())
248 ^ u128::from_ne_bytes(b0.try_into().unwrap()))
249 | (u128::from_ne_bytes(a1.try_into().unwrap())
250 ^ u128::from_ne_bytes(b1.try_into().unwrap()))
251 }) == 0
252 && {
253 let (left, left_tail) = left_tail.as_chunks::<8>();
254 let (right, right_tail) = right_tail.as_chunks::<8>();
255 left.iter().zip(right).fold(0_u64, |difference, (a, b)| {
256 difference | (u64::from_ne_bytes(*a) ^ u64::from_ne_bytes(*b))
257 }) == 0
258 && left_tail == right_tail
259 }
260 } else {
261 let (left, left_tail) = prefix.as_chunks::<8>();
262 let (right, right_tail) = bytes.as_chunks::<8>();
263 left.iter().zip(right).fold(0_u64, |difference, (a, b)| {
264 difference | (u64::from_ne_bytes(*a) ^ u64::from_ne_bytes(*b))
265 }) == 0
266 && left_tail == right_tail
267 }
268 } else {
269 prefix == bytes
270 };
271 self.remaining = rest;
272 } else {
273 self.equal = false;
274 self.remaining = &[];
275 }
276 Ok(())
277 }
278 fn finalize(self) -> postcard::Result<Self::Output> {
279 Ok(self.equal && self.remaining.is_empty())
280 }
281}
282
283fn encode<T: Wire>(id: u64, direction: u8, limits: Limits, value: &T) -> Result<Vec<u8>, Error> {
284 let size = admit::<T>(limits)?;
285 let mut bytes = Vec::new();
288 bytes
289 .try_reserve_exact(if size <= 128 { size } else { 64 })
290 .map_err(|_| Error::Allocation)?;
291 bytes.extend_from_slice(&header(id, direction));
292 let allocation_failed = Cell::new(false);
293 let output = GrowingOutput {
294 output: Output { bytes, limit: size },
295 allocation_failed: &allocation_failed,
296 };
297 postcard::serialize_with_flavor(value, output).map_err(|_| {
298 if allocation_failed.get() {
299 Error::Allocation
300 } else {
301 Error::Malformed
302 }
303 })
304}
305
306fn encode_into<T: Wire>(
309 id: u64,
310 direction: u8,
311 limits: Limits,
312 value: &T,
313 bytes: &mut Vec<u8>,
314) -> Result<(), Error> {
315 bytes.clear();
316 let size = admit::<T>(limits)?;
317 bytes
320 .try_reserve_exact(size.min(64))
321 .map_err(|_| Error::Allocation)?;
322 bytes.extend_from_slice(&header(id, direction));
323 let allocation_failed = Cell::new(false);
324 let output = GrowingOutput {
325 output: Output {
326 bytes: core::mem::take(bytes),
327 limit: size,
328 },
329 allocation_failed: &allocation_failed,
330 };
331 *bytes = postcard::serialize_with_flavor(value, output).map_err(|_| {
332 if allocation_failed.get() {
333 Error::Allocation
334 } else {
335 Error::Malformed
336 }
337 })?;
338 Ok(())
339}
340
341fn decode<'de, T: Wire + serde::Deserialize<'de>>(
342 id: u64,
343 direction: u8,
344 limits: Limits,
345 bytes: &'de [u8],
346) -> Result<T, Error> {
347 let size = admit::<T>(limits)?;
348 if bytes.len() > size {
350 return Err(Error::Limit);
351 }
352 let payload = payload(id, direction, bytes)?;
353 let (value, rest) = postcard::take_from_bytes::<T>(payload).map_err(|_| Error::Malformed)?;
354 if !rest.is_empty() {
355 return Err(Error::Trailing);
356 }
357 let equal = postcard::serialize_with_flavor(
358 &value,
359 Compare {
360 remaining: payload,
361 allowance: size - HEADER,
362 equal: true,
363 },
364 )
365 .map_err(|_| Error::Malformed)?;
366 if !equal {
367 return Err(Error::Noncanonical);
368 }
369 Ok(value)
370}
371
372pub fn encode_request<M: Method>(value: &M::Request) -> Result<RequestBytes<M>, Error> {
374 Ok(RequestBytes {
375 bytes: encode(M::ID, 0, M::REQUEST_LIMITS, value)?,
376 method: PhantomData,
377 })
378}
379pub fn encode_request_into<M: Method>(
385 value: &M::Request,
386 bytes: &mut Vec<u8>,
387) -> Result<(), Error> {
388 encode_into(M::ID, 0, M::REQUEST_LIMITS, value, bytes)
389}
390
391pub fn encode_response_into<M: Method>(
396 value: &M::Response,
397 bytes: &mut Vec<u8>,
398) -> Result<(), Error> {
399 encode_into(M::ID, 1, M::RESPONSE_LIMITS, value, bytes)
400}
401
402pub fn encoded_request_len<M: Method>(value: &M::Request) -> Result<usize, Error> {
406 encoded_len(M::REQUEST_LIMITS, value)
407}
408pub fn encoded_response_len<M: Method>(value: &M::Response) -> Result<usize, Error> {
412 encoded_len(M::RESPONSE_LIMITS, value)
413}
414pub fn decode_request<'de, M: Method>(bytes: &'de [u8]) -> Result<M::Request, Error>
416where
417 M::Request: serde::Deserialize<'de>,
418{
419 decode(M::ID, 0, M::REQUEST_LIMITS, bytes)
420}
421pub fn encode_response<M: Method>(value: &M::Response) -> Result<ResponseBytes<M>, Error> {
423 Ok(ResponseBytes {
424 bytes: encode(M::ID, 1, M::RESPONSE_LIMITS, value)?,
425 method: PhantomData,
426 })
427}
428pub fn decode_response<'de, M: Method>(bytes: &'de [u8]) -> Result<M::Response, Error>
430where
431 M::Response: serde::Deserialize<'de>,
432{
433 decode(M::ID, 1, M::RESPONSE_LIMITS, bytes)
434}
435
436pub(crate) fn header(id: u64, direction: u8) -> [u8; HEADER] {
437 let mut header = [0; HEADER];
438 header[..2].copy_from_slice(b"IW");
439 header[2..10].copy_from_slice(&id.to_le_bytes());
440 header[10] = direction;
441 header
442}
443pub(crate) fn payload(id: u64, direction: u8, bytes: &[u8]) -> Result<&[u8], Error> {
444 if bytes.len() < HEADER {
445 return Err(Error::Malformed);
446 }
447 if &bytes[..2] != b"IW" || bytes[2..10] != id.to_le_bytes() || bytes[10] != direction {
448 return Err(Error::Identity);
449 }
450 Ok(&bytes[HEADER..])
451}