• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use std::iter::FromIterator;
2 
3 use indexmap::map::IndexMap;
4 
5 use crate::key::Key;
6 use crate::repr::Decor;
7 use crate::value::DEFAULT_VALUE_DECOR;
8 use crate::{InlineTable, InternalString, Item, KeyMut, Value};
9 
10 /// Type representing a TOML non-inline table
11 #[derive(Clone, Debug, Default)]
12 pub struct Table {
13     // Comments/spaces before and after the header
14     pub(crate) decor: Decor,
15     // Whether to hide an empty table
16     pub(crate) implicit: bool,
17     // Whether this is a proxy for dotted keys
18     pub(crate) dotted: bool,
19     // Used for putting tables back in their original order when serialising.
20     //
21     // `None` for user created tables (can be overridden with `set_position`)
22     doc_position: Option<usize>,
23     pub(crate) span: Option<std::ops::Range<usize>>,
24     pub(crate) items: KeyValuePairs,
25 }
26 
27 /// Constructors
28 ///
29 /// See also `FromIterator`
30 impl Table {
31     /// Creates an empty table.
new() -> Self32     pub fn new() -> Self {
33         Default::default()
34     }
35 
with_pos(doc_position: Option<usize>) -> Self36     pub(crate) fn with_pos(doc_position: Option<usize>) -> Self {
37         Self {
38             doc_position,
39             ..Default::default()
40         }
41     }
42 
with_pairs(items: KeyValuePairs) -> Self43     pub(crate) fn with_pairs(items: KeyValuePairs) -> Self {
44         Self {
45             items,
46             ..Default::default()
47         }
48     }
49 
50     /// Convert to an inline table
into_inline_table(mut self) -> InlineTable51     pub fn into_inline_table(mut self) -> InlineTable {
52         for (_, kv) in self.items.iter_mut() {
53             kv.value.make_value();
54         }
55         let mut t = InlineTable::with_pairs(self.items);
56         t.fmt();
57         t
58     }
59 }
60 
61 /// Formatting
62 impl Table {
63     /// Get key/values for values that are visually children of this table
64     ///
65     /// For example, this will return dotted keys
get_values(&self) -> Vec<(Vec<&Key>, &Value)>66     pub fn get_values(&self) -> Vec<(Vec<&Key>, &Value)> {
67         let mut values = Vec::new();
68         let root = Vec::new();
69         self.append_values(&root, &mut values);
70         values
71     }
72 
append_values<'s>( &'s self, parent: &[&'s Key], values: &mut Vec<(Vec<&'s Key>, &'s Value)>, )73     fn append_values<'s>(
74         &'s self,
75         parent: &[&'s Key],
76         values: &mut Vec<(Vec<&'s Key>, &'s Value)>,
77     ) {
78         for value in self.items.values() {
79             let mut path = parent.to_vec();
80             path.push(&value.key);
81             match &value.value {
82                 Item::Table(table) if table.is_dotted() => {
83                     table.append_values(&path, values);
84                 }
85                 Item::Value(value) => {
86                     if let Some(table) = value.as_inline_table() {
87                         if table.is_dotted() {
88                             table.append_values(&path, values);
89                         } else {
90                             values.push((path, value));
91                         }
92                     } else {
93                         values.push((path, value));
94                     }
95                 }
96                 _ => {}
97             }
98         }
99     }
100 
101     /// Auto formats the table.
fmt(&mut self)102     pub fn fmt(&mut self) {
103         decorate_table(self);
104     }
105 
106     /// Sorts Key/Value Pairs of the table.
107     ///
108     /// Doesn't affect subtables or subarrays.
sort_values(&mut self)109     pub fn sort_values(&mut self) {
110         // Assuming standard tables have their doc_position set and this won't negatively impact them
111         self.items.sort_keys();
112         for kv in self.items.values_mut() {
113             match &mut kv.value {
114                 Item::Table(table) if table.is_dotted() => {
115                     table.sort_values();
116                 }
117                 _ => {}
118             }
119         }
120     }
121 
122     /// Sort Key/Value Pairs of the table using the using the comparison function `compare`.
123     ///
124     /// The comparison function receives two key and value pairs to compare (you can sort by keys or
125     /// values or their combination as needed).
sort_values_by<F>(&mut self, mut compare: F) where F: FnMut(&Key, &Item, &Key, &Item) -> std::cmp::Ordering,126     pub fn sort_values_by<F>(&mut self, mut compare: F)
127     where
128         F: FnMut(&Key, &Item, &Key, &Item) -> std::cmp::Ordering,
129     {
130         self.sort_values_by_internal(&mut compare);
131     }
132 
sort_values_by_internal<F>(&mut self, compare: &mut F) where F: FnMut(&Key, &Item, &Key, &Item) -> std::cmp::Ordering,133     fn sort_values_by_internal<F>(&mut self, compare: &mut F)
134     where
135         F: FnMut(&Key, &Item, &Key, &Item) -> std::cmp::Ordering,
136     {
137         let modified_cmp = |_: &InternalString,
138                             val1: &TableKeyValue,
139                             _: &InternalString,
140                             val2: &TableKeyValue|
141          -> std::cmp::Ordering {
142             compare(&val1.key, &val1.value, &val2.key, &val2.value)
143         };
144 
145         self.items.sort_by(modified_cmp);
146 
147         for kv in self.items.values_mut() {
148             match &mut kv.value {
149                 Item::Table(table) if table.is_dotted() => {
150                     table.sort_values_by_internal(compare);
151                 }
152                 _ => {}
153             }
154         }
155     }
156 
157     /// If a table has no key/value pairs and implicit, it will not be displayed.
158     ///
159     /// # Examples
160     ///
161     /// ```notrust
162     /// [target."x86_64/windows.json".dependencies]
163     /// ```
164     ///
165     /// In the document above, tables `target` and `target."x86_64/windows.json"` are implicit.
166     ///
167     /// ```
168     /// # #[cfg(feature = "parse")] {
169     /// # #[cfg(feature = "display")] {
170     /// use toml_edit::DocumentMut;
171     /// let mut doc = "[a]\n[a.b]\n".parse::<DocumentMut>().expect("invalid toml");
172     ///
173     /// doc["a"].as_table_mut().unwrap().set_implicit(true);
174     /// assert_eq!(doc.to_string(), "[a.b]\n");
175     /// # }
176     /// # }
177     /// ```
set_implicit(&mut self, implicit: bool)178     pub fn set_implicit(&mut self, implicit: bool) {
179         self.implicit = implicit;
180     }
181 
182     /// If a table has no key/value pairs and implicit, it will not be displayed.
is_implicit(&self) -> bool183     pub fn is_implicit(&self) -> bool {
184         self.implicit
185     }
186 
187     /// Change this table's dotted status
set_dotted(&mut self, yes: bool)188     pub fn set_dotted(&mut self, yes: bool) {
189         self.dotted = yes;
190     }
191 
192     /// Check if this is a wrapper for dotted keys, rather than a standard table
is_dotted(&self) -> bool193     pub fn is_dotted(&self) -> bool {
194         self.dotted
195     }
196 
197     /// Sets the position of the `Table` within the [`DocumentMut`][crate::DocumentMut].
set_position(&mut self, doc_position: usize)198     pub fn set_position(&mut self, doc_position: usize) {
199         self.doc_position = Some(doc_position);
200     }
201 
202     /// The position of the `Table` within the [`DocumentMut`][crate::DocumentMut].
203     ///
204     /// Returns `None` if the `Table` was created manually (i.e. not via parsing)
205     /// in which case its position is set automatically.  This can be overridden with
206     /// [`Table::set_position`].
position(&self) -> Option<usize>207     pub fn position(&self) -> Option<usize> {
208         self.doc_position
209     }
210 
211     /// Returns the surrounding whitespace
decor_mut(&mut self) -> &mut Decor212     pub fn decor_mut(&mut self) -> &mut Decor {
213         &mut self.decor
214     }
215 
216     /// Returns the decor associated with a given key of the table.
decor(&self) -> &Decor217     pub fn decor(&self) -> &Decor {
218         &self.decor
219     }
220 
221     /// Returns an accessor to a key's formatting
key(&self, key: &str) -> Option<&'_ Key>222     pub fn key(&self, key: &str) -> Option<&'_ Key> {
223         self.items.get(key).map(|kv| &kv.key)
224     }
225 
226     /// Returns an accessor to a key's formatting
key_mut(&mut self, key: &str) -> Option<KeyMut<'_>>227     pub fn key_mut(&mut self, key: &str) -> Option<KeyMut<'_>> {
228         self.items.get_mut(key).map(|kv| kv.key.as_mut())
229     }
230 
231     /// Returns the decor associated with a given key of the table.
232     #[deprecated(since = "0.21.1", note = "Replaced with `key_mut`")]
key_decor_mut(&mut self, key: &str) -> Option<&mut Decor>233     pub fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor> {
234         #![allow(deprecated)]
235         self.items.get_mut(key).map(|kv| kv.key.leaf_decor_mut())
236     }
237 
238     /// Returns the decor associated with a given key of the table.
239     #[deprecated(since = "0.21.1", note = "Replaced with `key_mut`")]
key_decor(&self, key: &str) -> Option<&Decor>240     pub fn key_decor(&self, key: &str) -> Option<&Decor> {
241         #![allow(deprecated)]
242         self.items.get(key).map(|kv| kv.key.leaf_decor())
243     }
244 
245     /// The location within the original document
246     ///
247     /// This generally requires an [`ImDocument`][crate::ImDocument].
span(&self) -> Option<std::ops::Range<usize>>248     pub fn span(&self) -> Option<std::ops::Range<usize>> {
249         self.span.clone()
250     }
251 
despan(&mut self, input: &str)252     pub(crate) fn despan(&mut self, input: &str) {
253         self.span = None;
254         self.decor.despan(input);
255         for kv in self.items.values_mut() {
256             kv.key.despan(input);
257             kv.value.despan(input);
258         }
259     }
260 }
261 
262 impl Table {
263     /// Returns an iterator over all key/value pairs, including empty.
iter(&self) -> Iter<'_>264     pub fn iter(&self) -> Iter<'_> {
265         Box::new(
266             self.items
267                 .iter()
268                 .filter(|(_, kv)| !kv.value.is_none())
269                 .map(|(key, kv)| (&key[..], &kv.value)),
270         )
271     }
272 
273     /// Returns an mutable iterator over all key/value pairs, including empty.
iter_mut(&mut self) -> IterMut<'_>274     pub fn iter_mut(&mut self) -> IterMut<'_> {
275         Box::new(
276             self.items
277                 .iter_mut()
278                 .filter(|(_, kv)| !kv.value.is_none())
279                 .map(|(_, kv)| (kv.key.as_mut(), &mut kv.value)),
280         )
281     }
282 
283     /// Returns the number of non-empty items in the table.
len(&self) -> usize284     pub fn len(&self) -> usize {
285         self.items.iter().filter(|i| !(i.1).value.is_none()).count()
286     }
287 
288     /// Returns true if the table is empty.
is_empty(&self) -> bool289     pub fn is_empty(&self) -> bool {
290         self.len() == 0
291     }
292 
293     /// Clears the table, removing all key-value pairs. Keeps the allocated memory for reuse.
clear(&mut self)294     pub fn clear(&mut self) {
295         self.items.clear();
296     }
297 
298     /// Gets the given key's corresponding entry in the Table for in-place manipulation.
entry<'a>(&'a mut self, key: &str) -> Entry<'a>299     pub fn entry<'a>(&'a mut self, key: &str) -> Entry<'a> {
300         // Accept a `&str` rather than an owned type to keep `InternalString`, well, internal
301         match self.items.entry(key.into()) {
302             indexmap::map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { entry }),
303             indexmap::map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry { entry, key: None }),
304         }
305     }
306 
307     /// Gets the given key's corresponding entry in the Table for in-place manipulation.
entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a>308     pub fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a> {
309         // Accept a `&Key` to be consistent with `entry`
310         match self.items.entry(key.get().into()) {
311             indexmap::map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { entry }),
312             indexmap::map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry {
313                 entry,
314                 key: Some(key.to_owned()),
315             }),
316         }
317     }
318 
319     /// Returns an optional reference to an item given the key.
get<'a>(&'a self, key: &str) -> Option<&'a Item>320     pub fn get<'a>(&'a self, key: &str) -> Option<&'a Item> {
321         self.items.get(key).and_then(|kv| {
322             if !kv.value.is_none() {
323                 Some(&kv.value)
324             } else {
325                 None
326             }
327         })
328     }
329 
330     /// Returns an optional mutable reference to an item given the key.
get_mut<'a>(&'a mut self, key: &str) -> Option<&'a mut Item>331     pub fn get_mut<'a>(&'a mut self, key: &str) -> Option<&'a mut Item> {
332         self.items.get_mut(key).and_then(|kv| {
333             if !kv.value.is_none() {
334                 Some(&mut kv.value)
335             } else {
336                 None
337             }
338         })
339     }
340 
341     /// Return references to the key-value pair stored for key, if it is present, else None.
get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)>342     pub fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)> {
343         self.items.get(key).and_then(|kv| {
344             if !kv.value.is_none() {
345                 Some((&kv.key, &kv.value))
346             } else {
347                 None
348             }
349         })
350     }
351 
352     /// Return mutable references to the key-value pair stored for key, if it is present, else None.
get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)>353     pub fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)> {
354         self.items.get_mut(key).and_then(|kv| {
355             if !kv.value.is_none() {
356                 Some((kv.key.as_mut(), &mut kv.value))
357             } else {
358                 None
359             }
360         })
361     }
362 
363     /// Returns true if the table contains an item with the given key.
contains_key(&self, key: &str) -> bool364     pub fn contains_key(&self, key: &str) -> bool {
365         if let Some(kv) = self.items.get(key) {
366             !kv.value.is_none()
367         } else {
368             false
369         }
370     }
371 
372     /// Returns true if the table contains a table with the given key.
contains_table(&self, key: &str) -> bool373     pub fn contains_table(&self, key: &str) -> bool {
374         if let Some(kv) = self.items.get(key) {
375             kv.value.is_table()
376         } else {
377             false
378         }
379     }
380 
381     /// Returns true if the table contains a value with the given key.
contains_value(&self, key: &str) -> bool382     pub fn contains_value(&self, key: &str) -> bool {
383         if let Some(kv) = self.items.get(key) {
384             kv.value.is_value()
385         } else {
386             false
387         }
388     }
389 
390     /// Returns true if the table contains an array of tables with the given key.
contains_array_of_tables(&self, key: &str) -> bool391     pub fn contains_array_of_tables(&self, key: &str) -> bool {
392         if let Some(kv) = self.items.get(key) {
393             kv.value.is_array_of_tables()
394         } else {
395             false
396         }
397     }
398 
399     /// Inserts a key-value pair into the map.
insert(&mut self, key: &str, item: Item) -> Option<Item>400     pub fn insert(&mut self, key: &str, item: Item) -> Option<Item> {
401         let kv = TableKeyValue::new(Key::new(key), item);
402         self.items.insert(key.into(), kv).map(|kv| kv.value)
403     }
404 
405     /// Inserts a key-value pair into the map.
insert_formatted(&mut self, key: &Key, item: Item) -> Option<Item>406     pub fn insert_formatted(&mut self, key: &Key, item: Item) -> Option<Item> {
407         let kv = TableKeyValue::new(key.to_owned(), item);
408         self.items.insert(key.get().into(), kv).map(|kv| kv.value)
409     }
410 
411     /// Removes an item given the key.
remove(&mut self, key: &str) -> Option<Item>412     pub fn remove(&mut self, key: &str) -> Option<Item> {
413         self.items.shift_remove(key).map(|kv| kv.value)
414     }
415 
416     /// Removes a key from the map, returning the stored key and value if the key was previously in the map.
remove_entry(&mut self, key: &str) -> Option<(Key, Item)>417     pub fn remove_entry(&mut self, key: &str) -> Option<(Key, Item)> {
418         self.items.shift_remove(key).map(|kv| (kv.key, kv.value))
419     }
420 
421     /// Retains only the elements specified by the `keep` predicate.
422     ///
423     /// In other words, remove all pairs `(key, item)` for which
424     /// `keep(&key, &mut item)` returns `false`.
425     ///
426     /// The elements are visited in iteration order.
retain<F>(&mut self, mut keep: F) where F: FnMut(&str, &mut Item) -> bool,427     pub fn retain<F>(&mut self, mut keep: F)
428     where
429         F: FnMut(&str, &mut Item) -> bool,
430     {
431         self.items
432             .retain(|key, key_value| keep(key, &mut key_value.value));
433     }
434 }
435 
436 #[cfg(feature = "display")]
437 impl std::fmt::Display for Table {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result438     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
439         let children = self.get_values();
440         // print table body
441         for (key_path, value) in children {
442             crate::encode::encode_key_path_ref(&key_path, f, None, DEFAULT_KEY_DECOR)?;
443             write!(f, "=")?;
444             crate::encode::encode_value(value, f, None, DEFAULT_VALUE_DECOR)?;
445             writeln!(f)?;
446         }
447         Ok(())
448     }
449 }
450 
451 impl<K: Into<Key>, V: Into<Value>> Extend<(K, V)> for Table {
extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T)452     fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
453         for (key, value) in iter {
454             let key = key.into();
455             let value = Item::Value(value.into());
456             let value = TableKeyValue::new(key, value);
457             self.items.insert(value.key.get().into(), value);
458         }
459     }
460 }
461 
462 impl<K: Into<Key>, V: Into<Value>> FromIterator<(K, V)> for Table {
from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = (K, V)>,463     fn from_iter<I>(iter: I) -> Self
464     where
465         I: IntoIterator<Item = (K, V)>,
466     {
467         let mut table = Table::new();
468         table.extend(iter);
469         table
470     }
471 }
472 
473 impl IntoIterator for Table {
474     type Item = (InternalString, Item);
475     type IntoIter = IntoIter;
476 
into_iter(self) -> Self::IntoIter477     fn into_iter(self) -> Self::IntoIter {
478         Box::new(self.items.into_iter().map(|(k, kv)| (k, kv.value)))
479     }
480 }
481 
482 impl<'s> IntoIterator for &'s Table {
483     type Item = (&'s str, &'s Item);
484     type IntoIter = Iter<'s>;
485 
into_iter(self) -> Self::IntoIter486     fn into_iter(self) -> Self::IntoIter {
487         self.iter()
488     }
489 }
490 
491 pub(crate) type KeyValuePairs = IndexMap<InternalString, TableKeyValue>;
492 
decorate_table(table: &mut Table)493 fn decorate_table(table: &mut Table) {
494     for (mut key, value) in table
495         .items
496         .iter_mut()
497         .filter(|(_, kv)| kv.value.is_value())
498         .map(|(_, kv)| (kv.key.as_mut(), kv.value.as_value_mut().unwrap()))
499     {
500         key.leaf_decor_mut().clear();
501         key.dotted_decor_mut().clear();
502         value.decor_mut().clear();
503     }
504 }
505 
506 // `key1 = value1`
507 pub(crate) const DEFAULT_ROOT_DECOR: (&str, &str) = ("", "");
508 pub(crate) const DEFAULT_KEY_DECOR: (&str, &str) = ("", " ");
509 pub(crate) const DEFAULT_TABLE_DECOR: (&str, &str) = ("\n", "");
510 pub(crate) const DEFAULT_KEY_PATH_DECOR: (&str, &str) = ("", "");
511 
512 #[derive(Debug, Clone)]
513 pub(crate) struct TableKeyValue {
514     pub(crate) key: Key,
515     pub(crate) value: Item,
516 }
517 
518 impl TableKeyValue {
new(key: Key, value: Item) -> Self519     pub(crate) fn new(key: Key, value: Item) -> Self {
520         TableKeyValue { key, value }
521     }
522 }
523 
524 /// An owned iterator type over `Table`'s key/value pairs.
525 pub type IntoIter = Box<dyn Iterator<Item = (InternalString, Item)>>;
526 /// An iterator type over `Table`'s key/value pairs.
527 pub type Iter<'a> = Box<dyn Iterator<Item = (&'a str, &'a Item)> + 'a>;
528 /// A mutable iterator type over `Table`'s key/value pairs.
529 pub type IterMut<'a> = Box<dyn Iterator<Item = (KeyMut<'a>, &'a mut Item)> + 'a>;
530 
531 /// This trait represents either a `Table`, or an `InlineTable`.
532 pub trait TableLike: crate::private::Sealed {
533     /// Returns an iterator over key/value pairs.
iter(&self) -> Iter<'_>534     fn iter(&self) -> Iter<'_>;
535     /// Returns an mutable iterator over all key/value pairs, including empty.
iter_mut(&mut self) -> IterMut<'_>536     fn iter_mut(&mut self) -> IterMut<'_>;
537     /// Returns the number of nonempty items.
len(&self) -> usize538     fn len(&self) -> usize {
539         self.iter().filter(|&(_, v)| !v.is_none()).count()
540     }
541     /// Returns true if the table is empty.
is_empty(&self) -> bool542     fn is_empty(&self) -> bool {
543         self.len() == 0
544     }
545     /// Clears the table, removing all key-value pairs. Keeps the allocated memory for reuse.
clear(&mut self)546     fn clear(&mut self);
547     /// Gets the given key's corresponding entry in the Table for in-place manipulation.
entry<'a>(&'a mut self, key: &str) -> Entry<'a>548     fn entry<'a>(&'a mut self, key: &str) -> Entry<'a>;
549     /// Gets the given key's corresponding entry in the Table for in-place manipulation.
entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a>550     fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a>;
551     /// Returns an optional reference to an item given the key.
get<'s>(&'s self, key: &str) -> Option<&'s Item>552     fn get<'s>(&'s self, key: &str) -> Option<&'s Item>;
553     /// Returns an optional mutable reference to an item given the key.
get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item>554     fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item>;
555     /// Return references to the key-value pair stored for key, if it is present, else None.
get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)>556     fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)>;
557     /// Return mutable references to the key-value pair stored for key, if it is present, else None.
get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)>558     fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)>;
559     /// Returns true if the table contains an item with the given key.
contains_key(&self, key: &str) -> bool560     fn contains_key(&self, key: &str) -> bool;
561     /// Inserts a key-value pair into the map.
insert(&mut self, key: &str, value: Item) -> Option<Item>562     fn insert(&mut self, key: &str, value: Item) -> Option<Item>;
563     /// Removes an item given the key.
remove(&mut self, key: &str) -> Option<Item>564     fn remove(&mut self, key: &str) -> Option<Item>;
565 
566     /// Get key/values for values that are visually children of this table
567     ///
568     /// For example, this will return dotted keys
get_values(&self) -> Vec<(Vec<&Key>, &Value)>569     fn get_values(&self) -> Vec<(Vec<&Key>, &Value)>;
570 
571     /// Auto formats the table.
fmt(&mut self)572     fn fmt(&mut self);
573     /// Sorts Key/Value Pairs of the table.
574     ///
575     /// Doesn't affect subtables or subarrays.
sort_values(&mut self)576     fn sort_values(&mut self);
577     /// Change this table's dotted status
set_dotted(&mut self, yes: bool)578     fn set_dotted(&mut self, yes: bool);
579     /// Check if this is a wrapper for dotted keys, rather than a standard table
is_dotted(&self) -> bool580     fn is_dotted(&self) -> bool;
581 
582     /// Returns an accessor to a key's formatting
key(&self, key: &str) -> Option<&'_ Key>583     fn key(&self, key: &str) -> Option<&'_ Key>;
584     /// Returns an accessor to a key's formatting
key_mut(&mut self, key: &str) -> Option<KeyMut<'_>>585     fn key_mut(&mut self, key: &str) -> Option<KeyMut<'_>>;
586     /// Returns the decor associated with a given key of the table.
587     #[deprecated(since = "0.21.1", note = "Replaced with `key_mut`")]
key_decor_mut(&mut self, key: &str) -> Option<&mut Decor>588     fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor>;
589     /// Returns the decor associated with a given key of the table.
590     #[deprecated(since = "0.21.1", note = "Replaced with `key_mut`")]
key_decor(&self, key: &str) -> Option<&Decor>591     fn key_decor(&self, key: &str) -> Option<&Decor>;
592 }
593 
594 impl TableLike for Table {
iter(&self) -> Iter<'_>595     fn iter(&self) -> Iter<'_> {
596         self.iter()
597     }
iter_mut(&mut self) -> IterMut<'_>598     fn iter_mut(&mut self) -> IterMut<'_> {
599         self.iter_mut()
600     }
clear(&mut self)601     fn clear(&mut self) {
602         self.clear();
603     }
entry<'a>(&'a mut self, key: &str) -> Entry<'a>604     fn entry<'a>(&'a mut self, key: &str) -> Entry<'a> {
605         self.entry(key)
606     }
entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a>607     fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a> {
608         self.entry_format(key)
609     }
get<'s>(&'s self, key: &str) -> Option<&'s Item>610     fn get<'s>(&'s self, key: &str) -> Option<&'s Item> {
611         self.get(key)
612     }
get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item>613     fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item> {
614         self.get_mut(key)
615     }
get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)>616     fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)> {
617         self.get_key_value(key)
618     }
get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)>619     fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)> {
620         self.get_key_value_mut(key)
621     }
contains_key(&self, key: &str) -> bool622     fn contains_key(&self, key: &str) -> bool {
623         self.contains_key(key)
624     }
insert(&mut self, key: &str, value: Item) -> Option<Item>625     fn insert(&mut self, key: &str, value: Item) -> Option<Item> {
626         self.insert(key, value)
627     }
remove(&mut self, key: &str) -> Option<Item>628     fn remove(&mut self, key: &str) -> Option<Item> {
629         self.remove(key)
630     }
631 
get_values(&self) -> Vec<(Vec<&Key>, &Value)>632     fn get_values(&self) -> Vec<(Vec<&Key>, &Value)> {
633         self.get_values()
634     }
fmt(&mut self)635     fn fmt(&mut self) {
636         self.fmt();
637     }
sort_values(&mut self)638     fn sort_values(&mut self) {
639         self.sort_values();
640     }
is_dotted(&self) -> bool641     fn is_dotted(&self) -> bool {
642         self.is_dotted()
643     }
set_dotted(&mut self, yes: bool)644     fn set_dotted(&mut self, yes: bool) {
645         self.set_dotted(yes);
646     }
647 
key(&self, key: &str) -> Option<&'_ Key>648     fn key(&self, key: &str) -> Option<&'_ Key> {
649         self.key(key)
650     }
key_mut(&mut self, key: &str) -> Option<KeyMut<'_>>651     fn key_mut(&mut self, key: &str) -> Option<KeyMut<'_>> {
652         self.key_mut(key)
653     }
key_decor_mut(&mut self, key: &str) -> Option<&mut Decor>654     fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor> {
655         #![allow(deprecated)]
656         self.key_decor_mut(key)
657     }
key_decor(&self, key: &str) -> Option<&Decor>658     fn key_decor(&self, key: &str) -> Option<&Decor> {
659         #![allow(deprecated)]
660         self.key_decor(key)
661     }
662 }
663 
664 /// A view into a single location in a map, which may be vacant or occupied.
665 pub enum Entry<'a> {
666     /// An occupied Entry.
667     Occupied(OccupiedEntry<'a>),
668     /// A vacant Entry.
669     Vacant(VacantEntry<'a>),
670 }
671 
672 impl<'a> Entry<'a> {
673     /// Returns the entry key
674     ///
675     /// # Examples
676     ///
677     /// ```
678     /// use toml_edit::Table;
679     ///
680     /// let mut map = Table::new();
681     ///
682     /// assert_eq!("hello", map.entry("hello").key());
683     /// ```
key(&self) -> &str684     pub fn key(&self) -> &str {
685         match self {
686             Entry::Occupied(e) => e.key(),
687             Entry::Vacant(e) => e.key(),
688         }
689     }
690 
691     /// Ensures a value is in the entry by inserting the default if empty, and returns
692     /// a mutable reference to the value in the entry.
or_insert(self, default: Item) -> &'a mut Item693     pub fn or_insert(self, default: Item) -> &'a mut Item {
694         match self {
695             Entry::Occupied(entry) => entry.into_mut(),
696             Entry::Vacant(entry) => entry.insert(default),
697         }
698     }
699 
700     /// Ensures a value is in the entry by inserting the result of the default function if empty,
701     /// and returns a mutable reference to the value in the entry.
or_insert_with<F: FnOnce() -> Item>(self, default: F) -> &'a mut Item702     pub fn or_insert_with<F: FnOnce() -> Item>(self, default: F) -> &'a mut Item {
703         match self {
704             Entry::Occupied(entry) => entry.into_mut(),
705             Entry::Vacant(entry) => entry.insert(default()),
706         }
707     }
708 }
709 
710 /// A view into a single occupied location in a `IndexMap`.
711 pub struct OccupiedEntry<'a> {
712     pub(crate) entry: indexmap::map::OccupiedEntry<'a, InternalString, TableKeyValue>,
713 }
714 
715 impl<'a> OccupiedEntry<'a> {
716     /// Gets a reference to the entry key
717     ///
718     /// # Examples
719     ///
720     /// ```
721     /// use toml_edit::Table;
722     ///
723     /// let mut map = Table::new();
724     ///
725     /// assert_eq!("foo", map.entry("foo").key());
726     /// ```
key(&self) -> &str727     pub fn key(&self) -> &str {
728         self.entry.key().as_str()
729     }
730 
731     /// Gets a mutable reference to the entry key
key_mut(&mut self) -> KeyMut<'_>732     pub fn key_mut(&mut self) -> KeyMut<'_> {
733         self.entry.get_mut().key.as_mut()
734     }
735 
736     /// Gets a reference to the value in the entry.
get(&self) -> &Item737     pub fn get(&self) -> &Item {
738         &self.entry.get().value
739     }
740 
741     /// Gets a mutable reference to the value in the entry.
get_mut(&mut self) -> &mut Item742     pub fn get_mut(&mut self) -> &mut Item {
743         &mut self.entry.get_mut().value
744     }
745 
746     /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
747     /// with a lifetime bound to the map itself
into_mut(self) -> &'a mut Item748     pub fn into_mut(self) -> &'a mut Item {
749         &mut self.entry.into_mut().value
750     }
751 
752     /// Sets the value of the entry, and returns the entry's old value
insert(&mut self, mut value: Item) -> Item753     pub fn insert(&mut self, mut value: Item) -> Item {
754         std::mem::swap(&mut value, &mut self.entry.get_mut().value);
755         value
756     }
757 
758     /// Takes the value out of the entry, and returns it
remove(self) -> Item759     pub fn remove(self) -> Item {
760         self.entry.shift_remove().value
761     }
762 }
763 
764 /// A view into a single empty location in a `IndexMap`.
765 pub struct VacantEntry<'a> {
766     pub(crate) entry: indexmap::map::VacantEntry<'a, InternalString, TableKeyValue>,
767     pub(crate) key: Option<Key>,
768 }
769 
770 impl<'a> VacantEntry<'a> {
771     /// Gets a reference to the entry key
772     ///
773     /// # Examples
774     ///
775     /// ```
776     /// use toml_edit::Table;
777     ///
778     /// let mut map = Table::new();
779     ///
780     /// assert_eq!("foo", map.entry("foo").key());
781     /// ```
key(&self) -> &str782     pub fn key(&self) -> &str {
783         self.entry.key().as_str()
784     }
785 
786     /// Sets the value of the entry with the `VacantEntry`'s key,
787     /// and returns a mutable reference to it
insert(self, value: Item) -> &'a mut Item788     pub fn insert(self, value: Item) -> &'a mut Item {
789         let entry = self.entry;
790         let key = self.key.unwrap_or_else(|| Key::new(entry.key().as_str()));
791         &mut entry.insert(TableKeyValue::new(key, value)).value
792     }
793 }
794