Skip to main content

deser_core/adapters/
mod.rs

1//! Adapters to customize how values are serialized and deserialized.
2//!
3//! An adapter is a type that knows how to serialize or deserialize a value of
4//! *another* type.  [`Serialize`] and [`Deserialize`] have a type parameter
5//! for the type of the value which defaults to `Self`: adapters implement
6//! `Serialize<T>` and `Deserialize<'de, T>` for the types `T` they support.
7//! They are typically zero sized marker types which are never instantiated.
8//!
9//! Adapters compose: the standard containers are adapters for the same
10//! container holding other types.  For instance `Vec<U>` is an adapter for
11//! `Vec<T>` if `U` is an adapter for `T` and `Option<U>` is an adapter for
12//! `Option<T>`.  A type is an adapter for itself, `Vec<T>` serializes with
13//! `Vec<T>` as adapter for `Vec<T>`.  [`Same`] is the adapter that uses the
14//! implementations of the type itself (which is useful where the type
15//! cannot be named, like in the derive).
16//!
17//! With the derive, adapters are selected with `#[deser(as = ...)]`.  In the
18//! attribute `_` can be used as a shorthand for [`Same`]:
19//!
20//! ```
21//! use std::collections::BTreeMap;
22//! use std::net::IpAddr;
23//! use deser::{Deserialize, Serialize};
24//! use deser::adapters::DisplayFromStr;
25//!
26//! #[derive(Serialize, Deserialize)]
27//! pub struct Config {
28//!     #[deser(as = DisplayFromStr)]
29//!     listen: IpAddr,
30//!     #[deser(as = Option<DisplayFromStr>)]
31//!     upstream: Option<IpAddr>,
32//!     #[deser(as = BTreeMap<_, Vec<DisplayFromStr>>)]
33//!     aliases: BTreeMap<String, Vec<IpAddr>>,
34//! }
35//! ```
36//!
37//! Missing fields are handled by the adapter (see
38//! [`Deserialize::initial_value`]) so in the example above `upstream` is
39//! optional as `Option<U>` makes missing values `None`.
40//!
41//! `serialize_as` and `deserialize_as` select an adapter for one direction
42//! only.  All three attributes can also be placed on structs, enums and
43//! unions to serialize and deserialize the type itself with an adapter (see
44//! [container adapters][container-adapters]).
45//!
46//! To use an adapter outside of the derive, the [`As`] wrapper can be used.
47//! It holds a value and serializes and deserializes it with an adapter.
48//!
49//! # Provided Adapters
50//!
51//! * [`Same`]: uses [`Serialize`] and [`Deserialize`] of the type itself.
52//! * [`DisplayFromStr`]: serializes with [`Display`](core::fmt::Display) and
53//!   deserializes with [`FromStr`](core::str::FromStr).
54//! * [`FromInto`] and [`TryFromInto`]: convert from and into another type.
55//!   [`FromIntoRef`] and [`TryFromIntoRef`] convert a reference when
56//!   serializing, so the value does not need to be cloned.
57//! * [`DefaultOnError`]: uses the [`Default`] if a value cannot be
58//!   deserialized.
59//! * [`DefaultOnNull`]: uses the [`Default`] if the value is null.
60//! * [`PickFirst`]: tries adapters in order until one of them accepts the
61//!   value (like numbers that are also sent as strings).
62//! * [`OneOrMany`]: a collection that also accepts a single element.
63//! * [`MapAsPairs`] and [`PairsAsMap`]: a map that is written as a
64//!   sequence of key and value pairs and the other way around.
65//! * [`Seconds`], [`Millis`], [`Micros`] and [`Nanos`]: durations and
66//!   timestamps as numbers of a unit.
67//! * [`VecSkipError`] and [`MapSkipError`]: skip elements and entries that
68//!   cannot be deserialized.
69//! * [`Borrowed`]: deserializes a `Cow<str>` or `Cow<[u8]>` borrowed from the
70//!   data if possible.
71//! * [`Flag`]: a `bool` which is set by giving its key (like `?recursive`
72//!   in a query string).
73//! * [`Separated`]: a sequence written as text with a separator (like
74//!   `a,b,c` in an environment variable).
75//! * [`TrimWhitespace`]: trims whitespace from strings before they are
76//!   deserialized.
77//! * [`SkipBlank`]: leaves no value for blank strings, which leaves them
78//!   out of sequences.
79//! * The adapters for bytes: the base64 encodings (for instance
80//!   [`Base64Url`]) and [`BytesFallback`] (see [bytes](#bytes)).
81//! * The standard containers: `Option<U>`, `Result<U, V>`, `Box<U>`,
82//!   `Arc<U>`, `Vec<U>`, `VecDeque<U>`, `LinkedList<U>`, `BinaryHeap<U>`,
83//!   `[U]`, `[U; N]`, `Box<[U]>`, `Arc<[U]>`, `BTreeMap<K, V>`,
84//!   `HashMap<K, V>`, `BTreeSet<U>`, `HashSet<U>` and tuples.  With the
85//!   features of the same names also the collections of `indexmap`,
86//!   `hashbrown`, `smallvec` and `arrayvec` (for instance `IndexMap<K, V>`
87//!   and `SmallVec<[U; N]>`).
88//!
89//! # Bytes
90//!
91//! Bytes (`Vec<u8>`, `[u8; N]`, `&[u8]` and `Cow<[u8]>`) are part of the
92//! data model as [`Atom::Bytes`].  Formats which support
93//! bytes natively (such as CBOR) use that, text formats like JSON and TOML
94//! have to represent them differently.  In deser the convention is:
95//!
96//! * Formats without native bytes write bytes as base64 strings (RFC 4648,
97//!   standard alphabet with padding).  A different
98//!   [`BytesFormat`](crate::BytesFormat) can be configured in the
99//!   [`Context`](crate::Context) (for instance to write sequences of
100//!   integers).
101//! * Types that expect bytes accept a string and decode it.  By default
102//!   this is lenient base64: both the standard and the URL-safe alphabet
103//!   are accepted and the padding is optional.  Sequences of integers are
104//!   always accepted.
105//!
106//! ## Adapters
107//!
108//! How the bytes of an individual value are represented can be changed with
109//! these adapters.  They support `Vec<u8>`, `[u8; N]` and
110//! `Cow<[u8]>` (see [`BytesBuf`]).
111//!
112//! * The encodings (such as [`Base64Url`]) are adapters which represent
113//!   bytes as strings in the encoding in all formats, also in formats with
114//!   native bytes.
115//! * [`BytesFallback`] keeps bytes as bytes in formats with native bytes and
116//!   only picks the representation for formats without them.  This can be
117//!   an encoding (`BytesFallback<Base64Url>`) or sequences of integers
118//!   (`BytesFallback<IntSeq>`).
119//!
120//! ```
121//! use deser::adapters::{Base64Url, Base64UrlNoPad, BytesFallback, IntSeq};
122//! use deser::{Deserialize, Serialize};
123//!
124//! #[derive(Serialize, Deserialize)]
125//! pub struct Blob {
126//!     // base64 in JSON and TOML, bytes in CBOR
127//!     data: Vec<u8>,
128//!     // a URL-safe base64 string in all formats
129//!     #[deser(as = Base64UrlNoPad)]
130//!     token: [u8; 32],
131//!     // URL-safe base64 in JSON and TOML, bytes in CBOR
132//!     #[deser(as = BytesFallback<Base64Url>)]
133//!     signature: Vec<u8>,
134//!     // `[1, 2]` in JSON and TOML, bytes in CBOR
135//!     #[deser(as = BytesFallback<IntSeq>)]
136//!     legacy: Vec<u8>,
137//! }
138//! ```
139//!
140//! When deserializing, all of these accept native bytes and strings in
141//! their encoding.
142//!
143//! ## Encodings
144//!
145//! deser provides the base64 encodings:
146//!
147//! | Encoding           | Description                                        |
148//! |--------------------|----------------------------------------------------|
149//! | [`Base64`]         | base64, standard alphabet with padding             |
150//! | [`Base64NoPad`]    | base64, standard alphabet without padding          |
151//! | [`Base64Url`]      | base64, URL-safe alphabet with padding             |
152//! | [`Base64UrlNoPad`] | base64, URL-safe alphabet without padding          |
153//!
154//! They all decode leniently like the default: both alphabets are accepted
155//! and the padding is optional.
156//!
157//! More encodings (hexadecimal and base32) are provided by
158//! [`deser-encoding`](https://docs.rs/deser-encoding).  Other encodings can
159//! be added by implementing [`BytesEncoding`].  They are adapters like the
160//! encodings provided by deser.
161//!
162//! # Implementing Adapters
163//!
164//! Adapters implement [`Deserialize`] and [`Serialize`] for a type that is
165//! not `Self`.  This example serializes a byte vector into a hex string
166//! (`deser-encoding` provides this as `Hex`, and for bytes implementing
167//! [`BytesEncoding`] is less work):
168//!
169//! ```
170//! use std::borrow::Cow;
171//! use deser::de::{Slot, default_atom};
172//! use deser::ser::Emit;
173//! use deser::{Atom, Deserialize, Error, ErrorKind, Serialize, State};
174//!
175//! pub struct Hex;
176//!
177//! impl Serialize<Vec<u8>> for Hex {
178//!     fn serialize<'a>(
179//!         value: &'a Vec<u8>,
180//!         _state: &mut State,
181//!     ) -> Result<Emit<'a>, Error> {
182//!         let hex: String =
183//!             value.iter().map(|x| format!("{:02x}", x)).collect();
184//!         Ok(Emit::Atom(Atom::Str(hex.into())))
185//!     }
186//! }
187//!
188//! impl<'de> Deserialize<'de, Vec<u8>> for Hex {
189//!     fn deserialize_atom(
190//!         slot: &mut Slot<Vec<u8>, Self>,
191//!         atom: Atom,
192//!         state: &mut State,
193//!     ) -> Result<(), Error> {
194//!         match atom {
195//!             Atom::Str(ref s) if s.len() % 2 == 0 => {
196//!                 let bytes = (0..s.len())
197//!                     .step_by(2)
198//!                     .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
199//!                     .collect::<Result<Vec<_>, _>>()
200//!                     .map_err(|_| {
201//!                         Error::new(ErrorKind::InvalidValue, "invalid hex")
202//!                     })?;
203//!                 slot.set(bytes);
204//!                 Ok(())
205//!             }
206//!             other => default_atom(slot, other, state),
207//!         }
208//!     }
209//!
210//!     fn expecting() -> Cow<'static, str> {
211//!         Cow::Borrowed("hex string")
212//!     }
213//! }
214//!
215//! #[derive(deser::Serialize, deser::Deserialize)]
216//! pub struct Blob {
217//!     #[deser(as = Hex)]
218//!     data: Vec<u8>,
219//!     #[deser(as = Vec<Hex>)]
220//!     parts: Vec<Vec<u8>>,
221//! }
222//! ```
223//!
224//! Implementations generic over adapters (like wrappers of other adapters)
225//! need the adapters to outlive the sinks and emitters that use them.  If
226//! they are not generic over the lifetime of these (like `Vec<A>` for
227//! `Vec<T>`), they require the adapters to be `'static`, which is the case
228//! for marker types.
229//!
230#![cfg_attr(
231    feature = "derive",
232    doc = "[container-adapters]: crate::derive#container-adapters"
233)]
234#![cfg_attr(
235    not(feature = "derive"),
236    doc = "[container-adapters]: https://docs.rs/deser/latest/deser/derive/index.html#container-adapters"
237)]
238
239use alloc::borrow::Cow;
240use alloc::vec::Vec;
241use core::cmp::Ordering;
242use core::fmt;
243use core::hash::{Hash, Hasher};
244use core::marker::PhantomData;
245use core::ops::{Deref, DerefMut};
246
247use crate::State;
248use crate::de::{Deserialize, InlineSeq, OwnedSink, SinkHandle};
249use crate::error::Error;
250use crate::event::{Atom, ContainerShape};
251use crate::ser::{Begin, Describe, Emit, PlainSink, Serialize};
252
253pub(crate) mod bytes;
254mod derived;
255mod forms;
256mod stock;
257mod text;
258mod time;
259
260pub use self::bytes::{
261    Base64, Base64NoPad, Base64Url, Base64UrlNoPad, BytesBuf, BytesEncoding, BytesFallback,
262    BytesFallbackFormat, IntSeq,
263};
264pub use self::derived::Derived;
265#[doc(hidden)]
266pub use self::derived::{DerivedDeserialize, DerivedSerialize};
267pub use self::forms::{
268    MapAsPairs, OneOrMany, OneOrManyForm, PairsAsMap, PickFirst, PreferMany, PreferOne,
269};
270pub use self::stock::{
271    Borrowed, DefaultOnError, DefaultOnNull, DisplayFromStr, Flag, FromInto, FromIntoRef,
272    MapSkipError, TryFromInto, TryFromIntoRef, VecSkipError,
273};
274pub use self::text::{Separated, SkipBlank, TrimWhitespace};
275pub use self::time::{Micros, Millis, Nanos, Seconds, TimeValue, UnitFormat};
276// used for the maps of other crates
277#[allow(unused_imports)]
278pub(crate) use self::stock::skip_map_sink;
279
280/// The adapter that uses the type's own implementation.
281///
282/// This forwards to [`Serialize`] and [`Deserialize`].  In
283/// `#[deser(as = ...)]` attributes `_` can be used instead.
284///
285/// ```
286/// use std::collections::BTreeMap;
287/// use deser::Deserialize;
288/// use deser::adapters::DisplayFromStr;
289///
290/// #[derive(Deserialize)]
291/// pub struct Ports {
292///     // same as BTreeMap<deser::adapters::Same, DisplayFromStr>
293///     #[deser(as = BTreeMap<_, DisplayFromStr>)]
294///     ports: BTreeMap<String, u16>,
295/// }
296/// ```
297pub struct Same;
298
299impl<'de, T: Deserialize<'de>> Deserialize<'de, T> for Same {
300    #[inline]
301    fn deserialize_into<'out>(
302        out: &'out mut Option<T>,
303        state: &mut State,
304    ) -> SinkHandle<'out, 'de> {
305        T::deserialize_into(out, state)
306    }
307
308    fn expecting() -> Cow<'static, str> {
309        T::expecting()
310    }
311
312    #[inline]
313    fn initial_value() -> Option<T> {
314        T::initial_value()
315    }
316
317    #[inline]
318    fn deserialize_update<'out>(value: &'out mut T, state: &mut State) -> SinkHandle<'out, 'de> {
319        T::deserialize_update(value, state)
320    }
321
322    #[inline]
323    fn __private_atom_into(
324        out: &mut Option<T>,
325        atom: Atom,
326        state: &mut State,
327    ) -> Result<(), Error> {
328        T::__private_atom_into(out, atom, state)
329    }
330
331    #[inline]
332    fn __private_borrowed_atom_into(
333        out: &mut Option<T>,
334        atom: Atom<'de>,
335        state: &mut State,
336    ) -> Result<(), Error> {
337        T::__private_borrowed_atom_into(out, atom, state)
338    }
339
340    #[inline]
341    fn __private_is_bytes() -> bool {
342        T::__private_is_bytes()
343    }
344
345    #[inline]
346    fn __private_vec_from_bytes(bytes: Vec<u8>) -> Option<Vec<T>> {
347        T::__private_vec_from_bytes(bytes)
348    }
349
350    #[inline]
351    fn __private_array_from_bytes<const N: usize>(bytes: &[u8]) -> Option<[T; N]> {
352        T::__private_array_from_bytes(bytes)
353    }
354
355    #[inline]
356    fn __private_atom_default() -> Option<T> {
357        T::__private_atom_default()
358    }
359
360    #[inline]
361    fn __private_inline_seq() -> Option<InlineSeq<T>> {
362        T::__private_inline_seq()
363    }
364
365    #[inline(always)]
366    fn __private_raw() -> Option<&'static crate::ext::RawFormatInfo> {
367        T::__private_raw()
368    }
369
370    fn describe_type(d: &mut dyn Describe) {
371        T::describe_type(d)
372    }
373
374    #[inline]
375    fn __private_collects() -> bool {
376        T::__private_collects()
377    }
378
379    #[inline]
380    fn __private_collect_into<'out>(
381        out: &'out mut Option<T>,
382        state: &mut State,
383    ) -> SinkHandle<'out, 'de> {
384        T::__private_collect_into(out, state)
385    }
386
387    #[inline]
388    fn __private_collect_update<'out>(
389        value: &'out mut T,
390        first: bool,
391        state: &mut State,
392    ) -> SinkHandle<'out, 'de> {
393        T::__private_collect_update(value, first, state)
394    }
395
396    #[inline]
397    fn __private_collect_empty() -> Option<T> {
398        T::__private_collect_empty()
399    }
400}
401
402impl<T: Serialize + ?Sized> Serialize<T> for Same {
403    #[inline]
404    fn serialize<'a>(value: &'a T, state: &mut State) -> Result<Emit<'a>, Error> {
405        T::serialize(value, state)
406    }
407
408    #[inline]
409    fn finish(value: &T, state: &mut State) -> Result<(), Error> {
410        T::finish(value, state)
411    }
412
413    #[inline]
414    fn is_optional(value: &T) -> bool {
415        T::is_optional(value)
416    }
417
418    #[inline]
419    fn container_shape(value: &T) -> ContainerShape {
420        T::container_shape(value)
421    }
422
423    fn describe(value: &T, d: &mut dyn Describe) {
424        T::describe(value, d)
425    }
426
427    #[inline]
428    fn __private_begin<'a>(value: &'a T, state: &mut State) -> Result<Begin<'a>, Error> {
429        T::__private_begin(value, state)
430    }
431
432    #[inline]
433    fn __private_is_plain() -> bool {
434        T::__private_is_plain()
435    }
436
437    #[inline]
438    fn __private_is_plain_value(value: &T) -> bool {
439        T::__private_is_plain_value(value)
440    }
441
442    #[inline]
443    fn __private_emit_plain(value: &T, sink: &mut dyn PlainSink) -> Result<(), Error> {
444        T::__private_emit_plain(value, sink)
445    }
446
447    #[inline]
448    fn __private_plain_cost(value: &T, budget: usize) -> Option<usize> {
449        T::__private_plain_cost(value, budget)
450    }
451
452    #[inline]
453    fn __private_slice_as_bytes(val: &[T]) -> Option<Cow<'_, [u8]>>
454    where
455        T: Sized,
456    {
457        T::__private_slice_as_bytes(val)
458    }
459}
460
461/// Holds a value that serializes and deserializes with an adapter.
462///
463/// This implements [`Serialize`] and [`Deserialize`] with the adapter `A`.
464/// It's useful to use adapters in places where `#[deser(as = ...)]` is not
465/// available.  The wrapper dereferences to the value.
466///
467/// ```
468/// use deser::adapters::{As, DisplayFromStr};
469///
470/// let values: Vec<As<u32, DisplayFromStr>> = vec![As::new(1), As::new(2)];
471/// assert_eq!(*values[0], 1);
472/// ```
473#[repr(transparent)]
474pub struct As<T, A> {
475    value: T,
476    _marker: PhantomData<fn() -> A>,
477}
478
479impl<T, A> As<T, A> {
480    /// Wraps a value.
481    #[inline(always)]
482    pub fn new(value: T) -> As<T, A> {
483        As {
484            value,
485            _marker: PhantomData,
486        }
487    }
488
489    /// Returns the wrapped value.
490    #[inline(always)]
491    pub fn into_inner(self) -> T {
492        self.value
493    }
494}
495
496impl<T, A> From<T> for As<T, A> {
497    fn from(value: T) -> As<T, A> {
498        As::new(value)
499    }
500}
501
502impl<T, A> Deref for As<T, A> {
503    type Target = T;
504
505    fn deref(&self) -> &T {
506        &self.value
507    }
508}
509
510impl<T, A> DerefMut for As<T, A> {
511    fn deref_mut(&mut self) -> &mut T {
512        &mut self.value
513    }
514}
515
516impl<T: fmt::Debug, A> fmt::Debug for As<T, A> {
517    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
518        fmt::Debug::fmt(&self.value, f)
519    }
520}
521
522impl<T: Clone, A> Clone for As<T, A> {
523    fn clone(&self) -> Self {
524        As::new(self.value.clone())
525    }
526}
527
528impl<T: Copy, A> Copy for As<T, A> {}
529
530impl<T: Default, A> Default for As<T, A> {
531    fn default() -> Self {
532        As::new(T::default())
533    }
534}
535
536impl<T: PartialEq, A> PartialEq for As<T, A> {
537    fn eq(&self, other: &Self) -> bool {
538        self.value == other.value
539    }
540}
541
542impl<T: Eq, A> Eq for As<T, A> {}
543
544impl<T: PartialOrd, A> PartialOrd for As<T, A> {
545    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
546        self.value.partial_cmp(&other.value)
547    }
548}
549
550impl<T: Ord, A> Ord for As<T, A> {
551    fn cmp(&self, other: &Self) -> Ordering {
552        self.value.cmp(&other.value)
553    }
554}
555
556impl<T: Hash, A> Hash for As<T, A> {
557    fn hash<H: Hasher>(&self, state: &mut H) {
558        self.value.hash(state)
559    }
560}
561
562impl<'de, T: Send, A: Deserialize<'de, T>> Deserialize<'de> for As<T, A> {
563    fn deserialize_into<'out>(
564        out: &'out mut Option<Self>,
565        state: &mut State,
566    ) -> SinkHandle<'out, 'de> {
567        crate::de::mapped::MappedSink::handle(
568            out,
569            OwnedSink::deserialize_as::<A>(state),
570            |value| Ok(As::new(value)),
571            state,
572        )
573    }
574
575    fn expecting() -> Cow<'static, str> {
576        A::expecting()
577    }
578
579    fn initial_value() -> Option<Self> {
580        A::initial_value().map(As::new)
581    }
582
583    #[inline]
584    fn __private_atom_into(
585        out: &mut Option<Self>,
586        atom: Atom,
587        state: &mut State,
588    ) -> Result<(), Error> {
589        let mut inner = None;
590        A::__private_atom_into(&mut inner, atom, state)?;
591        *out = inner.map(As::new);
592        Ok(())
593    }
594
595    #[inline]
596    fn __private_borrowed_atom_into(
597        out: &mut Option<Self>,
598        atom: Atom<'de>,
599        state: &mut State,
600    ) -> Result<(), Error> {
601        let mut inner = None;
602        A::__private_borrowed_atom_into(&mut inner, atom, state)?;
603        *out = inner.map(As::new);
604        Ok(())
605    }
606
607    #[inline]
608    fn __private_is_bytes() -> bool {
609        A::__private_is_bytes()
610    }
611
612    #[inline(always)]
613    fn __private_raw() -> Option<&'static crate::ext::RawFormatInfo> {
614        A::__private_raw()
615    }
616
617    fn describe_type(d: &mut dyn Describe) {
618        A::describe_type(d)
619    }
620
621    fn __private_vec_from_bytes(bytes: Vec<u8>) -> Option<Vec<Self>> {
622        A::__private_vec_from_bytes(bytes).map(|x| x.into_iter().map(As::new).collect())
623    }
624
625    fn __private_array_from_bytes<const N: usize>(bytes: &[u8]) -> Option<[Self; N]> {
626        A::__private_array_from_bytes::<N>(bytes).map(|x| x.map(As::new))
627    }
628}
629
630impl<T: Sync, A: Serialize<T>> Serialize for As<T, A> {
631    #[inline]
632    fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
633        A::serialize(&value.value, state)
634    }
635
636    #[inline]
637    fn finish(value: &Self, state: &mut State) -> Result<(), Error> {
638        A::finish(&value.value, state)
639    }
640
641    #[inline]
642    fn is_optional(value: &Self) -> bool {
643        A::is_optional(&value.value)
644    }
645
646    #[inline]
647    fn container_shape(value: &Self) -> ContainerShape {
648        A::container_shape(&value.value)
649    }
650
651    #[inline]
652    fn describe(value: &Self, d: &mut dyn Describe) {
653        A::describe(&value.value, d)
654    }
655
656    #[inline]
657    fn __private_begin<'a>(value: &'a Self, state: &mut State) -> Result<Begin<'a>, Error> {
658        A::__private_begin(&value.value, state)
659    }
660
661    #[inline]
662    fn __private_is_plain() -> bool {
663        A::__private_is_plain()
664    }
665
666    #[inline]
667    fn __private_is_plain_value(value: &Self) -> bool {
668        A::__private_is_plain_value(&value.value)
669    }
670
671    #[inline]
672    fn __private_emit_plain(value: &Self, sink: &mut dyn PlainSink) -> Result<(), Error> {
673        A::__private_emit_plain(&value.value, sink)
674    }
675
676    #[inline]
677    fn __private_plain_cost(value: &Self, budget: usize) -> Option<usize> {
678        A::__private_plain_cost(&value.value, budget)
679    }
680
681    #[inline]
682    fn __private_slice_as_bytes(val: &[Self]) -> Option<Cow<'_, [u8]>> {
683        // SAFETY: the wrapper is transparent over `T` (the marker is zero
684        // sized and has an alignment of one).
685        let val = unsafe { &*(val as *const [Self] as *const [T]) };
686        A::__private_slice_as_bytes(val)
687    }
688}