toml/
spanned.rs

1use serde::{de, ser};
2use std::borrow::Borrow;
3use std::cmp::Ordering;
4use std::fmt;
5use std::hash::{Hash, Hasher};
6
7pub(crate) const NAME: &str = "$__toml_private_Spanned";
8pub(crate) const START: &str = "$__toml_private_start";
9pub(crate) const END: &str = "$__toml_private_end";
10pub(crate) const VALUE: &str = "$__toml_private_value";
11
12/// A spanned value, indicating the range at which it is defined in the source.
13///
14/// ```
15/// use serde_derive::Deserialize;
16/// use toml::Spanned;
17///
18/// #[derive(Deserialize)]
19/// struct Value {
20///     s: Spanned<String>,
21/// }
22///
23/// fn main() {
24///     let t = "s = \"value\"\n";
25///
26///     let u: Value = toml::from_str(t).unwrap();
27///
28///     assert_eq!(u.s.start(), 4);
29///     assert_eq!(u.s.end(), 11);
30///     assert_eq!(u.s.get_ref(), "value");
31///     assert_eq!(u.s.into_inner(), String::from("value"));
32/// }
33/// ```
34#[derive(Clone, Debug)]
35pub struct Spanned<T> {
36    /// The start range.
37    start: usize,
38    /// The end range (exclusive).
39    end: usize,
40    /// The spanned value.
41    value: T,
42}
43
44impl<T> Spanned<T> {
45    /// Access the start of the span of the contained value.
46    pub fn start(&self) -> usize {
47        self.start
48    }
49
50    /// Access the end of the span of the contained value.
51    pub fn end(&self) -> usize {
52        self.end
53    }
54
55    /// Get the span of the contained value.
56    pub fn span(&self) -> (usize, usize) {
57        (self.start, self.end)
58    }
59
60    /// Consumes the spanned value and returns the contained value.
61    pub fn into_inner(self) -> T {
62        self.value
63    }
64
65    /// Returns a reference to the contained value.
66    pub fn get_ref(&self) -> &T {
67        &self.value
68    }
69
70    /// Returns a mutable reference to the contained value.
71    pub fn get_mut(&mut self) -> &mut T {
72        &mut self.value
73    }
74}
75
76impl Borrow<str> for Spanned<String> {
77    fn borrow(&self) -> &str {
78        &self.get_ref()
79    }
80}
81
82impl<T: PartialEq> PartialEq for Spanned<T> {
83    fn eq(&self, other: &Self) -> bool {
84        self.value.eq(&other.value)
85    }
86}
87
88impl<T: Eq> Eq for Spanned<T> {}
89
90impl<T: Hash> Hash for Spanned<T> {
91    fn hash<H: Hasher>(&self, state: &mut H) {
92        self.value.hash(state);
93    }
94}
95
96impl<T: PartialOrd> PartialOrd for Spanned<T> {
97    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
98        self.value.partial_cmp(&other.value)
99    }
100}
101
102impl<T: Ord> Ord for Spanned<T> {
103    fn cmp(&self, other: &Self) -> Ordering {
104        self.value.cmp(&other.value)
105    }
106}
107
108impl<'de, T> de::Deserialize<'de> for Spanned<T>
109where
110    T: de::Deserialize<'de>,
111{
112    fn deserialize<D>(deserializer: D) -> Result<Spanned<T>, D::Error>
113    where
114        D: de::Deserializer<'de>,
115    {
116        struct SpannedVisitor<T>(::std::marker::PhantomData<T>);
117
118        impl<'de, T> de::Visitor<'de> for SpannedVisitor<T>
119        where
120            T: de::Deserialize<'de>,
121        {
122            type Value = Spanned<T>;
123
124            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
125                formatter.write_str("a TOML spanned")
126            }
127
128            fn visit_map<V>(self, mut visitor: V) -> Result<Spanned<T>, V::Error>
129            where
130                V: de::MapAccess<'de>,
131            {
132                if visitor.next_key()? != Some(START) {
133                    return Err(de::Error::custom("spanned start key not found"));
134                }
135
136                let start: usize = visitor.next_value()?;
137
138                if visitor.next_key()? != Some(END) {
139                    return Err(de::Error::custom("spanned end key not found"));
140                }
141
142                let end: usize = visitor.next_value()?;
143
144                if visitor.next_key()? != Some(VALUE) {
145                    return Err(de::Error::custom("spanned value key not found"));
146                }
147
148                let value: T = visitor.next_value()?;
149
150                Ok(Spanned { start, end, value })
151            }
152        }
153
154        let visitor = SpannedVisitor(::std::marker::PhantomData);
155
156        static FIELDS: [&str; 3] = [START, END, VALUE];
157        deserializer.deserialize_struct(NAME, &FIELDS, visitor)
158    }
159}
160
161impl<T: ser::Serialize> ser::Serialize for Spanned<T> {
162    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
163    where
164        S: ser::Serializer,
165    {
166        self.value.serialize(serializer)
167    }
168}