Skip to main content

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 a [`Document`][crate::Document].
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        Self {
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 a [`Document`][crate::Document].
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    pub(crate) const EMPTY: Self = Self {
191        prefix: None,
192        suffix: None,
193    };
194
195    /// Creates a new decor from the given prefix and suffix.
196    pub fn new(prefix: impl Into<RawString>, suffix: impl Into<RawString>) -> Self {
197        Self {
198            prefix: Some(prefix.into()),
199            suffix: Some(suffix.into()),
200        }
201    }
202
203    /// Go back to default decor
204    pub fn clear(&mut self) {
205        self.prefix = None;
206        self.suffix = None;
207    }
208
209    /// Get the prefix.
210    pub fn prefix(&self) -> Option<&RawString> {
211        self.prefix.as_ref()
212    }
213
214    #[cfg(feature = "display")]
215    pub(crate) fn prefix_encode(
216        &self,
217        buf: &mut dyn std::fmt::Write,
218        input: Option<&str>,
219        default: &str,
220    ) -> std::fmt::Result {
221        if let Some(prefix) = self.prefix() {
222            prefix.encode_with_default(buf, input, default)
223        } else {
224            write!(buf, "{default}")
225        }
226    }
227
228    /// Set the prefix.
229    pub fn set_prefix(&mut self, prefix: impl Into<RawString>) {
230        self.prefix = Some(prefix.into());
231    }
232
233    /// Get the suffix.
234    pub fn suffix(&self) -> Option<&RawString> {
235        self.suffix.as_ref()
236    }
237
238    #[cfg(feature = "display")]
239    pub(crate) fn suffix_encode(
240        &self,
241        buf: &mut dyn std::fmt::Write,
242        input: Option<&str>,
243        default: &str,
244    ) -> std::fmt::Result {
245        if let Some(suffix) = self.suffix() {
246            suffix.encode_with_default(buf, input, default)
247        } else {
248            write!(buf, "{default}")
249        }
250    }
251
252    /// Set the suffix.
253    pub fn set_suffix(&mut self, suffix: impl Into<RawString>) {
254        self.suffix = Some(suffix.into());
255    }
256
257    pub(crate) fn despan(&mut self, input: &str) {
258        if let Some(prefix) = &mut self.prefix {
259            prefix.despan(input);
260        }
261        if let Some(suffix) = &mut self.suffix {
262            suffix.despan(input);
263        }
264    }
265}
266
267impl std::fmt::Debug for Decor {
268    #[inline]
269    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
270        let mut d = formatter.debug_struct("Decor");
271        match &self.prefix {
272            Some(r) => d.field("prefix", r),
273            None => d.field("prefix", &"default"),
274        };
275        match &self.suffix {
276            Some(r) => d.field("suffix", r),
277            None => d.field("suffix", &"default"),
278        };
279        d.finish()
280    }
281}