Skip to main content

deser_core/ext/
raw.rs

1use alloc::borrow::Cow;
2use alloc::vec::Vec;
3use core::any::Any;
4use core::fmt;
5use core::marker::PhantomData;
6
7use crate::State;
8use crate::adapters::Borrowed;
9use crate::de::recording::Capture;
10use crate::de::{Deserialize, DeserializeDriver, RecordBuf, Sink, SinkHandle};
11use crate::error::{Error, ErrorKind};
12use crate::event::Atom;
13use crate::ext::{BorrowedExtension, ExtValue};
14use crate::ser::{Emit, Serialize, SerializeHandle, SerializeRef};
15
16/// A data format whose encoded values can be held by [`Raw`].
17///
18/// This is implemented by a type of the crate of the format that stands
19/// for the format (for instance `deser_json::Json`).  The format is
20/// described at runtime by a [`RawFormatInfo`].
21///
22/// # Passing on the Input of Values
23///
24/// Raw values of a format that is deserialized from the same format hold
25/// the input of the value, and serializers of the format write them as
26/// they are.  For this the format:
27///
28/// * calls [`State::declare_raw_format`](crate::State::declare_raw_format) with
29///   its [`RawFormatId`] in the deserializer (before the first event, it
30///   returns the description of the format if the top-level value is
31///   wanted as raw value) and in the serializer (before the first value).
32/// * checks with [`Error::is_raw_request`](crate::Error::is_raw_request)
33///   whether the result of an event requests the next value as raw value
34///   and takes the description of the format with
35///   [`State::take_raw_request`](crate::State::take_raw_request).
36/// * checks that the description has the [`RawFormatId`] of the format
37///   (requests can be for raw values of any format, they are an error
38///   then), validates a value that is wanted as raw value and emits its
39///   input as [`RawInput`] (an [`Atom::Ext`]) with that description
40///   rather than its events.
41/// * writes the [`RawInput`] of its format as it is when serializing
42///   (see [`RawInput::is_format`]).
43///
44/// The parser and the serializer only refer to the [`RawFormatId`]: the
45/// functions of the format (like `replay`, which brings in its parser)
46/// are only in programs that use its raw values.
47///
48/// Formats that do not do this still have raw values: the values are
49/// encoded with the format then.
50pub trait RawFormat: 'static {
51    /// Returns the description of the format.
52    ///
53    /// This must always return the same static: formats are identified by
54    /// the address of their description.
55    fn info() -> &'static RawFormatInfo;
56}
57
58/// A [`RawFormat`] whose encoding is text.
59///
60/// [`Raw`] values of such formats can be accessed as strings (see
61/// [`Raw::get`]).
62///
63/// # Safety
64///
65/// The format must be described as text (see [`RawFormatId::new`]): its
66/// parser only passes on and its encoder only produces valid UTF-8.
67pub unsafe trait TextRawFormat: RawFormat {}
68
69/// Identifies a [`RawFormat`].
70///
71/// Formats are identified by the address of a static of this type.  Unlike
72/// the [`RawFormatInfo`] of the format it holds no functions: formats
73/// declare which raw values they pass on with it (see
74/// [`State::declare_raw_format`](crate::State::declare_raw_format)), so a program
75/// only contains the functions of the format (like its parser for
76/// `replay`) if it uses its raw values.
77pub struct RawFormatId {
78    name: &'static str,
79    is_text: bool,
80}
81
82impl RawFormatId {
83    /// Creates the identity of a format.
84    ///
85    /// * `name` is the name of the format (like `"json"`).
86    /// * `is_text` is `true` if the encoding is text.  The encoded values
87    ///   must then be valid UTF-8.
88    pub const fn new(name: &'static str, is_text: bool) -> RawFormatId {
89        RawFormatId { name, is_text }
90    }
91
92    /// Returns the name of the format.
93    pub fn name(&self) -> &'static str {
94        self.name
95    }
96
97    /// Returns `true` if the encoding of the format is text.
98    pub fn is_text(&self) -> bool {
99        self.is_text
100    }
101}
102
103impl fmt::Debug for RawFormatId {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        f.debug_tuple("RawFormatId").field(&self.name).finish()
106    }
107}
108
109/// Describes a [`RawFormat`] at runtime.
110///
111/// Formats that can pass on the input of values define a static of this
112/// type.  It travels with the input of values (see [`RawInput`]) so that
113/// code which does not know the format can still parse it.  Formats are
114/// identified by their [`RawFormatId`].
115pub struct RawFormatInfo {
116    id: &'static RawFormatId,
117    replay: for<'de> fn(&'de [u8], &mut DeserializeDriver<'_, 'de>) -> Result<(), Error>,
118    encode: fn(SerializeRef<'_>) -> Result<Vec<u8>, Error>,
119    fallback: for<'v> fn(&'v [u8]) -> Atom<'v>,
120    data: Option<&'static (dyn Any + Send + Sync)>,
121}
122
123impl RawFormatInfo {
124    /// Creates the description of a format.
125    ///
126    /// * `id` identifies the format.
127    /// * `replay` parses a value and emits its events into the driver.
128    /// * `encode` encodes a value.
129    /// * `fallback` returns the fallback atom of an encoded value (see
130    ///   [`Extension::fallback`](crate::ext::Extension::fallback)).  It
131    ///   must be [`Atom::Null`] for null, so that optionals are `None` for
132    ///   it, and must not be an extension value.
133    pub const fn new(
134        id: &'static RawFormatId,
135        replay: for<'de> fn(&'de [u8], &mut DeserializeDriver<'_, 'de>) -> Result<(), Error>,
136        encode: fn(SerializeRef<'_>) -> Result<Vec<u8>, Error>,
137        fallback: for<'v> fn(&'v [u8]) -> Atom<'v>,
138    ) -> RawFormatInfo {
139        RawFormatInfo {
140            id,
141            replay,
142            encode,
143            fallback,
144            data: None,
145        }
146    }
147
148    /// Attaches data of the format to the description.
149    ///
150    /// The format gets it back from the description of raw values that are
151    /// requested (see [`data`](Self::data)).  Formats keep what only
152    /// programs that use their raw values need here (like the scanner of
153    /// raw values in the parser): as only raw values refer to the
154    /// description, other programs do not contain it.
155    pub const fn set_data(&mut self, data: &'static (dyn Any + Send + Sync)) {
156        self.data = Some(data);
157    }
158
159    /// Returns the data of the format (see [`set_data`](Self::set_data)).
160    pub fn data(&self) -> Option<&'static (dyn Any + Send + Sync)> {
161        self.data
162    }
163
164    /// Returns the identity of the format.
165    pub fn id(&self) -> &'static RawFormatId {
166        self.id
167    }
168
169    /// Returns the name of the format.
170    pub fn name(&self) -> &'static str {
171        self.id.name
172    }
173
174    /// Returns `true` if the encoding of the format is text.
175    pub fn is_text(&self) -> bool {
176        self.id.is_text
177    }
178
179    /// Records an encoded value.
180    fn record<'a>(&self, bytes: &'a [u8]) -> Result<RecordBuf<'a>, Error> {
181        let mut recording = RecordBuf::new();
182        {
183            let mut driver = DeserializeDriver::from_fn(|state| recording.recorder(state));
184            (self.replay)(bytes, &mut driver)?;
185        }
186        Ok(recording)
187    }
188}
189
190impl fmt::Debug for RawFormatInfo {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        f.debug_tuple("RawFormatInfo").field(&self.id.name).finish()
193    }
194}
195
196/// Returns `true` if two descriptions are the same format.
197#[inline(always)]
198fn same_format(a: &'static RawFormatInfo, b: &'static RawFormatInfo) -> bool {
199    core::ptr::eq(a.id, b.id)
200}
201
202/// The encoded input of a value.
203///
204/// This is a well-known borrowing extension (see [`ext`](crate::ext)) which
205/// carries the encoding of a value between formats and [`Raw`] values:
206///
207/// * formats emit it for values that are requested as raw values (the
208///   values of [`Raw`] types).  They validate the value and pass on its
209///   input instead of its events.
210/// * [`Raw`] values emit it when they are serialized and the serializer
211///   writes the format as it is (see [`State::declare_raw_format`]).
212///
213/// It knows its format, so it's parsed into its value where it ends up in
214/// something that does not know it (for instance when a recording that
215/// holds it is serialized).
216#[derive(Clone)]
217pub struct RawInput<'a> {
218    bytes: Cow<'a, [u8]>,
219    format: &'static RawFormatInfo,
220}
221
222impl<'a> RawInput<'a> {
223    /// Creates the input of a value.
224    ///
225    /// # Safety
226    ///
227    /// The input must be a single, valid value of the format.  If the
228    /// format is text, it must be valid UTF-8.  Serializers of the format
229    /// write the input as it is.
230    ///
231    /// Descriptions of formats can be created by anybody (with the
232    /// identity of any format) and requests for raw values can be for any
233    /// format: formats must check that the description has the identity
234    /// of their own format (see
235    /// [`State::take_raw_request`](crate::State::take_raw_request)) rather
236    /// than rely on where it comes from or on its
237    /// [`data`](RawFormatInfo::data).
238    pub unsafe fn new<B: Into<Cow<'a, [u8]>>>(
239        bytes: B,
240        format: &'static RawFormatInfo,
241    ) -> RawInput<'a> {
242        let bytes = bytes.into();
243        debug_assert!(!format.is_text() || core::str::from_utf8(&bytes).is_ok());
244        RawInput { bytes, format }
245    }
246
247    /// Returns the encoded value.
248    pub fn as_bytes(&self) -> &[u8] {
249        &self.bytes
250    }
251
252    /// Returns the encoded value as text if the format is text.
253    pub fn as_str(&self) -> Option<&str> {
254        // SAFETY: the input of text formats is valid UTF-8, see `new`
255        self.format
256            .is_text()
257            .then(|| unsafe { core::str::from_utf8_unchecked(&self.bytes) })
258    }
259
260    /// Returns the format of the value.
261    pub fn format(&self) -> &'static RawFormatInfo {
262        self.format
263    }
264
265    /// Returns `true` if the value is of the format `F`.
266    pub fn is<F: RawFormat>(&self) -> bool {
267        same_format(self.format, F::info())
268    }
269
270    /// Returns `true` if the value is of the format with the identity.
271    ///
272    /// Serializers check with this whether they write a value as it is
273    /// (unlike [`is`](Self::is), this does not refer to the functions of
274    /// the format).
275    pub fn is_format(&self, id: &'static RawFormatId) -> bool {
276        core::ptr::eq(self.format.id, id)
277    }
278
279    /// Detaches the input from the data it borrows.
280    pub fn into_owned(self) -> RawInput<'static> {
281        RawInput {
282            bytes: Cow::Owned(self.bytes.into_owned()),
283            format: self.format,
284        }
285    }
286
287    /// Records the value.
288    pub fn record(&self) -> Result<RecordBuf<'_>, Error> {
289        self.format.record(&self.bytes)
290    }
291
292    /// Replays the value into a sink.
293    ///
294    /// The value is parsed, the sink can borrow its data.
295    pub fn replay<'x>(&'x self, sink: SinkHandle<'_, 'x>, state: &mut State) -> Result<(), Error> {
296        // the type of the sink is unknown, it does not want a raw value
297        self.replay_raw(sink, None, state)
298    }
299
300    /// Replays the value, `raw` is the raw value the sink wants.
301    fn replay_raw<'x>(
302        &'x self,
303        sink: SinkHandle<'_, 'x>,
304        raw: Option<&'static RawFormatInfo>,
305        state: &mut State,
306    ) -> Result<(), Error> {
307        DeserializeDriver::nested(state, sink, false, |driver| {
308            // the top-level value is requested before it starts
309            driver.state_mut().raw_requested = raw;
310            (self.format.replay)(&self.bytes, driver)
311        })
312    }
313
314    /// Deserializes the value.
315    ///
316    /// The value can borrow from the input (and the data it borrows).
317    pub fn deserialize<'x, T: Deserialize<'x>>(&'x self) -> Result<T, Error> {
318        // the driver requests the value as raw value if `T` wants one
319        crate::de::deserialize_value(|driver| (self.format.replay)(&self.bytes, driver))
320    }
321}
322
323/// Parses the input of a raw value into a sink that does not accept it.
324///
325/// The sink is finished by the caller (see `NoFinish`).
326pub(crate) fn parse_into<'de>(
327    input: &RawInput<'_>,
328    sink: &mut (dyn Sink<'de> + '_),
329    state: &mut State,
330) -> Result<(), Error> {
331    let mut sink = NoFinish(sink);
332    DeserializeDriver::nested(state, SinkHandle::to(&mut sink), false, |driver| {
333        driver.state_mut().raw_requested = None;
334        // the input lives shorter than the data of the sink
335        driver.transient(|driver| (input.format.replay)(&input.bytes, driver))
336    })
337}
338
339/// Forwards to a sink except for [`Sink::finish`].
340///
341/// This is used to parse a value into a sink that received an atom (see
342/// `parse_into`): the replay finishes the value, the sink is finished by
343/// the code that delivered the atom.
344struct NoFinish<'a, 'b, 'de>(&'a mut (dyn Sink<'de> + 'b));
345
346impl<'de> Sink<'de> for NoFinish<'_, '_, 'de> {
347    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
348        self.0.atom(atom, state)
349    }
350
351    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
352        self.0.borrowed_atom(atom, state)
353    }
354
355    fn map(&mut self, state: &mut State) -> Result<(), Error> {
356        self.0.map(state)
357    }
358
359    fn seq(&mut self, state: &mut State) -> Result<(), Error> {
360        self.0.seq(state)
361    }
362
363    fn next_key(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
364        self.0.next_key(state)
365    }
366
367    fn next_value(&mut self, state: &mut State) -> Result<SinkHandle<'_, 'de>, Error> {
368        self.0.next_value(state)
369    }
370
371    fn value_for_key(
372        &mut self,
373        key: &str,
374        state: &mut State,
375    ) -> Result<Option<SinkHandle<'_, 'de>>, Error> {
376        self.0.value_for_key(key, state)
377    }
378
379    fn recover(&mut self, err: Error, state: &mut State) -> Result<(), Error> {
380        self.0.recover(err, state)
381    }
382
383    fn expecting(&self) -> Cow<'_, str> {
384        self.0.expecting()
385    }
386
387    fn finish(&mut self, _state: &mut State) -> Result<(), Error> {
388        Ok(())
389    }
390}
391
392impl fmt::Debug for RawInput<'_> {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        let mut debug = f.debug_struct("RawInput");
395        debug.field("format", &self.format.id.name);
396        match self.as_str() {
397            Some(text) => debug.field("text", &text),
398            None => debug.field("bytes", &self.bytes),
399        };
400        debug.finish()
401    }
402}
403
404impl PartialEq for RawInput<'_> {
405    fn eq(&self, other: &Self) -> bool {
406        same_format(self.format, other.format) && self.bytes == other.bytes
407    }
408}
409
410impl BorrowedExtension for RawInput<'static> {
411    type Value<'a> = RawInput<'a>;
412
413    fn name<'v>(_value: &'v RawInput<'_>) -> &'v str {
414        "raw value"
415    }
416
417    fn fallback<'v>(value: &'v RawInput<'_>) -> Atom<'v> {
418        (value.format.fallback)(&value.bytes)
419    }
420
421    fn to_static(value: &RawInput<'_>) -> RawInput<'static> {
422        value.clone().into_owned()
423    }
424
425    fn shorten<'s, 'l: 's>(value: &'s RawInput<'l>) -> &'s RawInput<'s> {
426        value
427    }
428}
429
430/// Serializes the input of a value.
431///
432/// The input is passed on as extension value if the serializer writes its
433/// format as it is, otherwise the value is parsed and serialized.
434fn serialize_input<'a>(input: &'a RawInput<'_>, state: &mut State) -> Result<Emit<'a>, Error> {
435    if state.accepts_raw(input.format) {
436        return Ok(Emit::Atom(Atom::Ext(ExtValue::borrowed_value::<RawInput>(
437            input,
438        ))));
439    }
440    Ok(Emit::Forward(SerializeHandle::arena(
441        input.record()?,
442        state,
443    )))
444}
445
446/// Serializes an atom of a recording.
447///
448/// The input of values that the serializer does not write as it is is
449/// parsed and serialized.
450pub(crate) fn serialize_recorded_atom<'a>(
451    atom: &'a Atom<'_>,
452    state: &mut State,
453) -> Result<Emit<'a>, Error> {
454    if let Atom::Ext(ext) = atom
455        && let Some(input) = ext.downcast_value_ref::<RawInput>()
456    {
457        return serialize_input(input, state);
458    }
459    Ok(Emit::Atom(atom.as_borrowed()))
460}
461
462/// A value encoded in the format `F`.
463///
464/// A raw value holds a value in the encoding of a format, for instance
465/// JSON text with `deser_json::RawJson`.  It can be deserialized later
466/// (with [`deserialize`](Self::deserialize)), stored or written out again
467/// unchanged:
468///
469/// * If it's deserialized from the format `F`, it holds the input of the
470///   value as it is.  The format only validates the value and does not
471///   produce its events, which is fast.  With the
472///   [`Borrowed`] adapter the input is
473///   borrowed.
474/// * Otherwise (from another format or where the format cannot pass on
475///   the input, see below) the value is encoded in the format `F`.  The
476///   encoding can lose information that `F` cannot express (bytes in JSON
477///   for instance).  To keep a value of any format without interpreting
478///   it, use [`Recording`](crate::de::Recording).
479///
480/// When serialized with the format `F`, the encoded value is written as it
481/// is.  Other formats serialize the value it holds.
482///
483/// The input of values can only be passed on if the format knows before
484/// the value starts that a raw value is wanted.  Derived structs (for their
485/// first 64 fields), maps, sequences, `Option` and `Box` ask for it.
486/// Values in other places (like the fields of flattened structs, the
487/// variants of enums and values that are buffered, for instance for
488/// untagged enums) are encoded.
489///
490/// Like `Cow`, raw values are deserialized owned, so a `Raw<'static, F>`
491/// can be deserialized from any data.
492pub struct Raw<'a, F: RawFormat> {
493    input: RawInput<'a>,
494    _format: PhantomData<fn() -> F>,
495}
496
497impl<'a, F: RawFormat> Raw<'a, F> {
498    /// Creates a raw value from its encoding.
499    ///
500    /// The value is validated.
501    pub fn new<B: Into<Cow<'a, [u8]>>>(bytes: B) -> Result<Raw<'a, F>, Error> {
502        let bytes = bytes.into();
503        let info = F::info();
504        if info.is_text() && core::str::from_utf8(&bytes).is_err() {
505            return Err(Error::new(ErrorKind::Syntax, "invalid utf-8"));
506        }
507        {
508            let mut driver = DeserializeDriver::from_fn(|_| SinkHandle::null());
509            (info.replay)(&bytes, &mut driver)?;
510        }
511        // SAFETY: the value was validated
512        Ok(Raw::from_input(unsafe { RawInput::new(bytes, info) }))
513    }
514
515    /// Encodes a value.
516    pub fn encode<T: Serialize + ?Sized>(value: &T) -> Result<Raw<'static, F>, Error> {
517        let info = F::info();
518        let bytes = (info.encode)(SerializeRef::new(&value))?;
519        if info.is_text() && core::str::from_utf8(&bytes).is_err() {
520            return Err(Error::new(
521                ErrorKind::InvalidState,
522                "the encoding of a text format is not utf-8",
523            ));
524        }
525        // SAFETY: the encoder produces a valid value
526        Ok(Raw::from_input(unsafe { RawInput::new(bytes, info) }))
527    }
528
529    fn from_input(input: RawInput<'a>) -> Raw<'a, F> {
530        debug_assert!(input.is::<F>());
531        Raw {
532            input,
533            _format: PhantomData,
534        }
535    }
536
537    /// Returns the encoded value.
538    pub fn as_bytes(&self) -> &[u8] {
539        &self.input.bytes
540    }
541
542    /// Returns `true` if the value borrows from the data it was
543    /// deserialized from.
544    pub fn is_borrowed(&self) -> bool {
545        matches!(self.input.bytes, Cow::Borrowed(_))
546    }
547
548    /// Replays the value into a sink.
549    ///
550    /// The value is parsed, the sink can borrow its data.
551    pub fn replay<'x>(&'x self, sink: SinkHandle<'_, 'x>, state: &mut State) -> Result<(), Error> {
552        self.input.replay(sink, state)
553    }
554
555    /// Deserializes the value.
556    ///
557    /// The value can borrow from the raw value (and the data it borrows).
558    pub fn deserialize<'x, T: Deserialize<'x>>(&'x self) -> Result<T, Error> {
559        self.input.deserialize()
560    }
561
562    /// Detaches the value from the data it borrows.
563    pub fn into_owned(self) -> Raw<'static, F> {
564        Raw::from_input(self.input.into_owned())
565    }
566
567    /// Creates a raw value from an atom that was delivered for it.
568    #[inline(never)]
569    fn from_atom(atom: Atom<'_>, state: &State) -> Result<Raw<'static, F>, Error> {
570        if let Atom::Ext(ref ext) = atom
571            && let Some(input) = ext.downcast_value_ref::<RawInput>()
572        {
573            if input.is::<F>() {
574                return Ok(Raw::from_input(input.clone().into_owned()));
575            }
576            return Raw::encode(&input.record()?);
577        }
578        let mut recording = RecordBuf::new();
579        recording.set_atom(&atom, state);
580        Raw::encode(&recording)
581    }
582}
583
584impl<'de, F: RawFormat> Raw<'de, F> {
585    /// Creates a raw value from an atom that was delivered borrowed for it.
586    #[inline(never)]
587    fn from_borrowed_atom(atom: Atom<'de>, state: &State) -> Result<Raw<'de, F>, Error> {
588        if let Atom::Ext(ref ext) = atom {
589            // SAFETY: raw inputs are covariant in their lifetime
590            if let Some(input) = unsafe { ext.downcast_value_ref_covariant::<RawInput>() }
591                && input.is::<F>()
592            {
593                return Ok(Raw::from_input(input.clone()));
594            }
595        }
596        Raw::from_atom(atom, state)
597    }
598}
599
600impl<F: TextRawFormat> Raw<'_, F> {
601    /// Returns the encoded value as text.
602    pub fn get(&self) -> &str {
603        // SAFETY: the encoding of text formats is valid UTF-8
604        unsafe { core::str::from_utf8_unchecked(&self.input.bytes) }
605    }
606}
607
608impl<F: RawFormat> Clone for Raw<'_, F> {
609    fn clone(&self) -> Self {
610        Raw::from_input(self.input.clone())
611    }
612}
613
614impl<F: RawFormat> fmt::Debug for Raw<'_, F> {
615    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616        let mut debug = f.debug_tuple("Raw");
617        debug.field(&self.input.format.id.name);
618        match self.input.as_str() {
619            Some(text) => debug.field(&text),
620            None => debug.field(&self.input.bytes),
621        };
622        debug.finish()
623    }
624}
625
626/// Raw values are equal if their encodings are equal.
627impl<F: RawFormat> PartialEq for Raw<'_, F> {
628    fn eq(&self, other: &Self) -> bool {
629        self.input.bytes == other.input.bytes
630    }
631}
632
633impl<F: RawFormat> Eq for Raw<'_, F> {}
634
635impl<F: RawFormat> core::hash::Hash for Raw<'_, F> {
636    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
637        self.input.bytes.hash(state)
638    }
639}
640
641/// Serialized with the format `F`, the encoded value is written as it is.
642/// Other formats serialize the value it holds.
643impl<F: RawFormat> Serialize for Raw<'_, F> {
644    fn serialize<'a>(value: &'a Self, state: &mut State) -> Result<Emit<'a>, Error> {
645        serialize_input(&value.input, state)
646    }
647}
648
649/// Raw values are deserialized owned so that `Raw<'static, F>` can be
650/// deserialized from any data.  To borrow use the
651/// [`Borrowed`] adapter.
652impl<'de, 'a, F: RawFormat> Deserialize<'de> for Raw<'a, F> {
653    fn deserialize_into<'out>(
654        out: &'out mut Option<Self>,
655        state: &mut State,
656    ) -> SinkHandle<'out, 'de> {
657        RecordBuf::capture_with(RawCapture(out), state)
658    }
659
660    fn expecting() -> Cow<'static, str> {
661        Cow::Borrowed("any value")
662    }
663
664    #[inline]
665    fn __private_atom_into(
666        out: &mut Option<Self>,
667        atom: Atom,
668        state: &mut State,
669    ) -> Result<(), Error> {
670        *out = Some(Raw::from_atom(atom, state)?);
671        Ok(())
672    }
673
674    #[inline]
675    fn __private_borrowed_atom_into(
676        out: &mut Option<Self>,
677        atom: Atom<'de>,
678        state: &mut State,
679    ) -> Result<(), Error> {
680        *out = Some(Raw::from_atom(atom, state)?);
681        Ok(())
682    }
683
684    #[inline(always)]
685    fn __private_raw() -> Option<&'static RawFormatInfo> {
686        Some(F::info())
687    }
688}
689
690/// Borrows raw values from the data if the format passes it on borrowed.
691impl<'de: 'a, 'a, F: RawFormat> Deserialize<'de, Raw<'a, F>> for Borrowed {
692    fn deserialize_into<'out>(
693        out: &'out mut Option<Raw<'a, F>>,
694        state: &mut State,
695    ) -> SinkHandle<'out, 'de> {
696        RecordBuf::capture_with(BorrowedRawCapture(out), state)
697    }
698
699    fn expecting() -> Cow<'static, str> {
700        Cow::Borrowed("any value")
701    }
702
703    #[inline]
704    fn __private_atom_into(
705        out: &mut Option<Raw<'a, F>>,
706        atom: Atom,
707        state: &mut State,
708    ) -> Result<(), Error> {
709        *out = Some(Raw::from_atom(atom, state)?);
710        Ok(())
711    }
712
713    #[inline]
714    fn __private_borrowed_atom_into(
715        out: &mut Option<Raw<'a, F>>,
716        atom: Atom<'de>,
717        state: &mut State,
718    ) -> Result<(), Error> {
719        *out = Some(Raw::from_borrowed_atom(atom, state)?);
720        Ok(())
721    }
722
723    #[inline(always)]
724    fn __private_raw() -> Option<&'static RawFormatInfo> {
725        Some(F::info())
726    }
727}
728
729impl<'a, F: RawFormat> Serialize<Raw<'a, F>> for Borrowed {
730    fn serialize<'x>(value: &'x Raw<'a, F>, state: &mut State) -> Result<Emit<'x>, Error> {
731        <Raw<'a, F>>::serialize(value, state)
732    }
733}
734
735/// Places a captured value into the slot of a raw value, owned.
736struct RawCapture<'o, 'a, F: RawFormat>(&'o mut Option<Raw<'a, F>>);
737
738impl<'o, 'a, 'de, F: RawFormat> Capture<'de, RecordBuf<'de>> for RawCapture<'o, 'a, F> {
739    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
740        *self.0 = Some(Raw::from_atom(atom, state)?);
741        Ok(())
742    }
743
744    fn recorded(&mut self, recording: RecordBuf<'de>, _state: &mut State) -> Result<(), Error> {
745        *self.0 = Some(Raw::encode(&recording)?);
746        Ok(())
747    }
748}
749
750/// Places a captured value into the slot of a raw value, borrowed.
751struct BorrowedRawCapture<'o, 'a, F: RawFormat>(&'o mut Option<Raw<'a, F>>);
752
753impl<'o, 'a, 'de: 'a, F: RawFormat> Capture<'de, RecordBuf<'de>> for BorrowedRawCapture<'o, 'a, F> {
754    fn atom(&mut self, atom: Atom, state: &mut State) -> Result<(), Error> {
755        *self.0 = Some(Raw::from_atom(atom, state)?);
756        Ok(())
757    }
758
759    fn borrowed_atom(&mut self, atom: Atom<'de>, state: &mut State) -> Result<(), Error> {
760        *self.0 = Some(Raw::from_borrowed_atom(atom, state)?);
761        Ok(())
762    }
763
764    fn recorded(&mut self, recording: RecordBuf<'de>, _state: &mut State) -> Result<(), Error> {
765        *self.0 = Some(Raw::encode(&recording)?);
766        Ok(())
767    }
768}