1use crate::{Direction, Encoding, Error, Limits, method_id};
4use alloc::vec::Vec;
5use core::marker::PhantomData;
6
7use super::inline::InlineMessage;
8
9pub trait Evolving<'de>: Sized {
14 fn encode_evolving(
19 &self,
20 output: &mut Vec<u8>,
21 encoding: Encoding,
22 limits: Limits,
23 ) -> Result<(), Error>;
24
25 fn decode_evolving(input: &'de [u8], encoding: Encoding, limits: Limits)
30 -> Result<Self, Error>;
31}
32
33pub fn encode<'de, T: Evolving<'de>>(
38 value: &T,
39 encoding: Encoding,
40 limits: Limits,
41) -> Result<Vec<u8>, Error> {
42 let mut output = Vec::new();
43 encode_into(value, encoding, limits, &mut output)?;
44 Ok(output)
45}
46
47pub fn encode_into<'out, 'de, T: Evolving<'de>>(
53 value: &T,
54 encoding: Encoding,
55 limits: Limits,
56 output: &'out mut Vec<u8>,
57) -> Result<&'out [u8], Error> {
58 output.clear();
59 if let Err(error) = value.encode_evolving(output, encoding, limits) {
60 output.clear();
61 return Err(error);
62 }
63 Ok(output)
64}
65
66pub fn encoded_len<'de, T: InlineMessage<'de>>(
71 value: &T,
72 encoding: Encoding,
73 limits: Limits,
74) -> Result<usize, Error> {
75 let prefix = super::writer::frame_header(encoding).map_or(0, |_| crate::framing::HEADER_BYTES);
76 let limits = limits.without_prefix(prefix)?;
77 let budget = crate::meter::Budget::new(limits);
78 budget.check()?;
79 let context = super::WriteContext {
80 budget: &budget,
81 depth: 1,
82 byte_limit: limits.bytes,
83 };
84 let mut length = 0;
85 super::inline::with_scratch(T::MAY_STAGE, &budget, |scratch| {
86 let (prepared, _) = value.prepare(&context, scratch)?;
87 budget.check()?;
88 length = super::writer::projected_size(&prepared, &budget, limits.bytes)?;
89 Ok(())
90 })?;
91 budget.check()?;
92 Ok(length + prefix)
93}
94
95pub fn encode_to_slice<'out, 'de, T: InlineMessage<'de>>(
120 value: &T,
121 encoding: Encoding,
122 limits: Limits,
123 output: &'out mut [u8],
124) -> Result<&'out [u8], Error> {
125 super::encode_value_to_slice_with(output, encoding, limits, |mut destination| {
126 let context = destination.context();
127 super::inline::with_scratch(T::MAY_STAGE, context.budget, |scratch| {
128 let (prepared, _) = value.prepare(&context, scratch)?;
129 destination.write_value(&prepared)
130 })
131 })
132}
133
134pub fn decode<'de, T: Evolving<'de>>(
139 input: &'de [u8],
140 encoding: Encoding,
141 limits: Limits,
142) -> Result<T, Error> {
143 T::decode_evolving(input, encoding, limits)
144}
145
146pub struct Method<Request, Reply> {
151 name: &'static str,
152 id: u64,
153 request_limits: Limits,
154 reply_limits: Limits,
155 types: PhantomData<fn() -> (Request, Reply)>,
156}
157
158impl<Request, Reply> Method<Request, Reply> {
159 #[must_use]
164 pub const fn new(name: &'static str, request_limits: Limits, reply_limits: Limits) -> Self {
165 Self {
166 name,
167 id: method_id(name),
168 request_limits,
169 reply_limits,
170 types: PhantomData,
171 }
172 }
173
174 #[must_use]
176 pub const fn name(&self) -> &'static str {
177 self.name
178 }
179
180 #[must_use]
182 pub const fn id(&self) -> u64 {
183 self.id
184 }
185
186 #[must_use]
188 pub const fn request_limits(&self) -> Limits {
189 self.request_limits
190 }
191
192 #[must_use]
194 pub const fn reply_limits(&self) -> Limits {
195 self.reply_limits
196 }
197
198 pub fn encode_request<'de>(&self, value: &Request, output: &mut Vec<u8>) -> Result<(), Error>
203 where
204 Request: Evolving<'de>,
205 {
206 encode_into(
207 value,
208 self.encoding(Direction::Request),
209 self.request_limits,
210 output,
211 )
212 .map(|_| ())
213 }
214
215 pub fn decode_request<'de>(&self, input: &'de [u8]) -> Result<Request, Error>
220 where
221 Request: Evolving<'de>,
222 {
223 decode(
224 input,
225 self.encoding(Direction::Request),
226 self.request_limits,
227 )
228 }
229
230 pub fn encode_reply<'de>(&self, value: &Reply, output: &mut Vec<u8>) -> Result<(), Error>
235 where
236 Reply: Evolving<'de>,
237 {
238 encode_into(
239 value,
240 self.encoding(Direction::Response),
241 self.reply_limits,
242 output,
243 )
244 .map(|_| ())
245 }
246
247 pub fn decode_reply<'de>(&self, input: &'de [u8]) -> Result<Reply, Error>
252 where
253 Reply: Evolving<'de>,
254 {
255 decode(input, self.encoding(Direction::Response), self.reply_limits)
256 }
257
258 const fn encoding(&self, direction: Direction) -> Encoding {
259 Encoding::Frame {
260 method: self.id,
261 direction,
262 }
263 }
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269 use crate::evolution::{
270 Projected, decode_projected, encode_projected_into, encode_projected_to_slice,
271 inline::Fixed,
272 };
273 use crate::{LimitKind, TextRef};
274 use serde::{Deserialize, Serialize};
275
276 #[derive(Debug, PartialEq, Serialize, Deserialize)]
277 struct Request<'a>(#[serde(borrow)] TextRef<'a, 16>);
278
279 #[derive(Debug, PartialEq, Serialize, Deserialize)]
280 struct Reply(u16);
281
282 impl Fixed for Reply {}
283
284 impl<'de: 'a, 'a> Evolving<'de> for Request<'a> {
285 fn encode_evolving(
286 &self,
287 output: &mut Vec<u8>,
288 encoding: Encoding,
289 limits: Limits,
290 ) -> Result<(), Error> {
291 encode_projected_into(output, encoding, limits, |_| Ok(Projected::empty(self)))
292 .map(|_| ())
293 }
294
295 fn decode_evolving(
296 input: &'de [u8],
297 encoding: Encoding,
298 limits: Limits,
299 ) -> Result<Self, Error> {
300 decode_projected(
301 input,
302 encoding,
303 limits,
304 |root: Projected<'_, Self>, context| {
305 root.extensions.visit(context, |_, _| Ok(()))?;
306 Ok(root.core)
307 },
308 )
309 }
310 }
311
312 impl<'de> Evolving<'de> for Reply {
313 fn encode_evolving(
314 &self,
315 output: &mut Vec<u8>,
316 encoding: Encoding,
317 limits: Limits,
318 ) -> Result<(), Error> {
319 encode_projected_into(output, encoding, limits, |_| Ok(Projected::empty(self)))
320 .map(|_| ())
321 }
322
323 fn decode_evolving(
324 input: &'de [u8],
325 encoding: Encoding,
326 limits: Limits,
327 ) -> Result<Self, Error> {
328 decode_projected(
329 input,
330 encoding,
331 limits,
332 |root: Projected<'_, Self>, context| {
333 root.extensions.visit(context, |_, _| Ok(()))?;
334 Ok(root.core)
335 },
336 )
337 }
338 }
339
340 const REQUEST_LIMITS: Limits = Limits {
341 bytes: 64,
342 allocation: 4096,
343 nodes: 64,
344 depth: 16,
345 };
346 const REPLY_LIMITS: Limits = Limits {
347 bytes: 13,
348 ..REQUEST_LIMITS
349 };
350 const LOOKUP: Method<Request<'static>, Reply> =
351 Method::new("lookup", REQUEST_LIMITS, REPLY_LIMITS);
352
353 #[test]
354 fn typed_methods_round_trip_borrowed_requests_and_check_identity() {
355 assert_eq!(LOOKUP.name(), "lookup");
356 assert_eq!(LOOKUP.id(), method_id("lookup"));
357 assert_eq!(LOOKUP.request_limits().bytes, 64);
358 assert_eq!(LOOKUP.reply_limits().bytes, 13);
359
360 let value = alloc::string::String::from("hello");
361 let mut input = Vec::new();
362 let method: Method<Request<'_>, Reply> = LOOKUP;
363 method
364 .encode_request(&Request(TextRef::new(&value).unwrap()), &mut input)
365 .unwrap();
366 let decoded = method.decode_request(&input).unwrap();
367 assert_eq!(decoded.0.as_str(), "hello");
368 assert_eq!(decoded.0.as_str().as_bytes().as_ptr(), input[12..].as_ptr());
369
370 let other = Method::<Request<'_>, Reply>::new("other", REQUEST_LIMITS, REPLY_LIMITS);
371 assert_eq!(other.decode_request(&input), Err(Error::Identity));
372 let mut reply = Vec::new();
373 method.encode_reply(&Reply(7), &mut reply).unwrap();
374 assert_eq!(reply[10..], [1, 7, 0]);
375 assert_eq!(method.decode_reply(&reply), Ok(Reply(7)));
376 assert_eq!(method.decode_request(&reply), Err(Error::Identity));
377 }
378
379 #[test]
380 fn reply_limits_apply_to_both_encoding_and_decoding() {
381 let mut reply = alloc::vec![1, 2, 3];
382 assert_eq!(
383 LOOKUP.encode_reply(&Reply(128), &mut reply),
384 Err(Error::Limit(LimitKind::Bytes))
385 );
386 assert!(reply.is_empty());
387 let large = encode(
388 &Reply(128),
389 Encoding::Frame {
390 method: LOOKUP.id(),
391 direction: Direction::Response,
392 },
393 REQUEST_LIMITS,
394 )
395 .unwrap();
396 assert_eq!(
397 LOOKUP.decode_reply(&large),
398 Err(Error::Limit(LimitKind::Bytes))
399 );
400 }
401
402 #[test]
403 fn fixed_nested_reply_uses_its_explicit_projection_at_the_root() {
404 let value = Reply(42);
405 let encoding = Encoding::Payload;
406 let owned = encode(&value, encoding, REPLY_LIMITS).unwrap();
407 let mut output = [0; 2];
408 let slice = encode_projected_to_slice(&mut output, encoding, REPLY_LIMITS, |_| {
409 Ok(Projected::empty(&value))
410 })
411 .unwrap();
412 assert_eq!(slice, [42, 0]);
413 assert_eq!(slice, owned);
414 assert_eq!(decode::<Reply>(slice, encoding, REPLY_LIMITS), Ok(value));
415 }
416}