Skip to main content

deser_core/ser/
handle.rs

1//! References to values that are serialized with their type erased.
2use alloc::boxed::Box;
3use core::fmt;
4use core::marker::PhantomData;
5
6use crate::State;
7use crate::error::Error;
8use crate::event::ContainerShape;
9use crate::ser::boxed::{self, Boxed};
10use crate::ser::{Begin, Describe, Emit, PlainSink, Serialize};
11
12/// A value that serializes with an adapter.
13///
14/// The wrapper is transparent over the value, it can be created from a
15/// reference to the value without copying it.  The adapter is only a
16/// marker, it's never instantiated.
17#[repr(transparent)]
18pub(crate) struct Adapted<A, T: ?Sized> {
19    _marker: PhantomData<fn() -> A>,
20    value: T,
21}
22
23impl<A, T: ?Sized> Adapted<A, T> {
24    /// Wraps a reference to a value.
25    #[inline(always)]
26    pub(crate) fn new(value: &T) -> &Adapted<A, T> {
27        // SAFETY: the wrapper is transparent over `T` (the marker is zero
28        // sized and has an alignment of one).
29        unsafe { &*(value as *const T as *const Adapted<A, T>) }
30    }
31
32    /// Returns a pointer to the wrapper of a value.
33    ///
34    /// Unlike a reference, the pointer does not require the adapter to
35    /// outlive it.
36    #[inline(always)]
37    pub(crate) fn ptr(value: &T) -> *const Adapted<A, T> {
38        value as *const T as *const Adapted<A, T>
39    }
40
41    /// Returns the wrapped value.
42    #[inline(always)]
43    pub(crate) fn get(&self) -> &T {
44        &self.value
45    }
46}
47
48impl<A, T> Adapted<A, T> {
49    /// Wraps a value.
50    #[inline(always)]
51    fn owned(value: T) -> Adapted<A, T> {
52        Adapted {
53            _marker: PhantomData,
54            value,
55        }
56    }
57}
58
59/// A value that is serialized, with its type erased.
60///
61/// This is the trait object behind [`SerializeRef`] and
62/// [`SerializeHandle`], it's implemented for [`Adapted`].
63pub(crate) trait Erased: Sync {
64    fn erased_serialize(&self, state: &mut State) -> Result<Emit<'_>, Error>;
65    fn erased_finish(&self, state: &mut State) -> Result<(), Error>;
66    fn erased_is_optional(&self) -> bool;
67    fn erased_container_shape(&self) -> ContainerShape;
68    fn erased_describe(&self, d: &mut dyn Describe);
69    fn erased_begin(&self, state: &mut State) -> Result<Begin<'_>, Error>;
70    fn erased_is_plain_value(&self) -> bool;
71    fn erased_emit_plain(&self, sink: &mut dyn PlainSink) -> Result<(), Error>;
72    fn erased_plain_cost(&self, budget: usize) -> Option<usize>;
73}
74
75impl<A: Serialize<T>, T: ?Sized + Sync> Erased for Adapted<A, T> {
76    fn erased_serialize(&self, state: &mut State) -> Result<Emit<'_>, Error> {
77        A::serialize(&self.value, state)
78    }
79
80    fn erased_finish(&self, state: &mut State) -> Result<(), Error> {
81        A::finish(&self.value, state)
82    }
83
84    fn erased_is_optional(&self) -> bool {
85        A::is_optional(&self.value)
86    }
87
88    fn erased_container_shape(&self) -> ContainerShape {
89        A::container_shape(&self.value)
90    }
91
92    fn erased_describe(&self, d: &mut dyn Describe) {
93        A::describe(&self.value, d)
94    }
95
96    fn erased_begin(&self, state: &mut State) -> Result<Begin<'_>, Error> {
97        A::__private_begin(&self.value, state)
98    }
99
100    fn erased_is_plain_value(&self) -> bool {
101        A::__private_is_plain_value(&self.value)
102    }
103
104    fn erased_emit_plain(&self, sink: &mut dyn PlainSink) -> Result<(), Error> {
105        A::__private_emit_plain(&self.value, sink)
106    }
107
108    fn erased_plain_cost(&self, budget: usize) -> Option<usize> {
109        A::__private_plain_cost(&self.value, budget)
110    }
111}
112
113/// Converts a pointer to a wrapper into a trait object.
114///
115/// The compiler requires the wrapper, and with it the adapter, to outlive
116/// the trait object (even a reference to it).  The adapter always does
117/// (it's the type of the value or a marker type) but this cannot be
118/// expressed for adapters that are type parameters, like the element
119/// adapter of `Vec<A>`.
120///
121/// # Safety
122///
123/// The pointer must be valid for `'a`.  The parts of `S` that do not
124/// outlive `'a` must be adapters that are only used for their functions
125/// (which cannot hold borrowed data), `S` holds no values of them.
126#[inline(always)]
127pub(crate) unsafe fn erase_unbounded<'a, S: Erased>(value: *const S) -> &'a (dyn Erased + 'a) {
128    // like every type parameter, `S` outlives this function
129    let value: *const (dyn Erased + '_) = value;
130    // SAFETY: guaranteed by the caller
131    unsafe { &*core::mem::transmute::<*const (dyn Erased + '_), *const (dyn Erased + 'a)>(value) }
132}
133
134/// A reference to a value that is serialized.
135///
136/// This is the type erased form of a [`Serialize`] value (and an adapter
137/// if it's serialized with one).  The serializers of the data formats
138/// receive the values as references, for instance from the
139/// [`SerializeDriver`](crate::ser::SerializeDriver).  The methods of the
140/// reference invoke the ones of [`Serialize`].
141///
142/// ```
143/// use deser::adapters::DisplayFromStr;
144/// use deser::ser::SerializeRef;
145///
146/// let value = 42u32;
147/// assert!(!SerializeRef::new(&value).is_optional());
148///
149/// // serializes as string
150/// let value = SerializeRef::serialize_as::<DisplayFromStr, _>(&value);
151/// ```
152///
153/// Deserialization has no equivalent: values are type erased by creating
154/// their [`Sink`](crate::de::Sink) (see
155/// [`Deserialize::deserialize_into`](crate::de::Deserialize::deserialize_into)),
156/// which is already in the middle of deserializing them.
157#[derive(Clone, Copy)]
158pub struct SerializeRef<'a> {
159    value: &'a (dyn Erased + 'a),
160}
161
162impl<'a> SerializeRef<'a> {
163    /// Creates a reference to a value.
164    #[inline(always)]
165    pub fn new<T: Serialize>(value: &'a T) -> SerializeRef<'a> {
166        SerializeRef {
167            value: Adapted::<T, T>::new(value),
168        }
169    }
170
171    /// Creates a reference to a value that is serialized with an adapter.
172    ///
173    /// See [`adapters`](crate::adapters).
174    #[inline(always)]
175    pub fn serialize_as<A: Serialize<T>, T: Sync>(value: &'a T) -> SerializeRef<'a> {
176        SerializeRef {
177            // SAFETY: the wrapper is valid for 'a (it's the value), it only
178            // holds a marker of the adapter
179            value: unsafe { erase_unbounded(Adapted::<A, T>::ptr(value)) },
180        }
181    }
182
183    /// Creates a reference from a trait object.
184    #[inline(always)]
185    pub(crate) fn from_dyn(value: &'a (dyn Erased + 'a)) -> SerializeRef<'a> {
186        SerializeRef { value }
187    }
188
189    /// Returns the trait object.
190    #[inline(always)]
191    pub(crate) fn as_dyn(self) -> &'a (dyn Erased + 'a) {
192        self.value
193    }
194
195    /// Serializes the value (see [`Serialize::serialize`]).
196    #[inline]
197    pub fn serialize(self, state: &mut State) -> Result<Emit<'a>, Error> {
198        self.value.erased_serialize(state)
199    }
200
201    /// Invoked after the serialization finished (see [`Serialize::finish`]).
202    #[inline]
203    pub fn finish(self, state: &mut State) -> Result<(), Error> {
204        self.value.erased_finish(state)
205    }
206
207    /// Checks if the value is optional (see [`Serialize::is_optional`]).
208    #[inline]
209    pub fn is_optional(self) -> bool {
210        self.value.erased_is_optional()
211    }
212
213    /// Returns the shape of the value (see [`Serialize::container_shape`]).
214    #[inline]
215    pub fn container_shape(self) -> ContainerShape {
216        self.value.erased_container_shape()
217    }
218
219    /// Describes the Rust shape of the value (see [`Serialize::describe`]).
220    pub fn describe(self, d: &mut dyn Describe) {
221        self.value.erased_describe(d)
222    }
223
224    /// Begins the serialization (see `Serialize::__private_begin`).
225    #[inline]
226    pub(crate) fn begin(self, state: &mut State) -> Result<Begin<'a>, Error> {
227        self.value.erased_begin(state)
228    }
229
230    /// Returns `true` if the value is plain (see
231    /// `Serialize::__private_is_plain_value`).
232    #[inline]
233    pub(crate) fn is_plain_value(self) -> bool {
234        self.value.erased_is_plain_value()
235    }
236
237    /// Emits the events of a plain value (see
238    /// `Serialize::__private_emit_plain`).
239    #[inline]
240    pub(crate) fn emit_plain(self, sink: &mut dyn PlainSink) -> Result<(), Error> {
241        self.value.erased_emit_plain(sink)
242    }
243
244    /// Returns the budget that is left after emitting the plain value (see
245    /// `Serialize::__private_plain_cost`).
246    #[inline]
247    pub(crate) fn plain_cost(self, budget: usize) -> Option<usize> {
248        self.value.erased_plain_cost(budget)
249    }
250}
251
252impl fmt::Debug for SerializeRef<'_> {
253    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254        f.debug_struct("SerializeRef").finish_non_exhaustive()
255    }
256}
257
258impl<'a, T: Serialize> From<&'a T> for SerializeRef<'a> {
259    #[inline(always)]
260    fn from(value: &'a T) -> SerializeRef<'a> {
261        SerializeRef::new(value)
262    }
263}
264
265impl Serialize for SerializeRef<'_> {
266    #[inline]
267    fn serialize<'b>(value: &'b Self, state: &mut State) -> Result<Emit<'b>, Error> {
268        value.serialize(state)
269    }
270
271    #[inline]
272    fn finish(value: &Self, state: &mut State) -> Result<(), Error> {
273        (*value).finish(state)
274    }
275
276    #[inline]
277    fn is_optional(value: &Self) -> bool {
278        (*value).is_optional()
279    }
280
281    #[inline]
282    fn container_shape(value: &Self) -> ContainerShape {
283        (*value).container_shape()
284    }
285
286    fn describe(value: &Self, d: &mut dyn Describe) {
287        (*value).describe(d)
288    }
289
290    #[inline]
291    fn __private_begin<'b>(value: &'b Self, state: &mut State) -> Result<Begin<'b>, Error> {
292        value.begin(state)
293    }
294
295    #[inline]
296    fn __private_is_plain_value(value: &Self) -> bool {
297        value.is_plain_value()
298    }
299
300    #[inline]
301    fn __private_emit_plain(value: &Self, sink: &mut dyn PlainSink) -> Result<(), Error> {
302        value.emit_plain(sink)
303    }
304
305    #[inline]
306    fn __private_plain_cost(value: &Self, budget: usize) -> Option<usize> {
307        value.plain_cost(budget)
308    }
309}
310
311/// A handle to a value that is serialized.
312///
313/// During serialization it's common to be in a situation where one needs
314/// to return a locally constructed [`Serialize`].  This is where
315/// [`SerializeHandle`] comes in.  The handle either borrows the value (see
316/// [`to`](Self::to) and [`SerializeRef`]) or owns it (see
317/// [`arena`](Self::arena) and [`heap`](Self::heap)).
318///
319/// Unlike the [`SinkHandle`](crate::de::SinkHandle) of deserialization,
320/// which holds a sink that is already deserializing a value, this holds a
321/// value that is not serialized yet.  The serialization equivalent of a
322/// sink is an emitter in a [`Emit`].  The constructors line up:
323/// [`to`](Self::to) borrows, [`arena`](Self::arena) and
324/// [`heap`](Self::heap) own in the same way for both handles.
325pub struct SerializeHandle<'a>(pub(crate) HandleInner<'a>);
326
327pub(crate) enum HandleInner<'a> {
328    Borrowed(SerializeRef<'a>),
329    // owned values are `Send` so that the serialization can move between
330    // threads
331    Owned(Boxed<dyn Erased + Send + 'a>),
332}
333
334impl<'a> SerializeHandle<'a> {
335    /// Creates a borrowed handle to a value.
336    #[inline(always)]
337    pub fn to<S: Serialize>(value: &'a S) -> SerializeHandle<'a> {
338        SerializeHandle(HandleInner::Borrowed(SerializeRef::new(value)))
339    }
340
341    /// Creates an owned handle to a value in the arena of the state.
342    ///
343    /// This is how owned values are typically created (for instance for
344    /// [`Emit::Forward`]), see [`Boxed`].
345    #[inline(always)]
346    pub fn arena<S: Serialize + Send + 'a>(value: S, state: &mut State) -> SerializeHandle<'a> {
347        SerializeHandle(HandleInner::Owned(boxed::unsize(
348            Boxed::arena(Adapted::<S, S>::owned(value), state),
349            |x| x as *mut (dyn Erased + Send + 'a),
350        )))
351    }
352
353    /// Creates an owned handle to a value on the heap.
354    ///
355    /// Unlike [`arena`](Self::arena) the value does not need a state and is
356    /// independent of any serialization.
357    pub fn heap<S: Serialize + Send + 'a>(value: S) -> SerializeHandle<'a> {
358        SerializeHandle(HandleInner::Owned(Boxed::from(
359            Box::new(Adapted::<S, S>::owned(value)) as Box<dyn Erased + Send + 'a>,
360        )))
361    }
362
363    /// Returns a reference to the value.
364    #[inline(always)]
365    pub fn get(&self) -> SerializeRef<'_> {
366        match self.0 {
367            HandleInner::Borrowed(value) => value,
368            HandleInner::Owned(ref value) => SerializeRef::from_dyn(&**value),
369        }
370    }
371}
372
373impl<'a> From<SerializeRef<'a>> for SerializeHandle<'a> {
374    #[inline(always)]
375    fn from(value: SerializeRef<'a>) -> SerializeHandle<'a> {
376        SerializeHandle(HandleInner::Borrowed(value))
377    }
378}
379
380impl fmt::Debug for SerializeHandle<'_> {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        f.debug_struct("SerializeHandle").finish_non_exhaustive()
383    }
384}
385
386impl Serialize for SerializeHandle<'_> {
387    #[inline]
388    fn serialize<'b>(value: &'b Self, state: &mut State) -> Result<Emit<'b>, Error> {
389        value.get().serialize(state)
390    }
391
392    #[inline]
393    fn finish(value: &Self, state: &mut State) -> Result<(), Error> {
394        value.get().finish(state)
395    }
396
397    #[inline]
398    fn is_optional(value: &Self) -> bool {
399        value.get().is_optional()
400    }
401
402    #[inline]
403    fn container_shape(value: &Self) -> ContainerShape {
404        value.get().container_shape()
405    }
406
407    fn describe(value: &Self, d: &mut dyn Describe) {
408        value.get().describe(d)
409    }
410
411    #[inline]
412    fn __private_begin<'b>(value: &'b Self, state: &mut State) -> Result<Begin<'b>, Error> {
413        value.get().begin(state)
414    }
415
416    #[inline]
417    fn __private_is_plain_value(value: &Self) -> bool {
418        value.get().is_plain_value()
419    }
420
421    #[inline]
422    fn __private_emit_plain(value: &Self, sink: &mut dyn PlainSink) -> Result<(), Error> {
423        value.get().emit_plain(sink)
424    }
425
426    #[inline]
427    fn __private_plain_cost(value: &Self, budget: usize) -> Option<usize> {
428        value.get().plain_cost(budget)
429    }
430}