rune_alloc/
musli.rs

1use core::fmt;
2use core::hash::{BuildHasher, Hash};
3
4use crate::borrow::Cow;
5use crate::borrow::TryToOwned;
6use crate::sync::Arc;
7use crate::{BTreeMap, BTreeSet, Box, HashMap, HashSet, String, Vec, VecDeque};
8
9use musli::alloc::ToOwned;
10use musli::de::SizeHint;
11use musli::de::{
12    Decode, DecodeBytes, DecodeSliceBuilder, DecodeTrace, Decoder, EntryDecoder, MapDecoder,
13    SequenceDecoder, UnsizedVisitor,
14};
15use musli::en::{
16    Encode, EncodeBytes, EncodePacked, EncodeTrace, Encoder, EntryEncoder, MapEncoder,
17    SequenceEncoder,
18};
19use musli::{Allocator, Context};
20
21// Uses the same heuristic as:
22// https://github.com/serde-rs/serde/blob/d91f8ba950e2faf4db4e283e917ba2ee94a9b8a4/serde/src/de/size_hint.rs#L12
23#[inline]
24pub(crate) fn cautious<T>(hint: impl Into<SizeHint>) -> usize {
25    const MAX_PREALLOC_BYTES: usize = 1024 * 1024;
26
27    if size_of::<T>() == 0 {
28        return 0;
29    }
30
31    hint.into()
32        .or_default()
33        .min(MAX_PREALLOC_BYTES / size_of::<T>())
34}
35
36impl<M> Encode<M> for String {
37    type Encode = str;
38
39    const IS_BITWISE_ENCODE: bool = false;
40
41    #[inline]
42    fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
43    where
44        E: Encoder<Mode = M>,
45    {
46        self.as_str().encode(encoder)
47    }
48
49    #[inline]
50    fn as_encode(&self) -> &Self::Encode {
51        self
52    }
53}
54
55impl<'de, M, A> Decode<'de, M, A> for String
56where
57    A: Allocator,
58{
59    const IS_BITWISE_DECODE: bool = false;
60
61    #[inline]
62    fn decode<D>(decoder: D) -> Result<Self, D::Error>
63    where
64        D: Decoder<'de, Mode = M>,
65    {
66        struct Visitor;
67
68        #[musli::de::unsized_visitor]
69        impl<C> UnsizedVisitor<'_, C, str> for Visitor
70        where
71            C: Context,
72        {
73            type Ok = String;
74
75            #[inline]
76            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77                write!(f, "string")
78            }
79
80            #[inline]
81            fn visit_ref(self, cx: C, string: &str) -> Result<Self::Ok, Self::Error> {
82                string.try_to_owned().map_err(|e| cx.custom(e))
83            }
84        }
85
86        decoder.decode_string(Visitor)
87    }
88}
89
90impl<'de, M, A> Decode<'de, M, A> for Box<str>
91where
92    A: Allocator,
93{
94    const IS_BITWISE_DECODE: bool = false;
95
96    #[inline]
97    fn decode<D>(decoder: D) -> Result<Self, D::Error>
98    where
99        D: Decoder<'de, Mode = M>,
100    {
101        let cx = decoder.cx();
102        decoder
103            .decode::<String>()?
104            .try_into()
105            .map_err(|e| cx.custom(e))
106    }
107}
108
109macro_rules! cow {
110    (
111        $encode:ident :: $encode_fn:ident,
112        $as_encode:ident,
113        $decode:ident :: $decode_fn:ident,
114        $encode_packed:ident,
115        $decode_packed:ident,
116        $ty:ty, $source:ty,
117        $decode_method:ident, $cx:pat,
118        |$owned:ident| $owned_expr:expr,
119        |$borrowed:ident| $borrowed_expr:expr,
120        |$reference:ident| $reference_expr:expr $(,)?
121    ) => {
122        impl<M> $encode<M> for Cow<'_, $ty> {
123            const $encode_packed: bool = false;
124
125            type $encode = $ty;
126
127            #[inline]
128            fn $encode_fn<E>(&self, encoder: E) -> Result<(), E::Error>
129            where
130                E: Encoder<Mode = M>,
131            {
132                self.as_ref().$encode_fn(encoder)
133            }
134
135            #[inline]
136            fn $as_encode(&self) -> &Self::$encode {
137                self
138            }
139        }
140
141        impl<'de, M, A> $decode<'de, M, A> for Cow<'_, $ty>
142        where
143            A: Allocator,
144        {
145            const $decode_packed: bool = false;
146
147            #[inline]
148            fn $decode_fn<D>(decoder: D) -> Result<Self, D::Error>
149            where
150                D: Decoder<'de, Mode = M, Allocator = A>,
151            {
152                struct Visitor;
153
154                #[musli::de::unsized_visitor]
155                impl<'de, C> UnsizedVisitor<'de, C, $source> for Visitor
156                where
157                    C: Context,
158                {
159                    type Ok = Cow<'static, $ty>;
160
161                    #[inline]
162                    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163                        write!(f, "a string")
164                    }
165
166                    #[inline]
167                    fn visit_owned(
168                        self,
169                        $cx: C,
170                        $owned: <$source as ToOwned>::Owned<Self::Allocator>,
171                    ) -> Result<Self::Ok, Self::Error> {
172                        Ok($owned_expr)
173                    }
174
175                    #[inline]
176                    fn visit_borrowed(
177                        self,
178                        $cx: C,
179                        $borrowed: &'de $source,
180                    ) -> Result<Self::Ok, Self::Error> {
181                        Ok($borrowed_expr)
182                    }
183
184                    #[inline]
185                    fn visit_ref(
186                        self,
187                        $cx: C,
188                        $reference: &$source,
189                    ) -> Result<Self::Ok, Self::Error> {
190                        Ok($reference_expr)
191                    }
192                }
193
194                decoder.$decode_method(Visitor)
195            }
196        }
197    };
198}
199
200cow! {
201    Encode::encode,
202    as_encode,
203    Decode::decode,
204    IS_BITWISE_ENCODE,
205    IS_BITWISE_DECODE,
206    str, str, decode_string, cx,
207    |owned| {
208        match owned.into_std() {
209            Ok(owned) => Cow::Owned(owned.try_into().map_err(|e| cx.custom(e))?),
210            Err(owned) => {
211                Cow::Owned(TryToOwned::try_to_owned(owned.as_str()).map_err(|e| cx.custom(e))?)
212            }
213        }
214    },
215    |borrowed| Cow::Owned(TryToOwned::try_to_owned(borrowed).map_err(|e| cx.custom(e))?),
216    |reference| Cow::Owned(TryToOwned::try_to_owned(reference).map_err(|e| cx.custom(e))?),
217}
218
219cow! {
220    EncodeBytes::encode_bytes,
221    as_encode_bytes,
222    DecodeBytes::decode_bytes,
223    ENCODE_BYTES_PACKED,
224    DECODE_BYTES_PACKED,
225    [u8], [u8], decode_bytes, cx,
226    |owned| {
227        match owned.into_std() {
228            Ok(owned) => Cow::Owned(owned.try_into().map_err(|e| cx.custom(e))?),
229            Err(owned) => Cow::Owned(TryToOwned::try_to_owned(owned.as_slice()).map_err(|e| cx.custom(e))?),
230        }
231    },
232    |borrowed| Cow::Owned(TryToOwned::try_to_owned(borrowed).map_err(|e| cx.custom(e))?),
233    |reference| Cow::Owned(TryToOwned::try_to_owned(reference).map_err(|e| cx.custom(e))?),
234}
235
236macro_rules! sequence {
237    (
238        $(#[$($meta:meta)*])*
239        $cx:ident,
240        $ty:ident <T $(: $trait0:ident $(+ $trait:ident)*)? $(, $extra:ident: $extra_bound0:ident $(+ $extra_bound:ident)*)*>,
241        $insert:ident,
242        $access:ident,
243        $factory:expr
244    ) => {
245        $(#[$($meta)*])*
246        impl<M, T $(, $extra)*> Encode<M> for $ty<T $(, $extra)*>
247        where
248            T: Encode<M>,
249            $($extra: $extra_bound0 $(+ $extra_bound)*),*
250        {
251            const IS_BITWISE_ENCODE: bool = false;
252
253            type Encode = Self;
254
255            #[inline]
256            fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
257            where
258                E: Encoder<Mode = M>,
259            {
260                let $cx = encoder.cx();
261
262                encoder.encode_sequence_fn(self.len(), |seq| {
263                    let mut index = 0;
264
265                    for value in self {
266                        $cx.enter_sequence_index(index);
267                        seq.push(value)?;
268                        $cx.leave_sequence_index();
269                        index = index.wrapping_add(1);
270                    }
271
272                    Ok(())
273                })
274            }
275
276            #[inline]
277            fn as_encode(&self) -> &Self::Encode {
278                self
279            }
280        }
281
282        $(#[$($meta)*])*
283        impl<'de, M, A, T $(, $extra)*> Decode<'de, M, A> for $ty<T $(, $extra)*>
284        where
285            A: Allocator,
286            T: Decode<'de, M, A> $(+ $trait0 $(+ $trait)*)*,
287            $($extra: $extra_bound0 $(+ $extra_bound)*),*
288        {
289            const IS_BITWISE_DECODE: bool = false;
290
291            #[inline]
292            fn decode<D>(decoder: D) -> Result<Self, D::Error>
293            where
294                D: Decoder<'de, Mode = M, Allocator = A>,
295            {
296                let $cx = decoder.cx();
297
298                decoder.decode_sequence(|$access| {
299                    let mut out = $factory;
300
301                    let mut index = 0;
302
303                    while let Some(value) = $access.try_decode_next()? {
304                        $cx.enter_sequence_index(index);
305                        out.$insert(value.decode()?).map_err(|e| $cx.custom(e))?;
306                        $cx.leave_sequence_index();
307                        index = index.wrapping_add(1);
308                    }
309
310                    Ok(out)
311                })
312            }
313        }
314
315        $(#[$($meta)*])*
316        impl<M, T $(, $extra)*> EncodePacked<M> for $ty<T $(, $extra)*>
317        where
318            T: Encode<M>,
319            $($extra: $extra_bound0 $(+ $extra_bound)*),*
320        {
321            #[inline]
322            fn encode_packed<E>(&self, encoder: E) -> Result<(), E::Error>
323            where
324                E: Encoder<Mode = M>,
325            {
326                let $cx = encoder.cx();
327
328                encoder.encode_pack_fn(|pack| {
329                    let mut index = 0;
330
331                    for value in self {
332                        $cx.enter_sequence_index(index);
333                        pack.push(value)?;
334                        $cx.leave_sequence_index();
335                        index = index.wrapping_add(1);
336                    }
337
338                    Ok(())
339                })
340            }
341        }
342    }
343}
344
345macro_rules! slice_sequence {
346    (
347        $(#[$($meta:meta)*])*
348        $cx:ident,
349        $ty:ident <T $(, $alloc:ident)?>,
350        || $new:expr,
351        |$vec:ident, $value:ident| $insert:expr,
352        |$reserve_vec:ident, $reserve_capacity:ident| $reserve:expr,
353        |$capacity:ident| $with_capacity:expr,
354    ) => {
355        $(#[$($meta)*])*
356        impl<M, T $(, $alloc)*> Encode<M> for $ty<T $(, $alloc)*>
357        where
358            T: Encode<M>,
359            $($alloc: Allocator,)*
360        {
361            const IS_BITWISE_ENCODE: bool = false;
362
363            type Encode = Self;
364
365            #[inline]
366            fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
367            where
368                E: Encoder<Mode = M>,
369            {
370                encoder.encode_slice(self)
371            }
372
373            #[inline]
374            fn as_encode(&self) -> &Self::Encode {
375                self
376            }
377        }
378
379        $(#[$($meta)*])*
380        impl<'de, M, A, T> Decode<'de, M, A> for $ty<T $(, $alloc)*>
381        where
382            A: Allocator,
383            T: Decode<'de, M, A>,
384        {
385            const IS_BITWISE_DECODE: bool = false;
386
387            #[inline]
388            fn decode<D>(decoder: D) -> Result<Self, D::Error>
389            where
390                D: Decoder<'de, Mode = M, Allocator = A>,
391            {
392                struct Builder<'de, M, A, T>
393                where
394                    $($alloc: Allocator,)*
395                {
396                    vec: $ty<T $(, $alloc)*>,
397                    _marker: core::marker::PhantomData<(M, A, &'de ())>
398                }
399
400                #[allow(unused_variables)]
401                impl<'de, M, A, T> DecodeSliceBuilder<T, A> for Builder<'de, M, A, T>
402                where
403                    T: Decode<'de, M, A>,
404                    A: Allocator,
405                {
406                    #[inline]
407                    fn new<C>($cx: C) -> Result<Self, C::Error>
408                    where
409                        C: Context<Allocator = A>,
410                    {
411                        Ok(Builder {
412                            vec: $new,
413                            _marker: core::marker::PhantomData
414                        })
415                    }
416
417                    #[inline]
418                    fn with_capacity<C>($cx: C, $capacity: usize) -> Result<Self, C::Error>
419                    where
420                        C: Context<Allocator = A>,
421                    {
422                        Ok(Builder {
423                            vec: $with_capacity,
424                            _marker: core::marker::PhantomData
425                        })
426                    }
427
428                    #[inline]
429                    fn push<C>(&mut self, $cx: C, $value: T) -> Result<(), C::Error>
430                    where
431                        C: Context<Allocator = A>,
432                    {
433                        let $vec = &mut self.vec;
434                        $insert;
435                        Ok(())
436                    }
437
438                    #[inline]
439                    fn reserve<C>( &mut self, $cx: C, $reserve_capacity: usize) -> Result<(), C::Error>
440                    where
441                        C: Context<Allocator = A>,
442                    {
443                        let $reserve_vec = &mut self.vec;
444                        $reserve;
445                        Ok(())
446                    }
447
448                    #[inline]
449                    unsafe fn set_len(&mut self, len: usize) {
450                        self.vec.set_len(len);
451                    }
452
453                    #[inline]
454                    fn as_mut_ptr(&mut self) -> *mut T {
455                        self.vec.as_mut_ptr()
456                    }
457                }
458
459                let Builder { vec, _marker: core::marker::PhantomData } = decoder.decode_slice()?;
460                Ok(vec)
461            }
462        }
463
464        $(#[$($meta)*])*
465        impl<M, T $(, $alloc)*> EncodePacked<M> for $ty<T $(, $alloc)*>
466        where
467            T: Encode<M>,
468            $($alloc: Allocator,)*
469        {
470            #[inline]
471            fn encode_packed<E>(&self, encoder: E) -> Result<(), E::Error>
472            where
473                E: Encoder<Mode = M>,
474            {
475                encoder.encode_pack_fn(|pack| {
476                    SequenceEncoder::encode_slice(pack, self)
477                })
478            }
479        }
480    }
481}
482
483slice_sequence! {
484    cx,
485    Vec<T>,
486    || Vec::new(),
487    |vec, value| vec.try_push(value).map_err(|e| cx.custom(e))?,
488    |vec, capacity| vec.try_reserve(capacity).map_err(|e| cx.custom(e))?,
489    |size| Vec::try_with_capacity(size).map_err(|e| cx.custom(e))?,
490}
491
492impl<M, T> Encode<M> for VecDeque<T>
493where
494    T: Encode<M>,
495{
496    type Encode = Self;
497
498    const IS_BITWISE_ENCODE: bool = false;
499
500    #[inline]
501    fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
502    where
503        E: Encoder<Mode = M>,
504    {
505        let (a, b) = self.as_slices();
506        encoder.encode_slices(self.len(), [a, b])
507    }
508
509    #[inline]
510    fn as_encode(&self) -> &Self::Encode {
511        self
512    }
513}
514
515impl<'de, M, A, T> Decode<'de, M, A> for VecDeque<T>
516where
517    A: Allocator,
518    T: Decode<'de, M, A>,
519{
520    const IS_BITWISE_DECODE: bool = false;
521
522    #[inline]
523    fn decode<D>(decoder: D) -> Result<Self, D::Error>
524    where
525        D: Decoder<'de, Mode = M, Allocator = A>,
526    {
527        Ok(VecDeque::from(Vec::decode(decoder)?))
528    }
529}
530
531impl<M, T> EncodePacked<M> for VecDeque<T>
532where
533    T: Encode<M>,
534{
535    #[inline]
536    fn encode_packed<E>(&self, encoder: E) -> Result<(), E::Error>
537    where
538        E: Encoder<Mode = M>,
539    {
540        encoder.encode_pack_fn(|pack| {
541            let (a, b) = self.as_slices();
542            pack.encode_slices([a, b])
543        })
544    }
545}
546
547sequence! {
548    cx,
549    BTreeSet<T: Ord>,
550    try_insert,
551    seq,
552    BTreeSet::new()
553}
554
555sequence! {
556    cx,
557    HashSet<T: Eq + Hash, S: BuildHasher + Default>,
558    try_insert,
559    seq,
560    HashSet::try_with_capacity_and_hasher(cautious::<T>(seq.size_hint()), S::default()).map_err(|e| cx.custom(e))?
561}
562
563macro_rules! map {
564    (
565        $(#[$($meta:meta)*])*
566        $cx:ident,
567        $ty:ident<K $(: $key_bound0:ident $(+ $key_bound:ident)*)?, V $(, $extra:ident: $extra_bound0:ident $(+ $extra_bound:ident)*)*>,
568        $access:ident,
569        $with_capacity:expr
570    ) => {
571        $(#[$($meta)*])*
572        impl<'de, M, K, V $(, $extra)*> Encode<M> for $ty<K, V $(, $extra)*>
573        where
574            K: Encode<M>,
575            V: Encode<M>,
576            $($extra: $extra_bound0 $(+ $extra_bound)*),*
577        {
578            const IS_BITWISE_ENCODE: bool = false;
579
580            type Encode = Self;
581
582            #[inline]
583            fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
584            where
585                E: Encoder<Mode = M>,
586            {
587                let hint = self.len();
588
589                encoder.encode_map_fn(hint, |map| {
590                    for (k, v) in self {
591                        map.insert_entry(k, v)?;
592                    }
593
594                    Ok(())
595                })
596            }
597
598            #[inline]
599            fn as_encode(&self) -> &Self::Encode {
600                self
601            }
602        }
603
604        $(#[$($meta)*])*
605        impl<'de, M, K, V $(, $extra)*> EncodeTrace<M> for $ty<K, V $(, $extra)*>
606        where
607            K: fmt::Display + Encode<M>,
608            V: Encode<M>,
609            $($extra: $extra_bound0 $(+ $extra_bound)*),*
610        {
611            #[inline]
612            fn trace_encode<E>(&self, encoder: E) -> Result<(), E::Error>
613            where
614                E: Encoder<Mode = M>,
615            {
616                let hint = self.len();
617
618                let $cx = encoder.cx();
619
620                encoder.encode_map_fn(hint, |map| {
621                    for (k, v) in self {
622                        $cx.enter_map_key(k);
623                        map.encode_entry_fn(|entry| {
624                            entry.encode_key()?.encode(k)?;
625                            entry.encode_value()?.encode(v)?;
626                            Ok(())
627                        })?;
628                        $cx.leave_map_key();
629                    }
630
631                    Ok(())
632                })
633            }
634        }
635
636        $(#[$($meta)*])*
637        impl<'de, K, V, A, M $(, $extra)*> Decode<'de, M, A> for $ty<K, V $(, $extra)*>
638        where
639            A: Allocator,
640            K: Decode<'de, M, A> $(+ $key_bound0 $(+ $key_bound)*)*,
641            V: Decode<'de, M, A>,
642            $($extra: $extra_bound0 $(+ $extra_bound)*),*
643        {
644            const IS_BITWISE_DECODE: bool = false;
645
646            #[inline]
647            fn decode<D>(decoder: D) -> Result<Self, D::Error>
648            where
649                D: Decoder<'de, Mode = M, Allocator = A>,
650            {
651                let $cx = decoder.cx();
652
653                decoder.decode_map(|$access| {
654                    let mut out = $with_capacity;
655
656                    while let Some((key, value)) = $access.entry()? {
657                        out.try_insert(key, value).map_err(|e| $cx.custom(e))?;
658                    }
659
660                    Ok(out)
661                })
662            }
663        }
664
665        $(#[$($meta)*])*
666        impl<'de, K, V, A, M $(, $extra)*> DecodeTrace<'de, M, A> for $ty<K, V $(, $extra)*>
667        where
668            A: Allocator,
669            K: fmt::Display + Decode<'de, M, A> $(+ $key_bound0 $(+ $key_bound)*)*,
670            V: Decode<'de, M, A>,
671            $($extra: $extra_bound0 $(+ $extra_bound)*),*
672        {
673            #[inline]
674            fn trace_decode<D>(decoder: D) -> Result<Self, D::Error>
675            where
676                D: Decoder<'de, Mode = M, Allocator = A>,
677            {
678                let $cx = decoder.cx();
679
680                decoder.decode_map(|$access| {
681                    let mut out = $with_capacity;
682
683                    while let Some(mut entry) = $access.decode_entry()? {
684                        let key = entry.decode_key()?.decode()?;
685                        $cx.enter_map_key(&key);
686                        let value = entry.decode_value()?.decode()?;
687                        out.try_insert(key, value).map_err(|e| $cx.custom(e))?;
688                        $cx.leave_map_key();
689                    }
690
691                    Ok(out)
692                })
693            }
694        }
695    }
696}
697
698map!(_cx, BTreeMap<K: Ord, V>, map, BTreeMap::new());
699
700map!(
701    cx,
702    HashMap<K: Eq + Hash, V, S: BuildHasher + Default>,
703    map,
704    HashMap::try_with_capacity_and_hasher(cautious::<(K, V)>(map.size_hint()), S::default()).map_err(|e| cx.custom(e))?
705);
706
707macro_rules! smart_pointer {
708    ($($ty:ident),* $(,)?) => {
709        $(
710            impl<M, T> Encode<M> for $ty<T>
711            where
712                T: ?Sized + Encode<M>,
713            {
714                const IS_BITWISE_ENCODE: bool = false;
715
716                type Encode = T;
717
718                #[inline]
719                fn encode<E>(&self, encoder: E) -> Result<(), E::Error>
720                where
721                    E: Encoder<Mode = M>,
722                {
723                    self.as_ref().encode(encoder)
724                }
725
726                #[inline]
727                fn as_encode(&self) -> &Self::Encode {
728                    self
729                }
730            }
731
732            impl<'de, M, A, T> Decode<'de, M, A> for $ty<T>
733            where
734                A: Allocator,
735                T: Decode<'de, M, A>,
736            {
737                const IS_BITWISE_DECODE: bool = false;
738
739                #[inline]
740                fn decode<D>(decoder: D) -> Result<Self, D::Error>
741                where
742                    D: Decoder<'de, Mode = M, Allocator = A>,
743                {
744                    let cx = decoder.cx();
745                    $ty::try_new(decoder.decode()?).map_err(|e| cx.custom(e))
746                }
747            }
748
749            impl<'de, M, A, T> Decode<'de, M, A> for $ty<[T]>
750            where
751                A: Allocator,
752                T: Decode<'de, M, A>,
753            {
754                const IS_BITWISE_DECODE: bool = false;
755
756                #[inline]
757                fn decode<D>(decoder: D) -> Result<Self, D::Error>
758                where
759                    D: Decoder<'de, Mode = M, Allocator = A>,
760                {
761                    let cx = decoder.cx();
762                    $ty::try_from(Vec::<T>::decode(decoder)?).map_err(|e| cx.custom(e))
763                }
764            }
765
766            impl<'de, M, A> DecodeBytes<'de, M, A> for $ty<[u8]>
767            where
768                A: Allocator
769            {
770                const DECODE_BYTES_PACKED: bool = false;
771
772                #[inline]
773                fn decode_bytes<D>(decoder: D) -> Result<Self, D::Error>
774                where
775                    D: Decoder<'de, Mode = M, Allocator = A>,
776                {
777                    let cx = decoder.cx();
778                    $ty::try_from(<Vec<u8>>::decode_bytes(decoder)?).map_err(|e| cx.custom(e))
779                }
780            }
781        )*
782    };
783}
784
785smart_pointer!(Arc, Box);
786
787impl<M> EncodeBytes<M> for Vec<u8> {
788    const ENCODE_BYTES_PACKED: bool = false;
789
790    type EncodeBytes = [u8];
791
792    #[inline]
793    fn encode_bytes<E>(&self, encoder: E) -> Result<(), E::Error>
794    where
795        E: Encoder<Mode = M>,
796    {
797        encoder.encode_bytes(self.as_slice())
798    }
799
800    #[inline]
801    fn as_encode_bytes(&self) -> &Self::EncodeBytes {
802        self
803    }
804}
805
806impl<M> EncodeBytes<M> for Box<[u8]> {
807    const ENCODE_BYTES_PACKED: bool = false;
808
809    type EncodeBytes = [u8];
810
811    #[inline]
812    fn encode_bytes<E>(&self, encoder: E) -> Result<(), E::Error>
813    where
814        E: Encoder<Mode = M>,
815    {
816        encoder.encode_bytes(self.as_ref())
817    }
818
819    #[inline]
820    fn as_encode_bytes(&self) -> &Self::EncodeBytes {
821        self
822    }
823}
824
825impl<'de, M, A> DecodeBytes<'de, M, A> for Vec<u8>
826where
827    A: Allocator,
828{
829    const DECODE_BYTES_PACKED: bool = false;
830
831    #[inline]
832    fn decode_bytes<D>(decoder: D) -> Result<Self, D::Error>
833    where
834        D: Decoder<'de, Mode = M, Allocator = A>,
835    {
836        struct Visitor;
837
838        #[musli::de::unsized_visitor]
839        impl<'de, C> UnsizedVisitor<'de, C, [u8]> for Visitor
840        where
841            C: Context,
842        {
843            type Ok = Vec<u8>;
844
845            #[inline]
846            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
847                write!(f, "bytes")
848            }
849
850            #[inline]
851            fn visit_borrowed(self, cx: C, bytes: &'de [u8]) -> Result<Self::Ok, Self::Error> {
852                Vec::try_from(bytes).map_err(|e| cx.custom(e))
853            }
854
855            #[inline]
856            fn visit_ref(self, cx: C, bytes: &[u8]) -> Result<Self::Ok, Self::Error> {
857                Vec::try_from(bytes).map_err(|e| cx.custom(e))
858            }
859        }
860
861        decoder.decode_bytes(Visitor)
862    }
863}
864
865impl<M> EncodeBytes<M> for VecDeque<u8> {
866    const ENCODE_BYTES_PACKED: bool = false;
867
868    type EncodeBytes = VecDeque<u8>;
869
870    #[inline]
871    fn encode_bytes<E>(&self, encoder: E) -> Result<(), E::Error>
872    where
873        E: Encoder<Mode = M>,
874    {
875        let (first, second) = self.as_slices();
876        encoder.encode_bytes_vectored(self.len(), &[first, second])
877    }
878
879    #[inline]
880    fn as_encode_bytes(&self) -> &Self::EncodeBytes {
881        self
882    }
883}
884
885impl<'de, M, A> DecodeBytes<'de, M, A> for VecDeque<u8>
886where
887    A: Allocator,
888{
889    const DECODE_BYTES_PACKED: bool = false;
890
891    #[inline]
892    fn decode_bytes<D>(decoder: D) -> Result<Self, D::Error>
893    where
894        D: Decoder<'de, Mode = M, Allocator = A>,
895    {
896        Ok(VecDeque::from(<Vec<u8>>::decode_bytes(decoder)?))
897    }
898}