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::Document;
171 /// let mut doc = "[a]\n[a.b]\n".parse::<Document>().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 `Document`.
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 `Document`.
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 /// Returns the location within the original document
span(&self) -> Option<std::ops::Range<usize>>246 pub(crate) fn span(&self) -> Option<std::ops::Range<usize>> {
247 self.span.clone()
248 }
249
despan(&mut self, input: &str)250 pub(crate) fn despan(&mut self, input: &str) {
251 self.span = None;
252 self.decor.despan(input);
253 for kv in self.items.values_mut() {
254 kv.key.despan(input);
255 kv.value.despan(input);
256 }
257 }
258 }
259
260 impl Table {
261 /// Returns an iterator over all key/value pairs, including empty.
iter(&self) -> Iter<'_>262 pub fn iter(&self) -> Iter<'_> {
263 Box::new(
264 self.items
265 .iter()
266 .filter(|(_, kv)| !kv.value.is_none())
267 .map(|(key, kv)| (&key[..], &kv.value)),
268 )
269 }
270
271 /// Returns an mutable iterator over all key/value pairs, including empty.
iter_mut(&mut self) -> IterMut<'_>272 pub fn iter_mut(&mut self) -> IterMut<'_> {
273 Box::new(
274 self.items
275 .iter_mut()
276 .filter(|(_, kv)| !kv.value.is_none())
277 .map(|(_, kv)| (kv.key.as_mut(), &mut kv.value)),
278 )
279 }
280
281 /// Returns the number of non-empty items in the table.
len(&self) -> usize282 pub fn len(&self) -> usize {
283 self.items.iter().filter(|i| !(i.1).value.is_none()).count()
284 }
285
286 /// Returns true if the table is empty.
is_empty(&self) -> bool287 pub fn is_empty(&self) -> bool {
288 self.len() == 0
289 }
290
291 /// Clears the table, removing all key-value pairs. Keeps the allocated memory for reuse.
clear(&mut self)292 pub fn clear(&mut self) {
293 self.items.clear()
294 }
295
296 /// Gets the given key's corresponding entry in the Table for in-place manipulation.
entry<'a>(&'a mut self, key: &str) -> Entry<'a>297 pub fn entry<'a>(&'a mut self, key: &str) -> Entry<'a> {
298 // Accept a `&str` rather than an owned type to keep `InternalString`, well, internal
299 match self.items.entry(key.into()) {
300 indexmap::map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { entry }),
301 indexmap::map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry { entry, key: None }),
302 }
303 }
304
305 /// Gets the given key's corresponding entry in the Table for in-place manipulation.
entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a>306 pub fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a> {
307 // Accept a `&Key` to be consistent with `entry`
308 match self.items.entry(key.get().into()) {
309 indexmap::map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { entry }),
310 indexmap::map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry {
311 entry,
312 key: Some(key.to_owned()),
313 }),
314 }
315 }
316
317 /// Returns an optional reference to an item given the key.
get<'a>(&'a self, key: &str) -> Option<&'a Item>318 pub fn get<'a>(&'a self, key: &str) -> Option<&'a Item> {
319 self.items.get(key).and_then(|kv| {
320 if !kv.value.is_none() {
321 Some(&kv.value)
322 } else {
323 None
324 }
325 })
326 }
327
328 /// Returns an optional mutable reference to an item given the key.
get_mut<'a>(&'a mut self, key: &str) -> Option<&'a mut Item>329 pub fn get_mut<'a>(&'a mut self, key: &str) -> Option<&'a mut Item> {
330 self.items.get_mut(key).and_then(|kv| {
331 if !kv.value.is_none() {
332 Some(&mut kv.value)
333 } else {
334 None
335 }
336 })
337 }
338
339 /// 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)>340 pub fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)> {
341 self.items.get(key).and_then(|kv| {
342 if !kv.value.is_none() {
343 Some((&kv.key, &kv.value))
344 } else {
345 None
346 }
347 })
348 }
349
350 /// 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)>351 pub fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)> {
352 self.items.get_mut(key).and_then(|kv| {
353 if !kv.value.is_none() {
354 Some((kv.key.as_mut(), &mut kv.value))
355 } else {
356 None
357 }
358 })
359 }
360
361 /// Returns true if the table contains an item with the given key.
contains_key(&self, key: &str) -> bool362 pub fn contains_key(&self, key: &str) -> bool {
363 if let Some(kv) = self.items.get(key) {
364 !kv.value.is_none()
365 } else {
366 false
367 }
368 }
369
370 /// Returns true if the table contains a table with the given key.
contains_table(&self, key: &str) -> bool371 pub fn contains_table(&self, key: &str) -> bool {
372 if let Some(kv) = self.items.get(key) {
373 kv.value.is_table()
374 } else {
375 false
376 }
377 }
378
379 /// Returns true if the table contains a value with the given key.
contains_value(&self, key: &str) -> bool380 pub fn contains_value(&self, key: &str) -> bool {
381 if let Some(kv) = self.items.get(key) {
382 kv.value.is_value()
383 } else {
384 false
385 }
386 }
387
388 /// Returns true if the table contains an array of tables with the given key.
contains_array_of_tables(&self, key: &str) -> bool389 pub fn contains_array_of_tables(&self, key: &str) -> bool {
390 if let Some(kv) = self.items.get(key) {
391 kv.value.is_array_of_tables()
392 } else {
393 false
394 }
395 }
396
397 /// Inserts a key-value pair into the map.
insert(&mut self, key: &str, item: Item) -> Option<Item>398 pub fn insert(&mut self, key: &str, item: Item) -> Option<Item> {
399 let kv = TableKeyValue::new(Key::new(key), item);
400 self.items.insert(key.into(), kv).map(|kv| kv.value)
401 }
402
403 /// Inserts a key-value pair into the map.
insert_formatted(&mut self, key: &Key, item: Item) -> Option<Item>404 pub fn insert_formatted(&mut self, key: &Key, item: Item) -> Option<Item> {
405 let kv = TableKeyValue::new(key.to_owned(), item);
406 self.items.insert(key.get().into(), kv).map(|kv| kv.value)
407 }
408
409 /// Removes an item given the key.
remove(&mut self, key: &str) -> Option<Item>410 pub fn remove(&mut self, key: &str) -> Option<Item> {
411 self.items.shift_remove(key).map(|kv| kv.value)
412 }
413
414 /// 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)>415 pub fn remove_entry(&mut self, key: &str) -> Option<(Key, Item)> {
416 self.items.shift_remove(key).map(|kv| (kv.key, kv.value))
417 }
418
419 /// Retains only the elements specified by the `keep` predicate.
420 ///
421 /// In other words, remove all pairs `(key, item)` for which
422 /// `keep(&key, &mut item)` returns `false`.
423 ///
424 /// The elements are visited in iteration order.
retain<F>(&mut self, mut keep: F) where F: FnMut(&str, &mut Item) -> bool,425 pub fn retain<F>(&mut self, mut keep: F)
426 where
427 F: FnMut(&str, &mut Item) -> bool,
428 {
429 self.items
430 .retain(|key, key_value| keep(key, &mut key_value.value));
431 }
432 }
433
434 #[cfg(feature = "display")]
435 impl std::fmt::Display for Table {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result436 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
437 let children = self.get_values();
438 // print table body
439 for (key_path, value) in children {
440 crate::encode::encode_key_path_ref(&key_path, f, None, DEFAULT_KEY_DECOR)?;
441 write!(f, "=")?;
442 crate::encode::encode_value(value, f, None, DEFAULT_VALUE_DECOR)?;
443 writeln!(f)?;
444 }
445 Ok(())
446 }
447 }
448
449 impl<K: Into<Key>, V: Into<Value>> Extend<(K, V)> for Table {
extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T)450 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
451 for (key, value) in iter {
452 let key = key.into();
453 let value = Item::Value(value.into());
454 let value = TableKeyValue::new(key, value);
455 self.items.insert(value.key.get().into(), value);
456 }
457 }
458 }
459
460 impl<K: Into<Key>, V: Into<Value>> FromIterator<(K, V)> for Table {
from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = (K, V)>,461 fn from_iter<I>(iter: I) -> Self
462 where
463 I: IntoIterator<Item = (K, V)>,
464 {
465 let mut table = Table::new();
466 table.extend(iter);
467 table
468 }
469 }
470
471 impl IntoIterator for Table {
472 type Item = (InternalString, Item);
473 type IntoIter = IntoIter;
474
into_iter(self) -> Self::IntoIter475 fn into_iter(self) -> Self::IntoIter {
476 Box::new(self.items.into_iter().map(|(k, kv)| (k, kv.value)))
477 }
478 }
479
480 impl<'s> IntoIterator for &'s Table {
481 type Item = (&'s str, &'s Item);
482 type IntoIter = Iter<'s>;
483
into_iter(self) -> Self::IntoIter484 fn into_iter(self) -> Self::IntoIter {
485 self.iter()
486 }
487 }
488
489 pub(crate) type KeyValuePairs = IndexMap<InternalString, TableKeyValue>;
490
decorate_table(table: &mut Table)491 fn decorate_table(table: &mut Table) {
492 for (mut key, value) in table
493 .items
494 .iter_mut()
495 .filter(|(_, kv)| kv.value.is_value())
496 .map(|(_, kv)| (kv.key.as_mut(), kv.value.as_value_mut().unwrap()))
497 {
498 key.leaf_decor_mut().clear();
499 key.dotted_decor_mut().clear();
500 value.decor_mut().clear();
501 }
502 }
503
504 // `key1 = value1`
505 pub(crate) const DEFAULT_KEY_DECOR: (&str, &str) = ("", " ");
506 pub(crate) const DEFAULT_TABLE_DECOR: (&str, &str) = ("\n", "");
507 pub(crate) const DEFAULT_KEY_PATH_DECOR: (&str, &str) = ("", "");
508
509 #[derive(Debug, Clone)]
510 pub(crate) struct TableKeyValue {
511 pub(crate) key: Key,
512 pub(crate) value: Item,
513 }
514
515 impl TableKeyValue {
new(key: Key, value: Item) -> Self516 pub(crate) fn new(key: Key, value: Item) -> Self {
517 TableKeyValue { key, value }
518 }
519 }
520
521 /// An owned iterator type over `Table`'s key/value pairs.
522 pub type IntoIter = Box<dyn Iterator<Item = (InternalString, Item)>>;
523 /// An iterator type over `Table`'s key/value pairs.
524 pub type Iter<'a> = Box<dyn Iterator<Item = (&'a str, &'a Item)> + 'a>;
525 /// A mutable iterator type over `Table`'s key/value pairs.
526 pub type IterMut<'a> = Box<dyn Iterator<Item = (KeyMut<'a>, &'a mut Item)> + 'a>;
527
528 /// This trait represents either a `Table`, or an `InlineTable`.
529 pub trait TableLike: crate::private::Sealed {
530 /// Returns an iterator over key/value pairs.
iter(&self) -> Iter<'_>531 fn iter(&self) -> Iter<'_>;
532 /// Returns an mutable iterator over all key/value pairs, including empty.
iter_mut(&mut self) -> IterMut<'_>533 fn iter_mut(&mut self) -> IterMut<'_>;
534 /// Returns the number of nonempty items.
len(&self) -> usize535 fn len(&self) -> usize {
536 self.iter().filter(|&(_, v)| !v.is_none()).count()
537 }
538 /// Returns true if the table is empty.
is_empty(&self) -> bool539 fn is_empty(&self) -> bool {
540 self.len() == 0
541 }
542 /// Clears the table, removing all key-value pairs. Keeps the allocated memory for reuse.
clear(&mut self)543 fn clear(&mut self);
544 /// Gets the given key's corresponding entry in the Table for in-place manipulation.
entry<'a>(&'a mut self, key: &str) -> Entry<'a>545 fn entry<'a>(&'a mut self, key: &str) -> Entry<'a>;
546 /// Gets the given key's corresponding entry in the Table for in-place manipulation.
entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a>547 fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a>;
548 /// Returns an optional reference to an item given the key.
get<'s>(&'s self, key: &str) -> Option<&'s Item>549 fn get<'s>(&'s self, key: &str) -> Option<&'s Item>;
550 /// Returns an optional mutable reference to an item given the key.
get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item>551 fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item>;
552 /// 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)>553 fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)>;
554 /// 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)>555 fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)>;
556 /// Returns true if the table contains an item with the given key.
contains_key(&self, key: &str) -> bool557 fn contains_key(&self, key: &str) -> bool;
558 /// Inserts a key-value pair into the map.
insert(&mut self, key: &str, value: Item) -> Option<Item>559 fn insert(&mut self, key: &str, value: Item) -> Option<Item>;
560 /// Removes an item given the key.
remove(&mut self, key: &str) -> Option<Item>561 fn remove(&mut self, key: &str) -> Option<Item>;
562
563 /// Get key/values for values that are visually children of this table
564 ///
565 /// For example, this will return dotted keys
get_values(&self) -> Vec<(Vec<&Key>, &Value)>566 fn get_values(&self) -> Vec<(Vec<&Key>, &Value)>;
567
568 /// Auto formats the table.
fmt(&mut self)569 fn fmt(&mut self);
570 /// Sorts Key/Value Pairs of the table.
571 ///
572 /// Doesn't affect subtables or subarrays.
sort_values(&mut self)573 fn sort_values(&mut self);
574 /// Change this table's dotted status
set_dotted(&mut self, yes: bool)575 fn set_dotted(&mut self, yes: bool);
576 /// Check if this is a wrapper for dotted keys, rather than a standard table
is_dotted(&self) -> bool577 fn is_dotted(&self) -> bool;
578
579 /// Returns an accessor to a key's formatting
key(&self, key: &str) -> Option<&'_ Key>580 fn key(&self, key: &str) -> Option<&'_ Key>;
581 /// Returns an accessor to a key's formatting
key_mut(&mut self, key: &str) -> Option<KeyMut<'_>>582 fn key_mut(&mut self, key: &str) -> Option<KeyMut<'_>>;
583 /// Returns the decor associated with a given key of the table.
584 #[deprecated(since = "0.21.1", note = "Replaced with `key_mut`")]
key_decor_mut(&mut self, key: &str) -> Option<&mut Decor>585 fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor>;
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(&self, key: &str) -> Option<&Decor>588 fn key_decor(&self, key: &str) -> Option<&Decor>;
589 }
590
591 impl TableLike for Table {
iter(&self) -> Iter<'_>592 fn iter(&self) -> Iter<'_> {
593 self.iter()
594 }
iter_mut(&mut self) -> IterMut<'_>595 fn iter_mut(&mut self) -> IterMut<'_> {
596 self.iter_mut()
597 }
clear(&mut self)598 fn clear(&mut self) {
599 self.clear();
600 }
entry<'a>(&'a mut self, key: &str) -> Entry<'a>601 fn entry<'a>(&'a mut self, key: &str) -> Entry<'a> {
602 self.entry(key)
603 }
entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a>604 fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a> {
605 self.entry_format(key)
606 }
get<'s>(&'s self, key: &str) -> Option<&'s Item>607 fn get<'s>(&'s self, key: &str) -> Option<&'s Item> {
608 self.get(key)
609 }
get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item>610 fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item> {
611 self.get_mut(key)
612 }
get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)>613 fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)> {
614 self.get_key_value(key)
615 }
get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)>616 fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)> {
617 self.get_key_value_mut(key)
618 }
contains_key(&self, key: &str) -> bool619 fn contains_key(&self, key: &str) -> bool {
620 self.contains_key(key)
621 }
insert(&mut self, key: &str, value: Item) -> Option<Item>622 fn insert(&mut self, key: &str, value: Item) -> Option<Item> {
623 self.insert(key, value)
624 }
remove(&mut self, key: &str) -> Option<Item>625 fn remove(&mut self, key: &str) -> Option<Item> {
626 self.remove(key)
627 }
628
get_values(&self) -> Vec<(Vec<&Key>, &Value)>629 fn get_values(&self) -> Vec<(Vec<&Key>, &Value)> {
630 self.get_values()
631 }
fmt(&mut self)632 fn fmt(&mut self) {
633 self.fmt()
634 }
sort_values(&mut self)635 fn sort_values(&mut self) {
636 self.sort_values()
637 }
is_dotted(&self) -> bool638 fn is_dotted(&self) -> bool {
639 self.is_dotted()
640 }
set_dotted(&mut self, yes: bool)641 fn set_dotted(&mut self, yes: bool) {
642 self.set_dotted(yes)
643 }
644
key(&self, key: &str) -> Option<&'_ Key>645 fn key(&self, key: &str) -> Option<&'_ Key> {
646 self.key(key)
647 }
key_mut(&mut self, key: &str) -> Option<KeyMut<'_>>648 fn key_mut(&mut self, key: &str) -> Option<KeyMut<'_>> {
649 self.key_mut(key)
650 }
key_decor_mut(&mut self, key: &str) -> Option<&mut Decor>651 fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor> {
652 #![allow(deprecated)]
653 self.key_decor_mut(key)
654 }
key_decor(&self, key: &str) -> Option<&Decor>655 fn key_decor(&self, key: &str) -> Option<&Decor> {
656 #![allow(deprecated)]
657 self.key_decor(key)
658 }
659 }
660
661 /// A view into a single location in a map, which may be vacant or occupied.
662 pub enum Entry<'a> {
663 /// An occupied Entry.
664 Occupied(OccupiedEntry<'a>),
665 /// A vacant Entry.
666 Vacant(VacantEntry<'a>),
667 }
668
669 impl<'a> Entry<'a> {
670 /// Returns the entry key
671 ///
672 /// # Examples
673 ///
674 /// ```
675 /// use toml_edit::Table;
676 ///
677 /// let mut map = Table::new();
678 ///
679 /// assert_eq!("hello", map.entry("hello").key());
680 /// ```
key(&self) -> &str681 pub fn key(&self) -> &str {
682 match self {
683 Entry::Occupied(e) => e.key(),
684 Entry::Vacant(e) => e.key(),
685 }
686 }
687
688 /// Ensures a value is in the entry by inserting the default if empty, and returns
689 /// a mutable reference to the value in the entry.
or_insert(self, default: Item) -> &'a mut Item690 pub fn or_insert(self, default: Item) -> &'a mut Item {
691 match self {
692 Entry::Occupied(entry) => entry.into_mut(),
693 Entry::Vacant(entry) => entry.insert(default),
694 }
695 }
696
697 /// Ensures a value is in the entry by inserting the result of the default function if empty,
698 /// and returns a mutable reference to the value in the entry.
or_insert_with<F: FnOnce() -> Item>(self, default: F) -> &'a mut Item699 pub fn or_insert_with<F: FnOnce() -> Item>(self, default: F) -> &'a mut Item {
700 match self {
701 Entry::Occupied(entry) => entry.into_mut(),
702 Entry::Vacant(entry) => entry.insert(default()),
703 }
704 }
705 }
706
707 /// A view into a single occupied location in a `IndexMap`.
708 pub struct OccupiedEntry<'a> {
709 pub(crate) entry: indexmap::map::OccupiedEntry<'a, InternalString, TableKeyValue>,
710 }
711
712 impl<'a> OccupiedEntry<'a> {
713 /// Gets a reference to the entry key
714 ///
715 /// # Examples
716 ///
717 /// ```
718 /// use toml_edit::Table;
719 ///
720 /// let mut map = Table::new();
721 ///
722 /// assert_eq!("foo", map.entry("foo").key());
723 /// ```
key(&self) -> &str724 pub fn key(&self) -> &str {
725 self.entry.key().as_str()
726 }
727
728 /// Gets a mutable reference to the entry key
key_mut(&mut self) -> KeyMut<'_>729 pub fn key_mut(&mut self) -> KeyMut<'_> {
730 self.entry.get_mut().key.as_mut()
731 }
732
733 /// Gets a reference to the value in the entry.
get(&self) -> &Item734 pub fn get(&self) -> &Item {
735 &self.entry.get().value
736 }
737
738 /// Gets a mutable reference to the value in the entry.
get_mut(&mut self) -> &mut Item739 pub fn get_mut(&mut self) -> &mut Item {
740 &mut self.entry.get_mut().value
741 }
742
743 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
744 /// with a lifetime bound to the map itself
into_mut(self) -> &'a mut Item745 pub fn into_mut(self) -> &'a mut Item {
746 &mut self.entry.into_mut().value
747 }
748
749 /// Sets the value of the entry, and returns the entry's old value
insert(&mut self, mut value: Item) -> Item750 pub fn insert(&mut self, mut value: Item) -> Item {
751 std::mem::swap(&mut value, &mut self.entry.get_mut().value);
752 value
753 }
754
755 /// Takes the value out of the entry, and returns it
remove(self) -> Item756 pub fn remove(self) -> Item {
757 self.entry.shift_remove().value
758 }
759 }
760
761 /// A view into a single empty location in a `IndexMap`.
762 pub struct VacantEntry<'a> {
763 pub(crate) entry: indexmap::map::VacantEntry<'a, InternalString, TableKeyValue>,
764 pub(crate) key: Option<Key>,
765 }
766
767 impl<'a> VacantEntry<'a> {
768 /// Gets a reference to the entry key
769 ///
770 /// # Examples
771 ///
772 /// ```
773 /// use toml_edit::Table;
774 ///
775 /// let mut map = Table::new();
776 ///
777 /// assert_eq!("foo", map.entry("foo").key());
778 /// ```
key(&self) -> &str779 pub fn key(&self) -> &str {
780 self.entry.key().as_str()
781 }
782
783 /// Sets the value of the entry with the VacantEntry's key,
784 /// and returns a mutable reference to it
insert(self, value: Item) -> &'a mut Item785 pub fn insert(self, value: Item) -> &'a mut Item {
786 let entry = self.entry;
787 let key = self.key.unwrap_or_else(|| Key::new(entry.key().as_str()));
788 &mut entry.insert(TableKeyValue::new(key, value)).value
789 }
790 }
791