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 encode_to_slice<'out, 'de, T: InlineMessage<'de>>(
91 value: &T,
92 encoding: Encoding,
93 limits: Limits,
94 output: &'out mut [u8],
95) -> Result<&'out [u8], Error> {
96 super::encode_value_to_slice_with(output, encoding, limits, |mut destination| {
97 let context = destination.context();
98 super::inline::with_scratch(T::MAY_STAGE, context.budget, |scratch| {
99 let (prepared, _) = value.prepare(&context, scratch)?;
100 destination.write_value(&prepared)
101 })
102 })
103}
104
105pub fn decode<'de, T: Evolving<'de>>(
110 input: &'de [u8],
111 encoding: Encoding,
112 limits: Limits,
113) -> Result<T, Error> {
114 T::decode_evolving(input, encoding, limits)
115}
116
117pub struct Method<Request, Reply> {
122 name: &'static str,
123 id: u64,
124 request_limits: Limits,
125 reply_limits: Limits,
126 types: PhantomData<fn() -> (Request, Reply)>,
127}
128
129impl<Request, Reply> Method<Request, Reply> {
130 #[must_use]
135 pub const fn new(name: &'static str, request_limits: Limits, reply_limits: Limits) -> Self {
136 Self {
137 name,
138 id: method_id(name),
139 request_limits,
140 reply_limits,
141 types: PhantomData,
142 }
143 }
144
145 #[must_use]
147 pub const fn name(&self) -> &'static str {
148 self.name
149 }
150
151 #[must_use]
153 pub const fn id(&self) -> u64 {
154 self.id
155 }
156
157 #[must_use]
159 pub const fn request_limits(&self) -> Limits {
160 self.request_limits
161 }
162
163 #[must_use]
165 pub const fn reply_limits(&self) -> Limits {
166 self.reply_limits
167 }
168
169 pub fn encode_request<'de>(&self, value: &Request, output: &mut Vec<u8>) -> Result<(), Error>
174 where
175 Request: Evolving<'de>,
176 {
177 encode_into(
178 value,
179 self.encoding(Direction::Request),
180 self.request_limits,
181 output,
182 )
183 .map(|_| ())
184 }
185
186 pub fn decode_request<'de>(&self, input: &'de [u8]) -> Result<Request, Error>
191 where
192 Request: Evolving<'de>,
193 {
194 decode(
195 input,
196 self.encoding(Direction::Request),
197 self.request_limits,
198 )
199 }
200
201 pub fn encode_reply<'de>(&self, value: &Reply, output: &mut Vec<u8>) -> Result<(), Error>
206 where
207 Reply: Evolving<'de>,
208 {
209 encode_into(
210 value,
211 self.encoding(Direction::Response),
212 self.reply_limits,
213 output,
214 )
215 .map(|_| ())
216 }
217
218 pub fn decode_reply<'de>(&self, input: &'de [u8]) -> Result<Reply, Error>
223 where
224 Reply: Evolving<'de>,
225 {
226 decode(input, self.encoding(Direction::Response), self.reply_limits)
227 }
228
229 const fn encoding(&self, direction: Direction) -> Encoding {
230 Encoding::Frame {
231 method: self.id,
232 direction,
233 }
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240 use crate::evolution::{
241 Projected, decode_projected, encode_projected_into, encode_projected_to_slice,
242 inline::Fixed,
243 };
244 use crate::{LimitKind, TextRef};
245 use serde::{Deserialize, Serialize};
246
247 #[derive(Debug, PartialEq, Serialize, Deserialize)]
248 struct Request<'a>(#[serde(borrow)] TextRef<'a, 16>);
249
250 #[derive(Debug, PartialEq, Serialize, Deserialize)]
251 struct Reply(u16);
252
253 impl Fixed for Reply {}
254
255 impl<'de: 'a, 'a> Evolving<'de> for Request<'a> {
256 fn encode_evolving(
257 &self,
258 output: &mut Vec<u8>,
259 encoding: Encoding,
260 limits: Limits,
261 ) -> Result<(), Error> {
262 encode_projected_into(output, encoding, limits, |_| Ok(Projected::empty(self)))
263 .map(|_| ())
264 }
265
266 fn decode_evolving(
267 input: &'de [u8],
268 encoding: Encoding,
269 limits: Limits,
270 ) -> Result<Self, Error> {
271 decode_projected(
272 input,
273 encoding,
274 limits,
275 |root: Projected<'_, Self>, context| {
276 root.extensions.visit(context, |_, _| Ok(()))?;
277 Ok(root.core)
278 },
279 )
280 }
281 }
282
283 impl<'de> Evolving<'de> for Reply {
284 fn encode_evolving(
285 &self,
286 output: &mut Vec<u8>,
287 encoding: Encoding,
288 limits: Limits,
289 ) -> Result<(), Error> {
290 encode_projected_into(output, encoding, limits, |_| Ok(Projected::empty(self)))
291 .map(|_| ())
292 }
293
294 fn decode_evolving(
295 input: &'de [u8],
296 encoding: Encoding,
297 limits: Limits,
298 ) -> Result<Self, Error> {
299 decode_projected(
300 input,
301 encoding,
302 limits,
303 |root: Projected<'_, Self>, context| {
304 root.extensions.visit(context, |_, _| Ok(()))?;
305 Ok(root.core)
306 },
307 )
308 }
309 }
310
311 const REQUEST_LIMITS: Limits = Limits {
312 bytes: 64,
313 allocation: 4096,
314 nodes: 64,
315 depth: 16,
316 };
317 const REPLY_LIMITS: Limits = Limits {
318 bytes: 13,
319 ..REQUEST_LIMITS
320 };
321 const LOOKUP: Method<Request<'static>, Reply> =
322 Method::new("lookup", REQUEST_LIMITS, REPLY_LIMITS);
323
324 #[test]
325 fn typed_methods_round_trip_borrowed_requests_and_check_identity() {
326 assert_eq!(LOOKUP.name(), "lookup");
327 assert_eq!(LOOKUP.id(), method_id("lookup"));
328 assert_eq!(LOOKUP.request_limits().bytes, 64);
329 assert_eq!(LOOKUP.reply_limits().bytes, 13);
330
331 let value = alloc::string::String::from("hello");
332 let mut input = Vec::new();
333 let method: Method<Request<'_>, Reply> = LOOKUP;
334 method
335 .encode_request(&Request(TextRef::new(&value).unwrap()), &mut input)
336 .unwrap();
337 let decoded = method.decode_request(&input).unwrap();
338 assert_eq!(decoded.0.as_str(), "hello");
339 assert_eq!(decoded.0.as_str().as_bytes().as_ptr(), input[12..].as_ptr());
340
341 let other = Method::<Request<'_>, Reply>::new("other", REQUEST_LIMITS, REPLY_LIMITS);
342 assert_eq!(other.decode_request(&input), Err(Error::Identity));
343 let mut reply = Vec::new();
344 method.encode_reply(&Reply(7), &mut reply).unwrap();
345 assert_eq!(reply[10..], [1, 7, 0]);
346 assert_eq!(method.decode_reply(&reply), Ok(Reply(7)));
347 assert_eq!(method.decode_request(&reply), Err(Error::Identity));
348 }
349
350 #[test]
351 fn reply_limits_apply_to_both_encoding_and_decoding() {
352 let mut reply = alloc::vec![1, 2, 3];
353 assert_eq!(
354 LOOKUP.encode_reply(&Reply(128), &mut reply),
355 Err(Error::Limit(LimitKind::Bytes))
356 );
357 assert!(reply.is_empty());
358 let large = encode(
359 &Reply(128),
360 Encoding::Frame {
361 method: LOOKUP.id(),
362 direction: Direction::Response,
363 },
364 REQUEST_LIMITS,
365 )
366 .unwrap();
367 assert_eq!(
368 LOOKUP.decode_reply(&large),
369 Err(Error::Limit(LimitKind::Bytes))
370 );
371 }
372
373 #[test]
374 fn fixed_nested_reply_uses_its_explicit_projection_at_the_root() {
375 let value = Reply(42);
376 let encoding = Encoding::Payload;
377 let owned = encode(&value, encoding, REPLY_LIMITS).unwrap();
378 let mut output = [0; 2];
379 let slice = encode_projected_to_slice(&mut output, encoding, REPLY_LIMITS, |_| {
380 Ok(Projected::empty(&value))
381 })
382 .unwrap();
383 assert_eq!(slice, [42, 0]);
384 assert_eq!(slice, owned);
385 assert_eq!(decode::<Reply>(slice, encoding, REPLY_LIMITS), Ok(value));
386 }
387}