Skip to main content

deser_core/
source.rs

1use alloc::sync::Arc;
2use core::fmt;
3
4use crate::State;
5
6/// The source the input ranges refer to.
7///
8/// Formats can publish the byte range in the input of every event (see
9/// [`State::input_range`](crate::State::input_range)).  This is cheap, but
10/// resolving the ranges into lines and columns (see
11/// [`Position::of`](crate::Position::of)) requires the source.  As
12/// this requires a copy of the input, formats only provide it when asked to
13/// (for instance with their `track_locations` option).  They store it in
14/// the [`State`] as an extension value with [`set`](Self::set) before they
15/// emit the first event:
16///
17/// ```
18/// use deser::de::DeserializeDriver;
19/// use deser::Source;
20///
21/// let mut out = None::<bool>;
22/// let mut driver = DeserializeDriver::new(&mut out);
23/// Source::set(driver.state_mut(), "true");
24/// assert_eq!(&*driver.state().get::<Source>().unwrap().0, "true");
25/// ```
26#[derive(Clone, Default)]
27pub struct Source(pub Arc<str>);
28
29impl Source {
30    /// Sets the source in the state.
31    pub fn set<S: Into<Arc<str>>>(state: &mut State, source: S) {
32        *state.get_mut::<Source>() = Source(source.into());
33    }
34}
35
36impl fmt::Debug for Source {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        // the source can be large, it's not included
39        f.debug_struct("Source")
40            .field("len", &self.0.len())
41            .finish()
42    }
43}