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