toml_edit/
repr.rs

1use std::borrow::Cow;
2
3use crate::RawString;
4
5/// A scalar TOML [`Value`][crate::Value]'s logical value and its representation in a `&str`
6///
7/// This includes the surrounding whitespace and comments.
8#[derive(Eq, PartialEq, Clone, Hash)]
9pub struct Formatted<T> {
10    value: T,
11    repr: Option<Repr>,
12    decor: Decor,
13}
14
15impl<T> Formatted<T>
16where
17    T: ValueRepr,
18{
19    /// Default-formatted value
20    pub fn new(value: T) -> Self {
21        Self {
22            value,
23            repr: None,
24            decor: Default::default(),
25        }
26    }
27
28    pub(crate) fn set_repr_unchecked(&mut self, repr: Repr) {
29        self.repr = Some(repr);
30    }
31
32    /// The wrapped value
33    pub fn value(&self) -> &T {
34        &self.value
35    }
36
37    /// The wrapped value
38    pub fn into_value(self) -> T {
39        self.value
40    }
41
42    /// Returns the raw representation, if available.
43    pub fn as_repr(&self) -> Option<&Repr> {
44        self.repr.as_ref()
45    }
46
47    /// Returns the default raw representation.
48    #[cfg(feature = "display")]
49    pub fn default_repr(&self) -> Repr {
50        self.value.to_repr()
51    }
52
53    /// Returns a raw representation.
54    #[cfg(feature = "display")]
55    pub fn display_repr(&self) -> Cow<'_, str> {
56        self.as_repr()
57            .and_then(|r| r.as_raw().as_str())
58            .map(Cow::Borrowed)
59            .unwrap_or_else(|| {
60                Cow::Owned(self.default_repr().as_raw().as_str().unwrap().to_owned())
61            })
62    }
63
64    /// The location within the original document
65    ///
66    /// This generally requires an [`ImDocument`][crate::ImDocument].
67    pub fn span(&self) -> Option<std::ops::Range<usize>> {
68        self.repr.as_ref().and_then(|r| r.span())
69    }
70
71    pub(crate) fn despan(&mut self, input: &str) {
72        self.decor.despan(input);
73        if let Some(repr) = &mut self.repr {
74            repr.despan(input);
75        }
76    }
77
78    /// Returns the surrounding whitespace
79    pub fn decor_mut(&mut self) -> &mut Decor {
80        &mut self.decor
81    }
82
83    /// Returns the surrounding whitespace
84    pub fn decor(&self) -> &Decor {
85        &self.decor
86    }
87
88    /// Auto formats the value.
89    pub fn fmt(&mut self) {
90        self.repr = None;
91    }
92}
93
94impl<T> std::fmt::Debug for Formatted<T>
95where
96    T: std::fmt::Debug,
97{
98    #[inline]
99    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
100        let mut d = formatter.debug_struct("Formatted");
101        d.field("value", &self.value);
102        match &self.repr {
103            Some(r) => d.field("repr", r),
104            None => d.field("repr", &"default"),
105        };
106        d.field("decor", &self.decor);
107        d.finish()
108    }
109}
110
111#[cfg(feature = "display")]
112impl<T> std::fmt::Display for Formatted<T>
113where
114    T: ValueRepr,
115{
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        crate::encode::encode_formatted(self, f, None, ("", ""))
118    }
119}
120
121pub trait ValueRepr: crate::private::Sealed {
122    /// The TOML representation of the value
123    #[cfg(feature = "display")]
124    fn to_repr(&self) -> Repr;
125}
126
127#[cfg(not(feature = "display"))]
128mod inner {
129    use super::ValueRepr;
130
131    impl ValueRepr for String {}
132    impl ValueRepr for i64 {}
133    impl ValueRepr for f64 {}
134    impl ValueRepr for bool {}
135    impl ValueRepr for toml_datetime::Datetime {}
136}
137
138/// A TOML [`Value`][crate::Value] encoded as a `&str`
139#[derive(Eq, PartialEq, Clone, Hash)]
140pub struct Repr {
141    raw_value: RawString,
142}
143
144impl Repr {
145    pub(crate) fn new_unchecked(raw: impl Into<RawString>) -> Self {
146        Repr {
147            raw_value: raw.into(),
148        }
149    }
150
151    /// Access the underlying value
152    pub fn as_raw(&self) -> &RawString {
153        &self.raw_value
154    }
155
156    /// The location within the original document
157    ///
158    /// This generally requires an [`ImDocument`][crate::ImDocument].
159    pub fn span(&self) -> Option<std::ops::Range<usize>> {
160        self.raw_value.span()
161    }
162
163    pub(crate) fn despan(&mut self, input: &str) {
164        self.raw_value.despan(input);
165    }
166
167    #[cfg(feature = "display")]
168    pub(crate) fn encode(&self, buf: &mut dyn std::fmt::Write, input: &str) -> std::fmt::Result {
169        self.as_raw().encode(buf, input)
170    }
171}
172
173impl std::fmt::Debug for Repr {
174    #[inline]
175    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
176        self.raw_value.fmt(formatter)
177    }
178}
179
180/// A prefix and suffix,
181///
182/// Including comments, whitespaces and newlines.
183#[derive(Eq, PartialEq, Clone, Default, Hash)]
184pub struct Decor {
185    prefix: Option<RawString>,
186    suffix: Option<RawString>,
187}
188
189impl Decor {
190    /// Creates a new decor from the given prefix and suffix.
191    pub fn new(prefix: impl Into<RawString>, suffix: impl Into<RawString>) -> Self {
192        Self {
193            prefix: Some(prefix.into()),
194            suffix: Some(suffix.into()),
195        }
196    }
197
198    /// Go back to default decor
199    pub fn clear(&mut self) {
200        self.prefix = None;
201        self.suffix = None;
202    }
203
204    /// Get the prefix.
205    pub fn prefix(&self) -> Option<&RawString> {
206        self.prefix.as_ref()
207    }
208
209    #[cfg(feature = "display")]
210    pub(crate) fn prefix_encode(
211        &self,
212        buf: &mut dyn std::fmt::Write,
213        input: Option<&str>,
214        default: &str,
215    ) -> std::fmt::Result {
216        if let Some(prefix) = self.prefix() {
217            prefix.encode_with_default(buf, input, default)
218        } else {
219            write!(buf, "{default}")
220        }
221    }
222
223    /// Set the prefix.
224    pub fn set_prefix(&mut self, prefix: impl Into<RawString>) {
225        self.prefix = Some(prefix.into());
226    }
227
228    /// Get the suffix.
229    pub fn suffix(&self) -> Option<&RawString> {
230        self.suffix.as_ref()
231    }
232
233    #[cfg(feature = "display")]
234    pub(crate) fn suffix_encode(
235        &self,
236        buf: &mut dyn std::fmt::Write,
237        input: Option<&str>,
238        default: &str,
239    ) -> std::fmt::Result {
240        if let Some(suffix) = self.suffix() {
241            suffix.encode_with_default(buf, input, default)
242        } else {
243            write!(buf, "{default}")
244        }
245    }
246
247    /// Set the suffix.
248    pub fn set_suffix(&mut self, suffix: impl Into<RawString>) {
249        self.suffix = Some(suffix.into());
250    }
251
252    pub(crate) fn despan(&mut self, input: &str) {
253        if let Some(prefix) = &mut self.prefix {
254            prefix.despan(input);
255        }
256        if let Some(suffix) = &mut self.suffix {
257            suffix.despan(input);
258        }
259    }
260}
261
262impl std::fmt::Debug for Decor {
263    #[inline]
264    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
265        let mut d = formatter.debug_struct("Decor");
266        match &self.prefix {
267            Some(r) => d.field("prefix", r),
268            None => d.field("prefix", &"default"),
269        };
270        match &self.suffix {
271            Some(r) => d.field("suffix", r),
272            None => d.field("suffix", &"default"),
273        };
274        d.finish()
275    }
276}