bilrost/
message.rs

1use crate::buf::{ReverseBuf, ReverseBuffer};
2use crate::encoding::message::{
3    borrow_merge, borrow_merge_distinguished, merge, merge_distinguished,
4};
5use crate::encoding::{
6    encode_varint, encoded_len_varint, prepend_varint, Capped, DecodeContext,
7    RawDistinguishedMessageBorrowDecoder, RawDistinguishedMessageDecoder, RawMessage,
8    RawMessageBorrowDecoder, RawMessageDecoder, RestrictedDecodeContext,
9};
10use crate::Canonicity::{Canonical, NotCanonical};
11use crate::{length_delimiter_len, Canonicity, DecodeError, EncodeError};
12use alloc::vec::Vec;
13use bytes::{Buf, BufMut, Bytes, BytesMut};
14
15/// A Bilrost message. Provides basic encoding functionality for message types.
16pub trait Message {
17    /// Creates a new message with an empty state.
18    fn new_empty() -> Self
19    where
20        Self: Sized;
21
22    /// Encodes the message to a buffer.
23    ///
24    /// An error will be returned if the buffer does not have sufficient capacity.
25    fn encode<B: BufMut + ?Sized>(&self, buf: &mut B) -> Result<(), EncodeError>
26    where
27        Self: Sized;
28
29    /// Prepends the message to a buffer.
30    fn prepend<B: ReverseBuf + ?Sized>(&self, buf: &mut B)
31    where
32        Self: Sized;
33
34    /// Encodes the message with a length-delimiter to a buffer.
35    ///
36    /// An error will be returned if the buffer does not have sufficient capacity.
37    fn encode_length_delimited<B: BufMut + ?Sized>(&self, buf: &mut B) -> Result<(), EncodeError>
38    where
39        Self: Sized;
40
41    // ------------ Dyn-compatible methods follow ------------
42
43    /// Returns whether the message is currently in an empty state.
44    fn message_is_empty(&self) -> bool;
45
46    /// Resets the message to an empty state.
47    fn clear_message(&mut self);
48
49    /// Returns the encoded length of the message without a length delimiter.
50    fn encoded_len(&self) -> usize;
51
52    /// Encodes the message to a newly allocated buffer.
53    fn encode_to_vec(&self) -> Vec<u8>;
54
55    /// Encodes the message to a `Bytes` buffer.
56    fn encode_to_bytes(&self) -> Bytes;
57
58    /// Encodes the message to a `ReverseBuffer`.
59    fn encode_fast(&self) -> ReverseBuffer;
60
61    /// Encodes the message with a length-delimiter to a `ReverseBuffer`.
62    fn encode_length_delimited_fast(&self) -> ReverseBuffer;
63
64    /// Encodes the message to a new `RevserseBuffer` which will have exactly the required capacity
65    /// in one contiguous slice.
66    fn encode_contiguous(&self) -> ReverseBuffer;
67
68    /// Encodes the message with a length-delimiter to a new `RevserseBuffer` which will have
69    /// exactly the required capacity in one contiguous slice.
70    fn encode_length_delimited_contiguous(&self) -> ReverseBuffer;
71
72    /// Encodes the message to a `Bytes` buffer.
73    fn encode_dyn(&self, buf: &mut dyn BufMut) -> Result<(), EncodeError>;
74
75    /// Encodes the message with a length-delimiter to a newly allocated buffer.
76    fn encode_length_delimited_to_vec(&self) -> Vec<u8>;
77
78    /// Encodes the message with a length-delimiter to a `Bytes` buffer.
79    fn encode_length_delimited_to_bytes(&self) -> Bytes;
80
81    /// Encodes the message with a length-delimiter to a `Bytes` buffer.
82    fn encode_length_delimited_dyn(&self, buf: &mut dyn BufMut) -> Result<(), EncodeError>;
83}
84
85/// Basic decoding functionality for a Bilrost message that can decode to an owned form. This
86/// trait's decoding methods can decode from any byte buffer that implements `bytes::Buf`.
87pub trait OwnedMessage: Message {
88    /// Decodes an instance of the message from a buffer.
89    ///
90    /// The entire buffer will be consumed.
91    fn decode<B: Buf>(buf: B) -> Result<Self, DecodeError>
92    where
93        Self: Sized;
94
95    /// Decodes a length-delimited instance of the message from the buffer.
96    fn decode_length_delimited<B: Buf>(buf: B) -> Result<Self, DecodeError>
97    where
98        Self: Sized;
99
100    /// Decodes an instance from the given `Capped` buffer, consuming it to its cap.
101    #[doc(hidden)]
102    fn decode_capped<B: Buf + ?Sized>(buf: Capped<B>) -> Result<Self, DecodeError>
103    where
104        Self: Sized;
105
106    /// Decodes the non-ignored fields of this message from the buffer, replacing their values.
107    fn replace_from<B: Buf>(&mut self, buf: B) -> Result<(), DecodeError>
108    where
109        Self: Sized;
110
111    /// Decodes the non-ignored fields of this message, replacing their values from a
112    /// length-delimited value encoded in the buffer.
113    fn replace_from_length_delimited<B: Buf>(&mut self, buf: B) -> Result<(), DecodeError>
114    where
115        Self: Sized;
116
117    /// Decodes the non-ignored fields of this message, replacing their values from the given capped
118    /// buffer.
119    #[doc(hidden)]
120    fn replace_from_capped<B: Buf + ?Sized>(&mut self, buf: Capped<B>) -> Result<(), DecodeError>
121    where
122        Self: Sized;
123
124    // ------------ Dyn-compatible methods follow ------------
125
126    /// Decodes the non-ignored fields of this message from the buffer, replacing their values.
127    fn replace_from_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError>;
128
129    /// Decodes the non-ignored fields of this message, replacing their values from a
130    /// length-delimited value encoded in the buffer.
131    fn replace_from_length_delimited_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError>;
132
133    /// Decodes the non-ignored fields of this message from the buffer, replacing their values.
134    fn replace_from_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError>;
135
136    /// Decodes the non-ignored fields of this message, replacing their values from a
137    /// length-delimited value encoded in the buffer.
138    fn replace_from_length_delimited_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError>;
139
140    /// Decodes the non-ignored fields of this message, replacing their values from the given capped
141    /// buffer.
142    #[doc(hidden)]
143    fn replace_from_capped_dyn(&mut self, buf: Capped<dyn Buf>) -> Result<(), DecodeError>;
144}
145
146/// An enhanced trait for owned Bilrost messages that promise a distinguished representation.
147///
148/// Implementation of this trait comes with the following promises:
149///
150///  1. The message will always encode to the same bytes as any other message with an equal value.
151///  2. A message equal to that value will only ever decode canonically and without error from that
152///     exact sequence of bytes, not from any other.
153///
154/// Distinguished decoding methods come in three flavors:
155/// * "distinguished" methods, which decode anything that relaxed decoding will and return the
156///   value along with a `Canonicity`
157/// * "restricted" methods, which also require a minimum `Canonicity` and will early-exit decoding
158///   and return an appropriate error if the canonicity violates that constraint:
159///     * restrict to `Canonical` will return an error any time the encoding is not fully canonical
160///     * restrict to `HasExtensions` will return an error any time the encoding has known fields
161///       with non-canonical representations, but will not fail when unknown fields are present
162///     * passing `NotCanonical` gives exactly the same result as using the distinguished decoding
163///       methods
164/// * "canonical" methods, which are shorthand for "restricted" methods with `Canonical` constraint
165///   and do not return the `Canonicity`, because it will always be fully `Canonical`.
166///
167/// Note that currently the only restriction level that is sensible to *explicitly* pass to
168/// "restricted" methods is `HasExtensions`: "distinguished" methods already dispatch to passing
169/// `NotCanonical`, and when `Canonical` is passed only `Canonical` can be returned from a
170/// successful result (hence the "canonical" methods). It can of course make sense to call these
171/// methods with a varying restriction level.
172pub trait DistinguishedOwnedMessage: OwnedMessage {
173    // ------------ Distinguished mode ------------
174
175    /// Decodes an instance of the message from a buffer in distinguished mode.
176    ///
177    /// The entire buffer will be consumed.
178    fn decode_distinguished<B: Buf>(buf: B) -> Result<(Self, Canonicity), DecodeError>
179    where
180        Self: Sized;
181
182    /// Decodes a length-delimited instance of the message from the buffer in distinguished mode.
183    fn decode_distinguished_length_delimited<B: Buf>(
184        buf: B,
185    ) -> Result<(Self, Canonicity), DecodeError>
186    where
187        Self: Sized;
188
189    /// Decodes an instance from the given `Capped` buffer in distinguished mode, consuming it to
190    /// its cap.
191    #[doc(hidden)]
192    fn decode_distinguished_capped<B: Buf + ?Sized>(
193        buf: Capped<B>,
194    ) -> Result<(Self, Canonicity), DecodeError>
195    where
196        Self: Sized;
197
198    /// Decodes the non-ignored fields of this message from the buffer in distinguished mode,
199    /// replacing their values.
200    fn replace_distinguished_from<B: Buf>(&mut self, buf: B) -> Result<Canonicity, DecodeError>
201    where
202        Self: Sized;
203
204    /// Decodes the non-ignored fields of this message in distinguished mode, replacing their values
205    /// from a length-delimited value encoded in the buffer.
206    fn replace_distinguished_from_length_delimited<B: Buf>(
207        &mut self,
208        buf: B,
209    ) -> Result<Canonicity, DecodeError>
210    where
211        Self: Sized;
212
213    /// Decodes the non-ignored fields of this message in distinguished mode, replacing their values
214    /// from the given capped buffer.
215    #[doc(hidden)]
216    fn replace_distinguished_from_capped<B: Buf + ?Sized>(
217        &mut self,
218        buf: Capped<B>,
219    ) -> Result<Canonicity, DecodeError>
220    where
221        Self: Sized;
222
223    // ------------ Dyn-compatible methods follow ------------
224
225    /// Decodes a length-delimited instance of the message from the buffer in distinguished mode.
226    fn replace_distinguished_from_slice(&mut self, buf: &[u8]) -> Result<Canonicity, DecodeError>;
227
228    /// Decodes the non-ignored fields of this message, replacing their values from a
229    /// length-delimited value encoded in the buffer in distinguished mode.
230    fn replace_distinguished_from_dyn(
231        &mut self,
232        buf: &mut dyn Buf,
233    ) -> Result<Canonicity, DecodeError>;
234
235    /// Decodes the non-ignored fields of this message from the buffer in distinguished mode,
236    /// replacing their values.
237    fn replace_distinguished_from_length_delimited_slice(
238        &mut self,
239        buf: &[u8],
240    ) -> Result<Canonicity, DecodeError>;
241
242    /// Decodes the non-ignored fields of this message, replacing their values from a
243    /// length-delimited value encoded in the buffer in distinguished mode.
244    fn replace_distinguished_from_length_delimited_dyn(
245        &mut self,
246        buf: &mut dyn Buf,
247    ) -> Result<Canonicity, DecodeError>;
248
249    /// Decodes the non-ignored fields of this message, replacing their values from the given capped
250    /// buffer in distinguished mode.
251    #[doc(hidden)]
252    fn replace_distinguished_from_capped_dyn(
253        &mut self,
254        buf: Capped<dyn Buf>,
255    ) -> Result<Canonicity, DecodeError>;
256
257    // ------------ Restricted mode ------------
258
259    /// Decodes an instance of the message from a buffer in restricted mode.
260    ///
261    /// The entire buffer will be consumed.
262    fn decode_restricted<B: Buf>(
263        buf: B,
264        restrict_to: Canonicity,
265    ) -> Result<(Self, Canonicity), DecodeError>
266    where
267        Self: Sized;
268
269    /// Decodes a length-delimited instance of the message from the buffer in restricted mode.
270    fn decode_restricted_length_delimited<B: Buf>(
271        buf: B,
272        restrict_to: Canonicity,
273    ) -> Result<(Self, Canonicity), DecodeError>
274    where
275        Self: Sized;
276
277    /// Decodes an instance from the given `Capped` buffer in restricted mode, consuming it to
278    /// its cap.
279    #[doc(hidden)]
280    fn decode_restricted_capped<B: Buf + ?Sized>(
281        buf: Capped<B>,
282        restrict_to: Canonicity,
283    ) -> Result<(Self, Canonicity), DecodeError>
284    where
285        Self: Sized;
286
287    /// Decodes the non-ignored fields of this message from the buffer in restricted mode,
288    /// replacing their values.
289    fn replace_restricted_from<B: Buf>(
290        &mut self,
291        buf: B,
292        restrict_to: Canonicity,
293    ) -> Result<Canonicity, DecodeError>
294    where
295        Self: Sized;
296
297    /// Decodes the non-ignored fields of this message in restricted mode, replacing their values
298    /// from a length-delimited value encoded in the buffer.
299    fn replace_restricted_from_length_delimited<B: Buf>(
300        &mut self,
301        buf: B,
302        restrict_to: Canonicity,
303    ) -> Result<Canonicity, DecodeError>
304    where
305        Self: Sized;
306
307    /// Decodes the non-ignored fields of this message in restricted mode, replacing their values
308    /// from the given capped buffer.
309    #[doc(hidden)]
310    fn replace_restricted_from_capped<B: Buf + ?Sized>(
311        &mut self,
312        buf: Capped<B>,
313        restrict_to: Canonicity,
314    ) -> Result<Canonicity, DecodeError>
315    where
316        Self: Sized;
317
318    // ------------ Dyn-compatible methods follow ------------
319
320    /// Decodes a length-delimited instance of the message from the buffer in restricted mode.
321    fn replace_restricted_from_slice(
322        &mut self,
323        buf: &[u8],
324        restrict_to: Canonicity,
325    ) -> Result<Canonicity, DecodeError>;
326
327    /// Decodes the non-ignored fields of this message, replacing their values from a
328    /// length-delimited value encoded in the buffer in restricted mode.
329    fn replace_restricted_from_dyn(
330        &mut self,
331        buf: &mut dyn Buf,
332        restrict_to: Canonicity,
333    ) -> Result<Canonicity, DecodeError>;
334
335    /// Decodes the non-ignored fields of this message from the buffer in restricted mode,
336    /// replacing their values.
337    fn replace_restricted_from_length_delimited_slice(
338        &mut self,
339        buf: &[u8],
340        restrict_to: Canonicity,
341    ) -> Result<Canonicity, DecodeError>;
342
343    /// Decodes the non-ignored fields of this message, replacing their values from a
344    /// length-delimited value encoded in the buffer in restricted mode.
345    fn replace_restricted_from_length_delimited_dyn(
346        &mut self,
347        buf: &mut dyn Buf,
348        restrict_to: Canonicity,
349    ) -> Result<Canonicity, DecodeError>;
350
351    /// Decodes the non-ignored fields of this message, replacing their values from the given capped
352    /// buffer in restricted mode.
353    #[doc(hidden)]
354    fn replace_restricted_from_capped_dyn(
355        &mut self,
356        buf: Capped<dyn Buf>,
357        restrict_to: Canonicity,
358    ) -> Result<Canonicity, DecodeError>;
359
360    // ------------ Canonical mode ------------
361
362    /// Decodes an instance of the message from a buffer in canonical mode.
363    ///
364    /// The entire buffer will be consumed.
365    fn decode_canonical<B: Buf>(buf: B) -> Result<Self, DecodeError>
366    where
367        Self: Sized;
368
369    /// Decodes a length-delimited instance of the message from the buffer in canonical mode.
370    fn decode_canonical_length_delimited<B: Buf>(buf: B) -> Result<Self, DecodeError>
371    where
372        Self: Sized;
373
374    /// Decodes an instance from the given `Capped` buffer in canonical mode, consuming it to
375    /// its cap.
376    #[doc(hidden)]
377    fn decode_canonical_capped<B: Buf + ?Sized>(buf: Capped<B>) -> Result<Self, DecodeError>
378    where
379        Self: Sized;
380
381    /// Decodes the non-ignored fields of this message from the buffer in canonical mode,
382    /// replacing their values.
383    fn replace_canonical_from<B: Buf>(&mut self, buf: B) -> Result<(), DecodeError>
384    where
385        Self: Sized;
386
387    /// Decodes the non-ignored fields of this message in canonical mode, replacing their values
388    /// from a length-delimited value encoded in the buffer.
389    fn replace_canonical_from_length_delimited<B: Buf>(
390        &mut self,
391        buf: B,
392    ) -> Result<(), DecodeError>
393    where
394        Self: Sized;
395
396    /// Decodes the non-ignored fields of this message in canonical mode, replacing their values
397    /// from the given capped buffer.
398    #[doc(hidden)]
399    fn replace_canonical_from_capped<B: Buf + ?Sized>(
400        &mut self,
401        buf: Capped<B>,
402    ) -> Result<(), DecodeError>
403    where
404        Self: Sized;
405
406    // ------------ Dyn-compatible methods follow ------------
407
408    /// Decodes a length-delimited instance of the message from the buffer in canonical mode.
409    fn replace_canonical_from_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError>;
410
411    /// Decodes the non-ignored fields of this message, replacing their values from a
412    /// length-delimited value encoded in the buffer in canonical mode.
413    fn replace_canonical_from_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError>;
414
415    /// Decodes the non-ignored fields of this message from the buffer in canonical mode,
416    /// replacing their values.
417    fn replace_canonical_from_length_delimited_slice(
418        &mut self,
419        buf: &[u8],
420    ) -> Result<(), DecodeError>;
421
422    /// Decodes the non-ignored fields of this message, replacing their values from a
423    /// length-delimited value encoded in the buffer in canonical mode.
424    fn replace_canonical_from_length_delimited_dyn(
425        &mut self,
426        buf: &mut dyn Buf,
427    ) -> Result<(), DecodeError>;
428
429    /// Decodes the non-ignored fields of this message, replacing their values from the given capped
430    /// buffer in canonical mode.
431    #[doc(hidden)]
432    fn replace_canonical_from_capped_dyn(
433        &mut self,
434        buf: Capped<dyn Buf>,
435    ) -> Result<(), DecodeError>;
436}
437
438/// Basic decoding functionality for a Bilrost message that can decode from a borrowed slice.
439pub trait BorrowedMessage<'a>: Message {
440    /// Decodes an instance of the message from a buffer.
441    ///
442    /// The entire buffer will be consumed.
443    fn decode_borrowed(buf: &'a [u8]) -> Result<Self, DecodeError>
444    where
445        Self: Sized;
446
447    /// Decodes a length-delimited instance of the message from the buffer.
448    ///
449    /// * If the message decodes successfully, the provided slice will be shortened to no longer
450    ///   include the bytes that encoded it or its length delimiter.
451    /// * If the message is correctly delimited within the bounds of the slice but fails to decode,
452    ///   the provided slice will still be shortened even though an error is returned.
453    /// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
454    ///   itself is truncated, an error with Truncated kind is returned and it is unspecified how
455    ///   the provided slice value is modified.
456    fn decode_borrowed_length_delimited(buf: &mut &'a [u8]) -> Result<Self, DecodeError>
457    where
458        Self: Sized;
459
460    // ------------ Dyn-compatible methods follow ------------
461
462    /// Decodes the non-ignored fields of this message from the buffer, replacing their values.
463    fn replace_borrowed_from(&mut self, buf: &'a [u8]) -> Result<(), DecodeError>;
464
465    /// Decodes the non-ignored fields of this message, replacing their values from a
466    /// length-delimited value encoded in the buffer.
467    ///
468    /// * If the message decodes successfully, the provided slice will be shortened to no longer
469    ///   include the bytes that encoded it or its length delimiter.
470    /// * If the message is correctly delimited within the bounds of the slice but fails to decode,
471    ///   the provided slice will still be shortened even though an error is returned.
472    /// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
473    ///   itself is truncated, an error with Truncated kind is returned and it is unspecified how
474    ///   the provided slice value is modified.
475    fn replace_borrowed_from_length_delimited(
476        &mut self,
477        buf: &mut &'a [u8],
478    ) -> Result<(), DecodeError>;
479}
480
481/// An enhanced trait for borrowed Bilrost messages that promise a distinguished representation.
482///
483/// Implementation of this trait comes with the following promises:
484///
485///  1. The message will always encode to the same bytes as any other message with an equal value.
486///  2. A message equal to that value will only ever decode canonically and without error from that
487///     exact sequence of bytes, not from any other.
488///
489/// Distinguished decoding methods come in three flavors:
490/// * "distinguished" methods, which decode anything that relaxed decoding will and return the
491///   value along with a `Canonicity`
492/// * "restricted" methods, which also require a minimum `Canonicity` and will early-exit decoding
493///   and return an appropriate error if the canonicity violates that constraint:
494///     * restrict to `Canonical` will return an error any time the encoding is not fully canonical
495///     * restrict to `HasExtensions` will return an error any time the encoding has known fields
496///       with non-canonical representations, but will not fail when unknown fields are present
497///     * passing `NotCanonical` gives exactly the same result as using the distinguished decoding
498///       methods
499/// * "canonical" methods, which are shorthand for "restricted" methods with `Canonical` constraint
500///   and do not return the `Canonicity`, because it will always be fully `Canonical`.
501///
502/// Note that currently the only restriction level that is sensible to *explicitly* pass to
503/// "restricted" methods is `HasExtensions`: "distinguished" methods already dispatch to passing
504/// `NotCanonical`, and when `Canonical` is passed only `Canonical` can be returned from a
505/// successful result (hence the "canonical" methods). It can of course make sense to call these
506/// methods with a varying restriction level.
507pub trait DistinguishedBorrowedMessage<'a>: BorrowedMessage<'a> {
508    // ------------ Distinguished mode ------------
509
510    /// Decodes an instance of the message from a buffer in distinguished mode.
511    ///
512    /// The entire buffer will be consumed.
513    fn decode_distinguished_borrowed(buf: &'a [u8]) -> Result<(Self, Canonicity), DecodeError>
514    where
515        Self: Sized;
516
517    /// Decodes a length-delimited instance of the message from the buffer in distinguished mode.
518    ///
519    /// * If the message decodes successfully, the provided slice will be shortened to no longer
520    ///   include the bytes that encoded it or its length delimiter.
521    /// * If the message is correctly delimited within the bounds of the slice but fails to decode,
522    ///   the provided slice will still be shortened even though an error is returned.
523    /// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
524    ///   itself is truncated, an error with Truncated kind is returned and it is unspecified how
525    ///   the provided slice value is modified.
526    fn decode_distinguished_borrowed_length_delimited(
527        buf: &mut &'a [u8],
528    ) -> Result<(Self, Canonicity), DecodeError>
529    where
530        Self: Sized;
531
532    // ------------ Dyn-compatible methods follow ------------
533
534    /// Decodes the non-ignored fields of this message from the buffer in distinguished mode,
535    /// replacing their values.
536    fn replace_distinguished_borrowed_from(
537        &mut self,
538        buf: &'a [u8],
539    ) -> Result<Canonicity, DecodeError>;
540
541    /// Decodes the non-ignored fields of this message in distinguished mode, replacing their values
542    /// from a length-delimited value encoded in the buffer.
543    ///
544    /// * If the message decodes successfully, the provided slice will be shortened to no longer
545    ///   include the bytes that encoded it or its length delimiter.
546    /// * If the message is correctly delimited within the bounds of the slice but fails to decode,
547    ///   the provided slice will still be shortened even though an error is returned.
548    /// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
549    ///   itself is truncated, an error with Truncated kind is returned and it is unspecified how
550    ///   the provided slice value is modified.
551    fn replace_distinguished_borrowed_from_length_delimited(
552        &mut self,
553        buf: &mut &'a [u8],
554    ) -> Result<Canonicity, DecodeError>;
555
556    // ------------ Restricted mode ------------
557
558    /// Decodes an instance of the message from a buffer in restricted mode.
559    ///
560    /// The entire buffer will be consumed.
561    fn decode_restricted_borrowed(
562        buf: &'a [u8],
563        restrict_to: Canonicity,
564    ) -> Result<(Self, Canonicity), DecodeError>
565    where
566        Self: Sized;
567
568    /// Decodes a length-delimited instance of the message from the buffer in restricted mode.
569    ///
570    /// * If the message decodes successfully, the provided slice will be shortened to no longer
571    ///   include the bytes that encoded it or its length delimiter.
572    /// * If the message is correctly delimited within the bounds of the slice but fails to decode,
573    ///   the provided slice will still be shortened even though an error is returned.
574    /// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
575    ///   itself is truncated, an error with Truncated kind is returned and it is unspecified how
576    ///   the provided slice value is modified.
577    fn decode_restricted_borrowed_length_delimited(
578        buf: &mut &'a [u8],
579        restrict_to: Canonicity,
580    ) -> Result<(Self, Canonicity), DecodeError>
581    where
582        Self: Sized;
583
584    // ------------ Dyn-compatible methods follow ------------
585
586    /// Decodes the non-ignored fields of this message from the buffer in restricted mode,
587    /// replacing their values.
588    fn replace_restricted_borrowed_from(
589        &mut self,
590        buf: &'a [u8],
591        restrict_to: Canonicity,
592    ) -> Result<Canonicity, DecodeError>;
593
594    /// Decodes the non-ignored fields of this message in restricted mode, replacing their values
595    /// from a length-delimited value encoded in the buffer.
596    ///
597    /// * If the message decodes successfully, the provided slice will be shortened to no longer
598    ///   include the bytes that encoded it or its length delimiter.
599    /// * If the message is correctly delimited within the bounds of the slice but fails to decode,
600    ///   the provided slice will still be shortened even though an error is returned.
601    /// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
602    ///   itself is truncated, an error with Truncated kind is returned and it is unspecified how
603    ///   the provided slice value is modified.
604    fn replace_restricted_borrowed_from_length_delimited(
605        &mut self,
606        buf: &mut &'a [u8],
607        restrict_to: Canonicity,
608    ) -> Result<Canonicity, DecodeError>;
609
610    // ------------ Canonical mode ------------
611
612    /// Decodes an instance of the message from a buffer in canonical mode.
613    ///
614    /// The entire buffer will be consumed.
615    fn decode_canonical_borrowed(buf: &'a [u8]) -> Result<Self, DecodeError>
616    where
617        Self: Sized;
618
619    /// Decodes a length-delimited instance of the message from the buffer in canonical mode.
620    ///
621    /// * If the message decodes successfully, the provided slice will be shortened to no longer
622    ///   include the bytes that encoded it or its length delimiter.
623    /// * If the message is correctly delimited within the bounds of the slice but fails to decode,
624    ///   the provided slice will still be shortened even though an error is returned.
625    /// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
626    ///   itself is truncated, an error with Truncated kind is returned and it is unspecified how
627    ///   the provided slice value is modified.
628    fn decode_canonical_borrowed_length_delimited(buf: &mut &'a [u8]) -> Result<Self, DecodeError>
629    where
630        Self: Sized;
631
632    // ------------ Dyn-compatible methods follow ------------
633
634    /// Decodes the non-ignored fields of this message from the buffer in canonical mode,
635    /// replacing their values.
636    fn replace_canonical_borrowed_from(&mut self, buf: &'a [u8]) -> Result<(), DecodeError>;
637
638    /// Decodes the non-ignored fields of this message in canonical mode, replacing their values
639    /// from a length-delimited value encoded in the buffer.
640    ///
641    /// * If the message decodes successfully, the provided slice will be shortened to no longer
642    ///   include the bytes that encoded it or its length delimiter.
643    /// * If the message is correctly delimited within the bounds of the slice but fails to decode,
644    ///   the provided slice will still be shortened even though an error is returned.
645    /// * If the slice is shorter than the length delimiter indicates, or if the length delimiter
646    ///   itself is truncated, an error with Truncated kind is returned and it is unspecified how
647    ///   the provided slice value is modified.
648    fn replace_canonical_borrowed_from_length_delimited(
649        &mut self,
650        buf: &mut &'a [u8],
651    ) -> Result<(), DecodeError>;
652}
653
654/// `Message` is implemented as a usability layer on top of the basic functionality afforded by
655/// `RawMessage`.
656// TODO: extension decoding: extensions can't be provided singly alongside the message that's to be
657//  decoded and capture extensions in anything but the top layer message's extension fields. doing
658//  this in a really robust way that people will probably eventually want will probably require some
659//  kind of moderately robust semi-reflective mapping that mirrors the parsed structure of the
660//  message that it came from; re-encoding from this type could be similarly difficult to implement
661//  efficiently, since the way inlining is done now type-erases the implementations of each field's
662//  encoding and applying extensions would need to either interleave encoded message data (which is
663//  honestly probably faster) or make all of the field encodings reachable polymorphically.
664impl<T> Message for T
665where
666    T: RawMessage + Sized,
667{
668    fn new_empty() -> Self {
669        T::empty()
670    }
671
672    fn encode<B: BufMut + ?Sized>(&self, buf: &mut B) -> Result<(), EncodeError> {
673        let required = self.encoded_len();
674        let remaining = buf.remaining_mut();
675        if required > remaining {
676            return Err(EncodeError::new(required, remaining));
677        }
678
679        self.raw_encode(buf);
680        Ok(())
681    }
682
683    fn prepend<B: ReverseBuf + ?Sized>(&self, buf: &mut B) {
684        self.raw_prepend(buf);
685    }
686
687    fn encode_length_delimited<B: BufMut + ?Sized>(&self, buf: &mut B) -> Result<(), EncodeError> {
688        let len = self.encoded_len();
689        let required = len + encoded_len_varint(len as u64);
690        let remaining = buf.remaining_mut();
691        if required > remaining {
692            return Err(EncodeError::new(required, remaining));
693        }
694        encode_varint(len as u64, buf);
695        self.raw_encode(buf);
696        Ok(())
697    }
698
699    fn message_is_empty(&self) -> bool {
700        self.is_empty()
701    }
702
703    fn clear_message(&mut self) {
704        self.clear();
705    }
706
707    fn encoded_len(&self) -> usize {
708        self.raw_encoded_len()
709    }
710
711    fn encode_to_vec(&self) -> Vec<u8> {
712        let mut buf = Vec::with_capacity(self.encoded_len());
713        self.raw_encode(&mut buf);
714        buf
715    }
716
717    fn encode_to_bytes(&self) -> Bytes {
718        let mut buf = BytesMut::with_capacity(self.encoded_len());
719        self.raw_encode(&mut buf);
720        buf.freeze()
721    }
722
723    fn encode_fast(&self) -> ReverseBuffer {
724        let mut buf = ReverseBuffer::new();
725        self.raw_prepend(&mut buf);
726        buf
727    }
728
729    fn encode_length_delimited_fast(&self) -> ReverseBuffer {
730        let mut buf = self.encode_fast();
731        prepend_varint(buf.remaining() as u64, &mut buf);
732        buf
733    }
734
735    fn encode_contiguous(&self) -> ReverseBuffer {
736        let mut buf = ReverseBuffer::with_capacity(self.encoded_len());
737        self.raw_prepend(&mut buf);
738        debug_assert!(buf.contiguous().is_some());
739        debug_assert!(buf.capacity() == buf.len());
740        buf
741    }
742
743    fn encode_length_delimited_contiguous(&self) -> ReverseBuffer {
744        let len = self.encoded_len();
745        let mut buf = ReverseBuffer::with_capacity(len + length_delimiter_len(len));
746        self.raw_prepend(&mut buf);
747        prepend_varint(len as u64, &mut buf);
748        debug_assert!(buf.contiguous().is_some());
749        debug_assert!(buf.capacity() == buf.len());
750        buf
751    }
752
753    fn encode_dyn(&self, buf: &mut dyn BufMut) -> Result<(), EncodeError> {
754        self.encode(buf)
755    }
756
757    fn encode_length_delimited_to_vec(&self) -> Vec<u8> {
758        let len = self.encoded_len();
759        let mut buf = Vec::with_capacity(len + encoded_len_varint(len as u64));
760
761        encode_varint(len as u64, &mut buf);
762        self.raw_encode(&mut buf);
763        buf
764    }
765
766    fn encode_length_delimited_to_bytes(&self) -> Bytes {
767        let len = self.encoded_len();
768        let mut buf = BytesMut::with_capacity(len + encoded_len_varint(len as u64));
769
770        encode_varint(len as u64, &mut buf);
771        self.raw_encode(&mut buf);
772        buf.freeze()
773    }
774
775    fn encode_length_delimited_dyn(&self, buf: &mut dyn BufMut) -> Result<(), EncodeError> {
776        self.encode_length_delimited(buf)
777    }
778}
779
780impl<T> OwnedMessage for T
781where
782    T: RawMessageDecoder + Sized,
783{
784    fn decode<B: Buf>(mut buf: B) -> Result<Self, DecodeError> {
785        Self::decode_capped(Capped::new(&mut buf))
786    }
787
788    fn decode_length_delimited<B: Buf>(mut buf: B) -> Result<Self, DecodeError> {
789        Self::decode_capped(Capped::new_length_delimited(&mut buf)?)
790    }
791
792    #[doc(hidden)]
793    fn decode_capped<B: Buf + ?Sized>(buf: Capped<B>) -> Result<Self, DecodeError> {
794        let mut message = Self::empty();
795        merge(&mut message, buf, DecodeContext::default())?;
796        Ok(message)
797    }
798
799    fn replace_from<B: Buf>(&mut self, mut buf: B) -> Result<(), DecodeError> {
800        self.replace_from_capped(Capped::new(&mut buf))
801    }
802
803    fn replace_from_length_delimited<B: Buf>(&mut self, mut buf: B) -> Result<(), DecodeError> {
804        self.replace_from_capped(Capped::new_length_delimited(&mut buf)?)
805    }
806
807    #[doc(hidden)]
808    fn replace_from_capped<B: Buf + ?Sized>(&mut self, buf: Capped<B>) -> Result<(), DecodeError> {
809        self.clear();
810        // MSRV: here, and elsewhere, this `map_err` could be `inspect_err` (1.76)
811        merge(self, buf, DecodeContext::default()).map_err(|err| {
812            self.clear();
813            err
814        })
815    }
816
817    fn replace_from_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError> {
818        self.replace_from(buf)
819    }
820
821    fn replace_from_length_delimited_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError> {
822        self.replace_from_length_delimited(buf)
823    }
824
825    fn replace_from_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError> {
826        self.replace_from(buf)
827    }
828
829    fn replace_from_length_delimited_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError> {
830        self.replace_from_length_delimited(buf)
831    }
832
833    #[doc(hidden)]
834    fn replace_from_capped_dyn(&mut self, buf: Capped<dyn Buf>) -> Result<(), DecodeError> {
835        self.replace_from_capped(buf)
836    }
837}
838
839impl<T> DistinguishedOwnedMessage for T
840where
841    T: RawDistinguishedMessageDecoder + RawMessageDecoder,
842{
843    fn decode_distinguished<B: Buf>(buf: B) -> Result<(Self, Canonicity), DecodeError> {
844        Self::decode_restricted(buf, NotCanonical)
845    }
846
847    fn decode_distinguished_length_delimited<B: Buf>(
848        buf: B,
849    ) -> Result<(Self, Canonicity), DecodeError> {
850        Self::decode_restricted_length_delimited(buf, NotCanonical)
851    }
852
853    #[doc(hidden)]
854    fn decode_distinguished_capped<B: Buf + ?Sized>(
855        buf: Capped<B>,
856    ) -> Result<(Self, Canonicity), DecodeError> {
857        Self::decode_restricted_capped(buf, NotCanonical)
858    }
859
860    fn replace_distinguished_from<B: Buf>(&mut self, buf: B) -> Result<Canonicity, DecodeError> {
861        self.replace_restricted_from(buf, NotCanonical)
862    }
863
864    fn replace_distinguished_from_length_delimited<B: Buf>(
865        &mut self,
866        buf: B,
867    ) -> Result<Canonicity, DecodeError> {
868        self.replace_restricted_from_length_delimited(buf, NotCanonical)
869    }
870
871    #[doc(hidden)]
872    fn replace_distinguished_from_capped<B: Buf + ?Sized>(
873        &mut self,
874        buf: Capped<B>,
875    ) -> Result<Canonicity, DecodeError> {
876        self.replace_restricted_from_capped(buf, NotCanonical)
877    }
878
879    fn replace_distinguished_from_slice(&mut self, buf: &[u8]) -> Result<Canonicity, DecodeError> {
880        self.replace_restricted_from(buf, NotCanonical)
881    }
882
883    fn replace_distinguished_from_dyn(
884        &mut self,
885        buf: &mut dyn Buf,
886    ) -> Result<Canonicity, DecodeError> {
887        self.replace_restricted_from(buf, NotCanonical)
888    }
889
890    fn replace_distinguished_from_length_delimited_slice(
891        &mut self,
892        buf: &[u8],
893    ) -> Result<Canonicity, DecodeError> {
894        self.replace_restricted_from_length_delimited(buf, NotCanonical)
895    }
896
897    fn replace_distinguished_from_length_delimited_dyn(
898        &mut self,
899        buf: &mut dyn Buf,
900    ) -> Result<Canonicity, DecodeError> {
901        self.replace_restricted_from_length_delimited(buf, NotCanonical)
902    }
903
904    #[doc(hidden)]
905    fn replace_distinguished_from_capped_dyn(
906        &mut self,
907        buf: Capped<dyn Buf>,
908    ) -> Result<Canonicity, DecodeError> {
909        self.replace_restricted_from_capped(buf, NotCanonical)
910    }
911
912    fn decode_restricted<B: Buf>(
913        mut buf: B,
914        restrict_to: Canonicity,
915    ) -> Result<(Self, Canonicity), DecodeError> {
916        Self::decode_restricted_capped(Capped::new(&mut buf), restrict_to)
917    }
918
919    fn decode_restricted_length_delimited<B: Buf>(
920        mut buf: B,
921        restrict_to: Canonicity,
922    ) -> Result<(Self, Canonicity), DecodeError> {
923        Self::decode_restricted_capped(Capped::new_length_delimited(&mut buf)?, restrict_to)
924    }
925
926    fn decode_restricted_capped<B: Buf + ?Sized>(
927        buf: Capped<B>,
928        restrict_to: Canonicity,
929    ) -> Result<(Self, Canonicity), DecodeError> {
930        let mut message = Self::empty();
931        let ctx = RestrictedDecodeContext::new(restrict_to);
932        let canon = merge_distinguished(&mut message, buf, ctx.clone())
933            // Safety backstop to ensure we do not return a canonicity worse than restrict_to.
934            // See the docs on `RestrictedDecodeContext::check` for details on canonicity
935            // checking.
936            .and_then(|canon| ctx.check(canon))?;
937        Ok((message, canon))
938    }
939
940    fn replace_restricted_from<B: Buf>(
941        &mut self,
942        mut buf: B,
943        restrict_to: Canonicity,
944    ) -> Result<Canonicity, DecodeError> {
945        self.replace_restricted_from_capped(Capped::new(&mut buf), restrict_to)
946    }
947
948    fn replace_restricted_from_length_delimited<B: Buf>(
949        &mut self,
950        mut buf: B,
951        restrict_to: Canonicity,
952    ) -> Result<Canonicity, DecodeError> {
953        self.replace_restricted_from_capped(Capped::new_length_delimited(&mut buf)?, restrict_to)
954    }
955
956    fn replace_restricted_from_capped<B: Buf + ?Sized>(
957        &mut self,
958        buf: Capped<B>,
959        restrict_to: Canonicity,
960    ) -> Result<Canonicity, DecodeError> {
961        self.clear();
962        let ctx = RestrictedDecodeContext::new(restrict_to);
963        merge_distinguished(self, buf, ctx.clone())
964            .map_err(|err| {
965                self.clear();
966                err
967            })
968            // Safety backstop to ensure we do not return a canonicity worse than restrict_to.
969            // See the docs on `RestrictedDecodeContext::check` for details on canonicity
970            // checking.
971            .and_then(|canon| ctx.check(canon))
972    }
973
974    fn replace_restricted_from_slice(
975        &mut self,
976        buf: &[u8],
977        restrict_to: Canonicity,
978    ) -> Result<Canonicity, DecodeError> {
979        self.replace_restricted_from(buf, restrict_to)
980    }
981
982    fn replace_restricted_from_dyn(
983        &mut self,
984        buf: &mut dyn Buf,
985        restrict_to: Canonicity,
986    ) -> Result<Canonicity, DecodeError> {
987        self.replace_restricted_from(buf, restrict_to)
988    }
989
990    fn replace_restricted_from_length_delimited_slice(
991        &mut self,
992        buf: &[u8],
993        restrict_to: Canonicity,
994    ) -> Result<Canonicity, DecodeError> {
995        self.replace_restricted_from_length_delimited(buf, restrict_to)
996    }
997
998    fn replace_restricted_from_length_delimited_dyn(
999        &mut self,
1000        buf: &mut dyn Buf,
1001        restrict_to: Canonicity,
1002    ) -> Result<Canonicity, DecodeError> {
1003        self.replace_restricted_from_length_delimited(buf, restrict_to)
1004    }
1005
1006    fn replace_restricted_from_capped_dyn(
1007        &mut self,
1008        buf: Capped<dyn Buf>,
1009        restrict_to: Canonicity,
1010    ) -> Result<Canonicity, DecodeError> {
1011        self.replace_restricted_from_capped(buf, restrict_to)
1012    }
1013
1014    fn decode_canonical<B: Buf>(buf: B) -> Result<Self, DecodeError> {
1015        Self::decode_restricted(buf, Canonical).map(|(val, _)| val)
1016    }
1017
1018    fn decode_canonical_length_delimited<B: Buf>(buf: B) -> Result<Self, DecodeError> {
1019        Self::decode_restricted_length_delimited(buf, Canonical).map(|(val, _)| val)
1020    }
1021
1022    #[doc(hidden)]
1023    fn decode_canonical_capped<B: Buf + ?Sized>(buf: Capped<B>) -> Result<Self, DecodeError> {
1024        Self::decode_restricted_capped(buf, Canonical).map(|(val, _)| val)
1025    }
1026
1027    fn replace_canonical_from<B: Buf>(&mut self, buf: B) -> Result<(), DecodeError> {
1028        self.replace_restricted_from(buf, Canonical).map(|_| ())
1029    }
1030
1031    fn replace_canonical_from_length_delimited<B: Buf>(
1032        &mut self,
1033        buf: B,
1034    ) -> Result<(), DecodeError> {
1035        self.replace_restricted_from_length_delimited(buf, Canonical)
1036            .map(|_| ())
1037    }
1038
1039    #[doc(hidden)]
1040    fn replace_canonical_from_capped<B: Buf + ?Sized>(
1041        &mut self,
1042        buf: Capped<B>,
1043    ) -> Result<(), DecodeError> {
1044        self.replace_restricted_from_capped(buf, Canonical)
1045            .map(|_| ())
1046    }
1047
1048    fn replace_canonical_from_slice(&mut self, buf: &[u8]) -> Result<(), DecodeError> {
1049        self.replace_restricted_from(buf, Canonical).map(|_| ())
1050    }
1051
1052    fn replace_canonical_from_dyn(&mut self, buf: &mut dyn Buf) -> Result<(), DecodeError> {
1053        self.replace_restricted_from(buf, Canonical).map(|_| ())
1054    }
1055
1056    fn replace_canonical_from_length_delimited_slice(
1057        &mut self,
1058        buf: &[u8],
1059    ) -> Result<(), DecodeError> {
1060        self.replace_restricted_from_length_delimited(buf, Canonical)
1061            .map(|_| ())
1062    }
1063
1064    fn replace_canonical_from_length_delimited_dyn(
1065        &mut self,
1066        buf: &mut dyn Buf,
1067    ) -> Result<(), DecodeError> {
1068        self.replace_restricted_from_length_delimited(buf, Canonical)
1069            .map(|_| ())
1070    }
1071
1072    #[doc(hidden)]
1073    fn replace_canonical_from_capped_dyn(
1074        &mut self,
1075        buf: Capped<dyn Buf>,
1076    ) -> Result<(), DecodeError> {
1077        self.replace_restricted_from_capped(buf, Canonical)
1078            .map(|_| ())
1079    }
1080}
1081
1082impl<'a, T> BorrowedMessage<'a> for T
1083where
1084    T: RawMessageBorrowDecoder<'a> + Sized,
1085{
1086    fn decode_borrowed(mut buf: &'a [u8]) -> Result<Self, DecodeError> {
1087        let mut message = Self::empty();
1088        borrow_merge(
1089            &mut message,
1090            Capped::new(&mut buf),
1091            DecodeContext::default(),
1092        )?;
1093        Ok(message)
1094    }
1095
1096    fn decode_borrowed_length_delimited(buf: &mut &'a [u8]) -> Result<Self, DecodeError> {
1097        Self::decode_borrowed(Capped::new(buf).take_borrowed_length_delimited()?)
1098    }
1099
1100    fn replace_borrowed_from(&mut self, mut buf: &'a [u8]) -> Result<(), DecodeError> {
1101        self.clear();
1102        borrow_merge(self, Capped::new(&mut buf), DecodeContext::default()).map_err(|err| {
1103            self.clear();
1104            err
1105        })
1106    }
1107
1108    fn replace_borrowed_from_length_delimited(
1109        &mut self,
1110        buf: &mut &'a [u8],
1111    ) -> Result<(), DecodeError> {
1112        self.replace_borrowed_from(Capped::new(buf).take_borrowed_length_delimited()?)
1113    }
1114}
1115
1116impl<'a, T> DistinguishedBorrowedMessage<'a> for T
1117where
1118    T: RawDistinguishedMessageBorrowDecoder<'a> + RawMessageBorrowDecoder<'a>,
1119{
1120    fn decode_distinguished_borrowed(buf: &'a [u8]) -> Result<(Self, Canonicity), DecodeError> {
1121        Self::decode_restricted_borrowed(buf, NotCanonical)
1122    }
1123
1124    fn decode_distinguished_borrowed_length_delimited(
1125        buf: &mut &'a [u8],
1126    ) -> Result<(Self, Canonicity), DecodeError> {
1127        Self::decode_restricted_borrowed_length_delimited(buf, NotCanonical)
1128    }
1129
1130    fn replace_distinguished_borrowed_from(
1131        &mut self,
1132        buf: &'a [u8],
1133    ) -> Result<Canonicity, DecodeError> {
1134        self.replace_restricted_borrowed_from(buf, NotCanonical)
1135    }
1136
1137    fn replace_distinguished_borrowed_from_length_delimited(
1138        &mut self,
1139        buf: &mut &'a [u8],
1140    ) -> Result<Canonicity, DecodeError> {
1141        self.replace_restricted_borrowed_from_length_delimited(buf, NotCanonical)
1142    }
1143
1144    fn decode_restricted_borrowed(
1145        mut buf: &'a [u8],
1146        restrict_to: Canonicity,
1147    ) -> Result<(Self, Canonicity), DecodeError> {
1148        let mut message = Self::empty();
1149        let ctx = RestrictedDecodeContext::new(restrict_to);
1150        let canon = borrow_merge_distinguished(&mut message, Capped::new(&mut buf), ctx.clone())
1151            // Safety backstop to ensure we do not return a canonicity worse than restrict_to.
1152            // See the docs on `RestrictedDecodeContext::check` for details on canonicity
1153            // checking.
1154            .and_then(|canon| ctx.check(canon))?;
1155        Ok((message, canon))
1156    }
1157
1158    fn decode_restricted_borrowed_length_delimited(
1159        buf: &mut &'a [u8],
1160        restrict_to: Canonicity,
1161    ) -> Result<(Self, Canonicity), DecodeError> {
1162        Self::decode_restricted_borrowed(
1163            Capped::new(buf).take_borrowed_length_delimited()?,
1164            restrict_to,
1165        )
1166    }
1167
1168    fn replace_restricted_borrowed_from(
1169        &mut self,
1170        mut buf: &'a [u8],
1171        restrict_to: Canonicity,
1172    ) -> Result<Canonicity, DecodeError> {
1173        self.clear();
1174        let ctx = RestrictedDecodeContext::new(restrict_to);
1175        borrow_merge_distinguished(self, Capped::new(&mut buf), ctx.clone())
1176            .map_err(|err| {
1177                self.clear();
1178                err
1179            })
1180            // Safety backstop to ensure we do not return a canonicity worse than restrict_to.
1181            // See the docs on `RestrictedDecodeContext::check` for details on canonicity
1182            // checking.
1183            .and_then(|canon| ctx.check(canon))
1184    }
1185
1186    fn replace_restricted_borrowed_from_length_delimited(
1187        &mut self,
1188        buf: &mut &'a [u8],
1189        restrict_to: Canonicity,
1190    ) -> Result<Canonicity, DecodeError> {
1191        self.replace_restricted_borrowed_from(
1192            Capped::new(buf).take_borrowed_length_delimited()?,
1193            restrict_to,
1194        )
1195    }
1196
1197    fn decode_canonical_borrowed(buf: &'a [u8]) -> Result<Self, DecodeError> {
1198        Self::decode_restricted_borrowed(buf, Canonical).map(|(val, _)| val)
1199    }
1200
1201    fn decode_canonical_borrowed_length_delimited(buf: &mut &'a [u8]) -> Result<Self, DecodeError> {
1202        Self::decode_restricted_borrowed_length_delimited(buf, Canonical).map(|(val, _)| val)
1203    }
1204
1205    fn replace_canonical_borrowed_from(&mut self, buf: &'a [u8]) -> Result<(), DecodeError> {
1206        self.replace_restricted_borrowed_from(buf, Canonical)
1207            .map(|_| ())
1208    }
1209
1210    fn replace_canonical_borrowed_from_length_delimited(
1211        &mut self,
1212        buf: &mut &'a [u8],
1213    ) -> Result<(), DecodeError> {
1214        self.replace_restricted_borrowed_from_length_delimited(buf, Canonical)
1215            .map(|_| ())
1216    }
1217}
1218
1219#[cfg(test)]
1220mod tests {
1221    use super::{
1222        BorrowedMessage, DistinguishedBorrowedMessage, DistinguishedOwnedMessage, Message,
1223        OwnedMessage,
1224    };
1225    use alloc::vec::Vec;
1226
1227    const _MESSAGE_IS_DYN_COMPATIBLE: Option<&dyn Message> = None;
1228    const _OWNED_MESSAGE_IS_DYN_COMPATIBLE: Option<&dyn OwnedMessage> = None;
1229    const _DISTINGUISHED_OWNED_MESSAGE_IS_DYN_COMPATIBLE: Option<&dyn DistinguishedOwnedMessage> =
1230        None;
1231    const _BORROWED_MESSAGE_IS_DYN_COMPATIBLE: Option<&dyn BorrowedMessage<'static>> = None;
1232    const _DISTINGUISHED_BORROWED_MESSAGE_IS_DYN_COMPATIBLE: Option<
1233        &dyn DistinguishedBorrowedMessage<'static>,
1234    > = None;
1235
1236    fn use_dyn_owned_messages<M: DistinguishedOwnedMessage>(
1237        safe: &mut dyn DistinguishedOwnedMessage,
1238        mut msg: M,
1239    ) {
1240        let mut vec = Vec::<u8>::new();
1241
1242        safe.encoded_len();
1243        safe.encode_dyn(&mut vec).unwrap();
1244        assert_eq!(vec, safe.encode_to_vec());
1245        assert_eq!(vec, safe.encode_contiguous().into_vec());
1246        safe.replace_from_length_delimited_dyn(&mut [0u8].as_slice())
1247            .unwrap();
1248        assert!(safe.message_is_empty());
1249        safe.replace_canonical_from_length_delimited_dyn(&mut [0u8].as_slice())
1250            .unwrap();
1251        assert!(safe.message_is_empty());
1252        safe.replace_from_slice(&[]).unwrap();
1253        assert!(safe.message_is_empty());
1254        safe.replace_canonical_from_slice(&[]).unwrap();
1255        assert!(safe.message_is_empty());
1256
1257        msg.encoded_len();
1258        msg = M::decode_length_delimited(&mut [0u8].as_slice()).unwrap();
1259        msg.encode(&mut vec).unwrap();
1260        msg.clear_message();
1261    }
1262
1263    fn use_dyn_borrowed_messages<'a, M: DistinguishedBorrowedMessage<'a>>(
1264        safe: &mut dyn DistinguishedBorrowedMessage<'a>,
1265        mut msg: M,
1266    ) {
1267        let mut vec = Vec::<u8>::new();
1268
1269        safe.encoded_len();
1270        safe.encode_dyn(&mut vec).unwrap();
1271        assert_eq!(vec, safe.encode_to_vec());
1272        safe.replace_borrowed_from_length_delimited(&mut [0u8].as_slice())
1273            .unwrap();
1274        assert!(safe.message_is_empty());
1275        safe.replace_canonical_borrowed_from_length_delimited(&mut [0u8].as_slice())
1276            .unwrap();
1277        assert!(safe.message_is_empty());
1278
1279        msg.encoded_len();
1280        msg = M::decode_borrowed_length_delimited(&mut [0u8].as_slice()).unwrap();
1281        msg.encode(&mut vec).unwrap();
1282        msg.clear_message();
1283    }
1284
1285    #[test]
1286    fn using_dyn_messages() {
1287        let mut vec = Vec::<u8>::new();
1288        use_dyn_owned_messages(&mut (), ());
1289        use_dyn_borrowed_messages(&mut (), ());
1290        assert_eq!(().encoded_len(), 0);
1291        ().encode(&mut vec).unwrap();
1292        ().encode_dyn(&mut vec).unwrap();
1293        <()>::decode(&mut [].as_slice()).unwrap();
1294    }
1295}