Skip to main content

toml_edit/
key.rs

1use std::borrow::Cow;
2use std::str::FromStr;
3
4#[cfg(feature = "display")]
5use toml_writer::ToTomlKey as _;
6
7use crate::repr::{Decor, Repr};
8
9/// For Key/[`Value`][crate::Value] pairs under a [`Table`][crate::Table] header or inside an
10/// [`InlineTable`][crate::InlineTable]
11///
12/// # Examples
13///
14/// ```notrust
15/// [dependencies."nom"]
16/// version = "5.0"
17/// 'literal key' = "nonsense"
18/// "basic string key" = 42
19/// ```
20///
21/// There are 3 types of keys:
22///
23/// 1. Bare keys (`version` and `dependencies`)
24///
25/// 2. Basic quoted keys (`"basic string key"` and `"nom"`)
26///
27/// 3. Literal quoted keys (`'literal key'`)
28///
29/// For details see [toml spec](https://github.com/toml-lang/toml/#keyvalue-pair).
30///
31/// To parse a key use `FromStr` trait implementation: `"string".parse::<Key>()`.
32#[derive(Debug)]
33pub struct Key {
34    key: String,
35    pub(crate) repr: Option<Repr>,
36    pub(crate) leaf_decor: Decor,
37    pub(crate) dotted_decor: Decor,
38}
39
40impl Key {
41    /// Create a new table key
42    pub fn new(key: impl Into<String>) -> Self {
43        Self {
44            key: key.into(),
45            repr: None,
46            leaf_decor: Default::default(),
47            dotted_decor: Default::default(),
48        }
49    }
50
51    /// Parse a TOML key expression
52    ///
53    /// Unlike `"".parse<Key>()`, this supports dotted keys.
54    #[cfg(feature = "parse")]
55    pub fn parse(repr: &str) -> Result<Vec<Self>, crate::TomlError> {
56        Self::try_parse_path(repr)
57    }
58
59    pub(crate) fn with_repr_unchecked(mut self, repr: Repr) -> Self {
60        self.repr = Some(repr);
61        self
62    }
63
64    /// While creating the `Key`, add `Decor` to it for the line entry
65    pub fn with_leaf_decor(mut self, decor: Decor) -> Self {
66        self.leaf_decor = decor;
67        self
68    }
69
70    /// While creating the `Key`, add `Decor` to it for between dots
71    pub fn with_dotted_decor(mut self, decor: Decor) -> Self {
72        self.dotted_decor = decor;
73        self
74    }
75
76    /// Access a mutable proxy for the `Key`.
77    pub fn as_mut(&mut self) -> KeyMut<'_> {
78        KeyMut { key: self }
79    }
80
81    /// Returns the parsed key value.
82    pub fn get(&self) -> &str {
83        &self.key
84    }
85
86    /// Returns key raw representation, if available.
87    pub fn as_repr(&self) -> Option<&Repr> {
88        self.repr.as_ref()
89    }
90
91    /// Returns the default raw representation.
92    #[cfg(feature = "display")]
93    pub fn default_repr(&self) -> Repr {
94        let output = toml_writer::TomlKeyBuilder::new(&self.key)
95            .as_default()
96            .to_toml_key();
97        Repr::new_unchecked(output)
98    }
99
100    /// Returns a raw representation.
101    #[cfg(feature = "display")]
102    pub fn display_repr(&self) -> Cow<'_, str> {
103        self.as_repr()
104            .and_then(|r| r.as_raw().as_str())
105            .map(Cow::Borrowed)
106            .unwrap_or_else(|| Cow::Owned(self.default_repr().into_raw().into_string().unwrap()))
107    }
108
109    /// Returns the surrounding whitespace for the line entry
110    pub fn leaf_decor_mut(&mut self) -> &mut Decor {
111        &mut self.leaf_decor
112    }
113
114    /// Returns the surrounding whitespace for between dots
115    pub fn dotted_decor_mut(&mut self) -> &mut Decor {
116        &mut self.dotted_decor
117    }
118
119    /// Returns the surrounding whitespace for the line entry
120    pub fn leaf_decor(&self) -> &Decor {
121        &self.leaf_decor
122    }
123
124    /// Returns the surrounding whitespace for between dots
125    pub fn dotted_decor(&self) -> &Decor {
126        &self.dotted_decor
127    }
128
129    /// The location within the original document
130    ///
131    /// This generally requires a [`Document`][crate::Document].
132    pub fn span(&self) -> Option<std::ops::Range<usize>> {
133        self.repr.as_ref().and_then(|r| r.span())
134    }
135
136    pub(crate) fn despan(&mut self, input: &str) {
137        self.leaf_decor.despan(input);
138        self.dotted_decor.despan(input);
139        if let Some(repr) = &mut self.repr {
140            repr.despan(input);
141        }
142    }
143
144    /// Auto formats the key.
145    pub fn fmt(&mut self) {
146        self.repr = None;
147        self.leaf_decor.clear();
148        self.dotted_decor.clear();
149    }
150
151    #[cfg(feature = "parse")]
152    fn try_parse_simple(s: &str) -> Result<Self, crate::TomlError> {
153        let source = toml_parser::Source::new(s);
154        let mut sink = crate::error::TomlSink::<Option<_>>::new(source);
155        let mut key = crate::parser::parse_key(source, &mut sink);
156        if let Some(err) = sink.into_inner() {
157            Err(err)
158        } else {
159            key.despan(s);
160            Ok(key)
161        }
162    }
163
164    #[cfg(feature = "parse")]
165    fn try_parse_path(s: &str) -> Result<Vec<Self>, crate::TomlError> {
166        let source = toml_parser::Source::new(s);
167        let mut sink = crate::error::TomlSink::<Option<_>>::new(source);
168        let mut keys = crate::parser::parse_key_path(source, &mut sink);
169        if let Some(err) = sink.into_inner() {
170            Err(err)
171        } else {
172            for key in &mut keys {
173                key.despan(s);
174            }
175            Ok(keys)
176        }
177    }
178}
179
180impl Clone for Key {
181    #[inline(never)]
182    fn clone(&self) -> Self {
183        Self {
184            key: self.key.clone(),
185            repr: self.repr.clone(),
186            leaf_decor: self.leaf_decor.clone(),
187            dotted_decor: self.dotted_decor.clone(),
188        }
189    }
190}
191
192impl std::ops::Deref for Key {
193    type Target = str;
194
195    fn deref(&self) -> &Self::Target {
196        self.get()
197    }
198}
199
200impl std::borrow::Borrow<str> for Key {
201    #[inline]
202    fn borrow(&self) -> &str {
203        self.get()
204    }
205}
206
207impl std::hash::Hash for Key {
208    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
209        self.get().hash(state);
210    }
211}
212
213impl Ord for Key {
214    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
215        self.get().cmp(other.get())
216    }
217}
218
219impl PartialOrd for Key {
220    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
221        Some(self.cmp(other))
222    }
223}
224
225impl Eq for Key {}
226
227impl PartialEq for Key {
228    #[inline]
229    fn eq(&self, other: &Self) -> bool {
230        PartialEq::eq(self.get(), other.get())
231    }
232}
233
234impl PartialEq<str> for Key {
235    #[inline]
236    fn eq(&self, other: &str) -> bool {
237        PartialEq::eq(self.get(), other)
238    }
239}
240
241impl PartialEq<&str> for Key {
242    #[inline]
243    fn eq(&self, other: &&str) -> bool {
244        PartialEq::eq(self.get(), *other)
245    }
246}
247
248impl PartialEq<String> for Key {
249    #[inline]
250    fn eq(&self, other: &String) -> bool {
251        PartialEq::eq(self.get(), other.as_str())
252    }
253}
254
255#[cfg(feature = "display")]
256impl std::fmt::Display for Key {
257    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258        crate::encode::encode_key(self, f, None)
259    }
260}
261
262#[cfg(feature = "parse")]
263impl FromStr for Key {
264    type Err = crate::TomlError;
265
266    /// Tries to parse a key from a &str,
267    /// if fails, tries as basic quoted key (surrounds with "")
268    /// and then literal quoted key (surrounds with '')
269    fn from_str(s: &str) -> Result<Self, Self::Err> {
270        Self::try_parse_simple(s)
271    }
272}
273
274impl<'b> From<&'b str> for Key {
275    fn from(s: &'b str) -> Self {
276        Self::new(s)
277    }
278}
279
280impl<'b> From<&'b String> for Key {
281    fn from(s: &'b String) -> Self {
282        Self::new(s)
283    }
284}
285
286impl From<String> for Key {
287    fn from(s: String) -> Self {
288        Self::new(s)
289    }
290}
291
292#[doc(hidden)]
293impl From<Key> for String {
294    fn from(key: Key) -> Self {
295        key.key
296    }
297}
298
299/// A mutable reference to a [`Key`]'s formatting
300#[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
301pub struct KeyMut<'k> {
302    key: &'k mut Key,
303}
304
305impl KeyMut<'_> {
306    /// Returns the parsed key value.
307    pub fn get(&self) -> &str {
308        self.key.get()
309    }
310
311    /// Returns the raw representation, if available.
312    pub fn as_repr(&self) -> Option<&Repr> {
313        self.key.as_repr()
314    }
315
316    /// Returns the default raw representation.
317    #[cfg(feature = "display")]
318    pub fn default_repr(&self) -> Repr {
319        self.key.default_repr()
320    }
321
322    /// Returns a raw representation.
323    #[cfg(feature = "display")]
324    pub fn display_repr(&self) -> Cow<'_, str> {
325        self.key.display_repr()
326    }
327
328    /// Returns the surrounding whitespace for the line entry
329    pub fn leaf_decor_mut(&mut self) -> &mut Decor {
330        self.key.leaf_decor_mut()
331    }
332
333    /// Returns the surrounding whitespace for between dots
334    pub fn dotted_decor_mut(&mut self) -> &mut Decor {
335        self.key.dotted_decor_mut()
336    }
337
338    /// Returns the surrounding whitespace for the line entry
339    pub fn leaf_decor(&self) -> &Decor {
340        self.key.leaf_decor()
341    }
342
343    /// Returns the surrounding whitespace for between dots
344    pub fn dotted_decor(&self) -> &Decor {
345        self.key.dotted_decor()
346    }
347
348    /// Auto formats the key.
349    pub fn fmt(&mut self) {
350        self.key.fmt();
351    }
352}
353
354impl std::ops::Deref for KeyMut<'_> {
355    type Target = str;
356
357    fn deref(&self) -> &Self::Target {
358        self.get()
359    }
360}
361
362impl PartialEq<str> for KeyMut<'_> {
363    #[inline]
364    fn eq(&self, other: &str) -> bool {
365        PartialEq::eq(self.get(), other)
366    }
367}
368
369impl<'s> PartialEq<&'s str> for KeyMut<'s> {
370    #[inline]
371    fn eq(&self, other: &&str) -> bool {
372        PartialEq::eq(self.get(), *other)
373    }
374}
375
376impl PartialEq<String> for KeyMut<'_> {
377    #[inline]
378    fn eq(&self, other: &String) -> bool {
379        PartialEq::eq(self.get(), other.as_str())
380    }
381}
382
383#[cfg(feature = "display")]
384impl std::fmt::Display for KeyMut<'_> {
385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386        std::fmt::Display::fmt(&self.key, f)
387    }
388}
389
390#[test]
391#[cfg(feature = "parse")]
392#[cfg(feature = "display")]
393fn string_roundtrip() {
394    Key::new("hello").to_string().parse::<Key>().unwrap();
395}