1use std::iter::FromIterator;
2
3use indexmap::map::IndexMap;
4
5use crate::key::Key;
6use crate::repr::Decor;
7use crate::value::DEFAULT_VALUE_DECOR;
8use crate::{InlineTable, InternalString, Item, KeyMut, Value};
9
10/// Type representing a TOML non-inline table
11#[derive(Clone, Debug, Default)]
12pub 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`
30impl Table {
31 /// Creates an empty table.
32 pub fn new() -> Self {
33 Default::default()
34 }
35
36 pub(crate) fn with_pos(doc_position: Option<usize>) -> Self {
37 Self {
38 doc_position,
39 ..Default::default()
40 }
41 }
42
43 pub(crate) fn with_pairs(items: KeyValuePairs) -> Self {
44 Self {
45 items,
46 ..Default::default()
47 }
48 }
49
50 /// Convert to an inline table
51 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
62impl Table {
63 /// Get key/values for values that are visually children of this table
64 ///
65 /// For example, this will return dotted keys
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
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.
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.
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).
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
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 /// ```
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.
183 pub fn is_implicit(&self) -> bool {
184 self.implicit
185 }
186
187 /// Change this table's dotted status
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
193 pub fn is_dotted(&self) -> bool {
194 self.dotted
195 }
196
197 /// Sets the position of the `Table` within the `Document`.
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`].
207 pub fn position(&self) -> Option<usize> {
208 self.doc_position
209 }
210
211 /// Returns the surrounding whitespace
212 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.
217 pub fn decor(&self) -> &Decor {
218 &self.decor
219 }
220
221 /// Returns the decor associated with a given key of the table.
222 pub fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor> {
223 self.items.get_mut(key).map(|kv| &mut kv.key.decor)
224 }
225
226 /// Returns the decor associated with a given key of the table.
227 pub fn key_decor(&self, key: &str) -> Option<&Decor> {
228 self.items.get(key).map(|kv| &kv.key.decor)
229 }
230
231 /// Returns the location within the original document
232 pub(crate) fn span(&self) -> Option<std::ops::Range<usize>> {
233 self.span.clone()
234 }
235
236 pub(crate) fn despan(&mut self, input: &str) {
237 self.span = None;
238 self.decor.despan(input);
239 for kv in self.items.values_mut() {
240 kv.key.despan(input);
241 kv.value.despan(input);
242 }
243 }
244}
245
246impl Table {
247 /// Returns an iterator over all key/value pairs, including empty.
248 pub fn iter(&self) -> Iter<'_> {
249 Box::new(
250 self.items
251 .iter()
252 .filter(|(_, kv)| !kv.value.is_none())
253 .map(|(key, kv)| (&key[..], &kv.value)),
254 )
255 }
256
257 /// Returns an mutable iterator over all key/value pairs, including empty.
258 pub fn iter_mut(&mut self) -> IterMut<'_> {
259 Box::new(
260 self.items
261 .iter_mut()
262 .filter(|(_, kv)| !kv.value.is_none())
263 .map(|(_, kv)| (kv.key.as_mut(), &mut kv.value)),
264 )
265 }
266
267 /// Returns the number of non-empty items in the table.
268 pub fn len(&self) -> usize {
269 self.items.iter().filter(|i| !(i.1).value.is_none()).count()
270 }
271
272 /// Returns true if the table is empty.
273 pub fn is_empty(&self) -> bool {
274 self.len() == 0
275 }
276
277 /// Clears the table, removing all key-value pairs. Keeps the allocated memory for reuse.
278 pub fn clear(&mut self) {
279 self.items.clear()
280 }
281
282 /// Gets the given key's corresponding entry in the Table for in-place manipulation.
283 pub fn entry<'a>(&'a mut self, key: &str) -> Entry<'a> {
284 // Accept a `&str` rather than an owned type to keep `InternalString`, well, internal
285 match self.items.entry(key.into()) {
286 indexmap::map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { entry }),
287 indexmap::map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry { entry, key: None }),
288 }
289 }
290
291 /// Gets the given key's corresponding entry in the Table for in-place manipulation.
292 pub fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a> {
293 // Accept a `&Key` to be consistent with `entry`
294 match self.items.entry(key.get().into()) {
295 indexmap::map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { entry }),
296 indexmap::map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry {
297 entry,
298 key: Some(key.to_owned()),
299 }),
300 }
301 }
302
303 /// Returns an optional reference to an item given the key.
304 pub fn get<'a>(&'a self, key: &str) -> Option<&'a Item> {
305 self.items.get(key).and_then(|kv| {
306 if !kv.value.is_none() {
307 Some(&kv.value)
308 } else {
309 None
310 }
311 })
312 }
313
314 /// Returns an optional mutable reference to an item given the key.
315 pub fn get_mut<'a>(&'a mut self, key: &str) -> Option<&'a mut Item> {
316 self.items.get_mut(key).and_then(|kv| {
317 if !kv.value.is_none() {
318 Some(&mut kv.value)
319 } else {
320 None
321 }
322 })
323 }
324
325 /// Return references to the key-value pair stored for key, if it is present, else None.
326 pub fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)> {
327 self.items.get(key).and_then(|kv| {
328 if !kv.value.is_none() {
329 Some((&kv.key, &kv.value))
330 } else {
331 None
332 }
333 })
334 }
335
336 /// Return mutable references to the key-value pair stored for key, if it is present, else None.
337 pub fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)> {
338 self.items.get_mut(key).and_then(|kv| {
339 if !kv.value.is_none() {
340 Some((kv.key.as_mut(), &mut kv.value))
341 } else {
342 None
343 }
344 })
345 }
346
347 /// Returns true if the table contains an item with the given key.
348 pub fn contains_key(&self, key: &str) -> bool {
349 if let Some(kv) = self.items.get(key) {
350 !kv.value.is_none()
351 } else {
352 false
353 }
354 }
355
356 /// Returns true if the table contains a table with the given key.
357 pub fn contains_table(&self, key: &str) -> bool {
358 if let Some(kv) = self.items.get(key) {
359 kv.value.is_table()
360 } else {
361 false
362 }
363 }
364
365 /// Returns true if the table contains a value with the given key.
366 pub fn contains_value(&self, key: &str) -> bool {
367 if let Some(kv) = self.items.get(key) {
368 kv.value.is_value()
369 } else {
370 false
371 }
372 }
373
374 /// Returns true if the table contains an array of tables with the given key.
375 pub fn contains_array_of_tables(&self, key: &str) -> bool {
376 if let Some(kv) = self.items.get(key) {
377 kv.value.is_array_of_tables()
378 } else {
379 false
380 }
381 }
382
383 /// Inserts a key-value pair into the map.
384 pub fn insert(&mut self, key: &str, item: Item) -> Option<Item> {
385 let kv = TableKeyValue::new(Key::new(key), item);
386 self.items.insert(key.into(), kv).map(|kv| kv.value)
387 }
388
389 /// Inserts a key-value pair into the map.
390 pub fn insert_formatted(&mut self, key: &Key, item: Item) -> Option<Item> {
391 let kv = TableKeyValue::new(key.to_owned(), item);
392 self.items.insert(key.get().into(), kv).map(|kv| kv.value)
393 }
394
395 /// Removes an item given the key.
396 pub fn remove(&mut self, key: &str) -> Option<Item> {
397 self.items.shift_remove(key).map(|kv| kv.value)
398 }
399
400 /// Removes a key from the map, returning the stored key and value if the key was previously in the map.
401 pub fn remove_entry(&mut self, key: &str) -> Option<(Key, Item)> {
402 self.items.shift_remove(key).map(|kv| (kv.key, kv.value))
403 }
404
405 /// Retains only the elements specified by the `keep` predicate.
406 ///
407 /// In other words, remove all pairs `(key, item)` for which
408 /// `keep(&key, &mut item)` returns `false`.
409 ///
410 /// The elements are visited in iteration order.
411 pub fn retain<F>(&mut self, mut keep: F)
412 where
413 F: FnMut(&str, &mut Item) -> bool,
414 {
415 self.items
416 .retain(|key, key_value| keep(key, &mut key_value.value));
417 }
418}
419
420#[cfg(feature = "display")]
421impl std::fmt::Display for Table {
422 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
423 use crate::encode::Encode;
424 let children: Vec<(Vec<&Key>, &Value)> = self.get_values();
425 // print table body
426 for (key_path: Vec<&Key>, value: &Value) in children {
427 key_path.as_slice().encode(buf:f, input:None, DEFAULT_KEY_DECOR)?;
428 write!(f, "=")?;
429 value.encode(buf:f, input:None, DEFAULT_VALUE_DECOR)?;
430 writeln!(f)?;
431 }
432 Ok(())
433 }
434}
435
436impl<K: Into<Key>, V: Into<Value>> Extend<(K, V)> for Table {
437 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
438 for (key: K, value: V) in iter {
439 let key: Key = key.into();
440 let value: Item = Item::Value(value.into());
441 let value: TableKeyValue = TableKeyValue::new(key, value);
442 self.items.insert(key:value.key.get().into(), value);
443 }
444 }
445}
446
447impl<K: Into<Key>, V: Into<Value>> FromIterator<(K, V)> for Table {
448 fn from_iter<I>(iter: I) -> Self
449 where
450 I: IntoIterator<Item = (K, V)>,
451 {
452 let mut table: Table = Table::new();
453 table.extend(iter);
454 table
455 }
456}
457
458impl IntoIterator for Table {
459 type Item = (InternalString, Item);
460 type IntoIter = IntoIter;
461
462 fn into_iter(self) -> Self::IntoIter {
463 Box::new(self.items.into_iter().map(|(k: InternalString, kv: TableKeyValue)| (k, kv.value)))
464 }
465}
466
467impl<'s> IntoIterator for &'s Table {
468 type Item = (&'s str, &'s Item);
469 type IntoIter = Iter<'s>;
470
471 fn into_iter(self) -> Self::IntoIter {
472 self.iter()
473 }
474}
475
476pub(crate) type KeyValuePairs = IndexMap<InternalString, TableKeyValue>;
477
478fn decorate_table(table: &mut Table) {
479 for (key_decor: &mut Decor, value: &mut Value) in tableimpl Iterator
480 .items
481 .iter_mut()
482 .filter(|(_, kv: &&mut TableKeyValue)| kv.value.is_value())
483 .map(|(_, kv: &mut TableKeyValue)| (&mut kv.key.decor, kv.value.as_value_mut().unwrap()))
484 {
485 key_decor.clear();
486 value.decor_mut().clear();
487 }
488}
489
490// `key1 = value1`
491pub(crate) const DEFAULT_KEY_DECOR: (&str, &str) = ("", " ");
492pub(crate) const DEFAULT_TABLE_DECOR: (&str, &str) = ("\n", "");
493pub(crate) const DEFAULT_KEY_PATH_DECOR: (&str, &str) = ("", "");
494
495#[derive(Debug, Clone)]
496pub(crate) struct TableKeyValue {
497 pub(crate) key: Key,
498 pub(crate) value: Item,
499}
500
501impl TableKeyValue {
502 pub(crate) fn new(key: Key, value: Item) -> Self {
503 TableKeyValue { key, value }
504 }
505}
506
507/// An owned iterator type over `Table`'s key/value pairs.
508pub type IntoIter = Box<dyn Iterator<Item = (InternalString, Item)>>;
509/// An iterator type over `Table`'s key/value pairs.
510pub type Iter<'a> = Box<dyn Iterator<Item = (&'a str, &'a Item)> + 'a>;
511/// A mutable iterator type over `Table`'s key/value pairs.
512pub type IterMut<'a> = Box<dyn Iterator<Item = (KeyMut<'a>, &'a mut Item)> + 'a>;
513
514/// This trait represents either a `Table`, or an `InlineTable`.
515pub trait TableLike: crate::private::Sealed {
516 /// Returns an iterator over key/value pairs.
517 fn iter(&self) -> Iter<'_>;
518 /// Returns an mutable iterator over all key/value pairs, including empty.
519 fn iter_mut(&mut self) -> IterMut<'_>;
520 /// Returns the number of nonempty items.
521 fn len(&self) -> usize {
522 self.iter().filter(|&(_, v)| !v.is_none()).count()
523 }
524 /// Returns true if the table is empty.
525 fn is_empty(&self) -> bool {
526 self.len() == 0
527 }
528 /// Clears the table, removing all key-value pairs. Keeps the allocated memory for reuse.
529 fn clear(&mut self);
530 /// Gets the given key's corresponding entry in the Table for in-place manipulation.
531 fn entry<'a>(&'a mut self, key: &str) -> Entry<'a>;
532 /// Gets the given key's corresponding entry in the Table for in-place manipulation.
533 fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a>;
534 /// Returns an optional reference to an item given the key.
535 fn get<'s>(&'s self, key: &str) -> Option<&'s Item>;
536 /// Returns an optional mutable reference to an item given the key.
537 fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item>;
538 /// Return references to the key-value pair stored for key, if it is present, else None.
539 fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)>;
540 /// Return mutable references to the key-value pair stored for key, if it is present, else None.
541 fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)>;
542 /// Returns true if the table contains an item with the given key.
543 fn contains_key(&self, key: &str) -> bool;
544 /// Inserts a key-value pair into the map.
545 fn insert(&mut self, key: &str, value: Item) -> Option<Item>;
546 /// Removes an item given the key.
547 fn remove(&mut self, key: &str) -> Option<Item>;
548
549 /// Get key/values for values that are visually children of this table
550 ///
551 /// For example, this will return dotted keys
552 fn get_values(&self) -> Vec<(Vec<&Key>, &Value)>;
553
554 /// Auto formats the table.
555 fn fmt(&mut self);
556 /// Sorts Key/Value Pairs of the table.
557 ///
558 /// Doesn't affect subtables or subarrays.
559 fn sort_values(&mut self);
560 /// Change this table's dotted status
561 fn set_dotted(&mut self, yes: bool);
562 /// Check if this is a wrapper for dotted keys, rather than a standard table
563 fn is_dotted(&self) -> bool;
564
565 /// Returns the decor associated with a given key of the table.
566 fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor>;
567 /// Returns the decor associated with a given key of the table.
568 fn key_decor(&self, key: &str) -> Option<&Decor>;
569}
570
571impl TableLike for Table {
572 fn iter(&self) -> Iter<'_> {
573 self.iter()
574 }
575 fn iter_mut(&mut self) -> IterMut<'_> {
576 self.iter_mut()
577 }
578 fn clear(&mut self) {
579 self.clear();
580 }
581 fn entry<'a>(&'a mut self, key: &str) -> Entry<'a> {
582 self.entry(key)
583 }
584 fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a> {
585 self.entry_format(key)
586 }
587 fn get<'s>(&'s self, key: &str) -> Option<&'s Item> {
588 self.get(key)
589 }
590 fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item> {
591 self.get_mut(key)
592 }
593 fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)> {
594 self.get_key_value(key)
595 }
596 fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)> {
597 self.get_key_value_mut(key)
598 }
599 fn contains_key(&self, key: &str) -> bool {
600 self.contains_key(key)
601 }
602 fn insert(&mut self, key: &str, value: Item) -> Option<Item> {
603 self.insert(key, value)
604 }
605 fn remove(&mut self, key: &str) -> Option<Item> {
606 self.remove(key)
607 }
608
609 fn get_values(&self) -> Vec<(Vec<&Key>, &Value)> {
610 self.get_values()
611 }
612 fn fmt(&mut self) {
613 self.fmt()
614 }
615 fn sort_values(&mut self) {
616 self.sort_values()
617 }
618 fn is_dotted(&self) -> bool {
619 self.is_dotted()
620 }
621 fn set_dotted(&mut self, yes: bool) {
622 self.set_dotted(yes)
623 }
624
625 fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor> {
626 self.key_decor_mut(key)
627 }
628 fn key_decor(&self, key: &str) -> Option<&Decor> {
629 self.key_decor(key)
630 }
631}
632
633/// A view into a single location in a map, which may be vacant or occupied.
634pub enum Entry<'a> {
635 /// An occupied Entry.
636 Occupied(OccupiedEntry<'a>),
637 /// A vacant Entry.
638 Vacant(VacantEntry<'a>),
639}
640
641impl<'a> Entry<'a> {
642 /// Returns the entry key
643 ///
644 /// # Examples
645 ///
646 /// ```
647 /// use toml_edit::Table;
648 ///
649 /// let mut map = Table::new();
650 ///
651 /// assert_eq!("hello", map.entry("hello").key());
652 /// ```
653 pub fn key(&self) -> &str {
654 match self {
655 Entry::Occupied(e) => e.key(),
656 Entry::Vacant(e) => e.key(),
657 }
658 }
659
660 /// Ensures a value is in the entry by inserting the default if empty, and returns
661 /// a mutable reference to the value in the entry.
662 pub fn or_insert(self, default: Item) -> &'a mut Item {
663 match self {
664 Entry::Occupied(entry) => entry.into_mut(),
665 Entry::Vacant(entry) => entry.insert(default),
666 }
667 }
668
669 /// Ensures a value is in the entry by inserting the result of the default function if empty,
670 /// and returns a mutable reference to the value in the entry.
671 pub fn or_insert_with<F: FnOnce() -> Item>(self, default: F) -> &'a mut Item {
672 match self {
673 Entry::Occupied(entry) => entry.into_mut(),
674 Entry::Vacant(entry) => entry.insert(default()),
675 }
676 }
677}
678
679/// A view into a single occupied location in a `IndexMap`.
680pub struct OccupiedEntry<'a> {
681 pub(crate) entry: indexmap::map::OccupiedEntry<'a, InternalString, TableKeyValue>,
682}
683
684impl<'a> OccupiedEntry<'a> {
685 /// Gets a reference to the entry key
686 ///
687 /// # Examples
688 ///
689 /// ```
690 /// use toml_edit::Table;
691 ///
692 /// let mut map = Table::new();
693 ///
694 /// assert_eq!("foo", map.entry("foo").key());
695 /// ```
696 pub fn key(&self) -> &str {
697 self.entry.key().as_str()
698 }
699
700 /// Gets a mutable reference to the entry key
701 pub fn key_mut(&mut self) -> KeyMut<'_> {
702 self.entry.get_mut().key.as_mut()
703 }
704
705 /// Gets a reference to the value in the entry.
706 pub fn get(&self) -> &Item {
707 &self.entry.get().value
708 }
709
710 /// Gets a mutable reference to the value in the entry.
711 pub fn get_mut(&mut self) -> &mut Item {
712 &mut self.entry.get_mut().value
713 }
714
715 /// Converts the OccupiedEntry into a mutable reference to the value in the entry
716 /// with a lifetime bound to the map itself
717 pub fn into_mut(self) -> &'a mut Item {
718 &mut self.entry.into_mut().value
719 }
720
721 /// Sets the value of the entry, and returns the entry's old value
722 pub fn insert(&mut self, mut value: Item) -> Item {
723 std::mem::swap(&mut value, &mut self.entry.get_mut().value);
724 value
725 }
726
727 /// Takes the value out of the entry, and returns it
728 pub fn remove(self) -> Item {
729 self.entry.shift_remove().value
730 }
731}
732
733/// A view into a single empty location in a `IndexMap`.
734pub struct VacantEntry<'a> {
735 pub(crate) entry: indexmap::map::VacantEntry<'a, InternalString, TableKeyValue>,
736 pub(crate) key: Option<Key>,
737}
738
739impl<'a> VacantEntry<'a> {
740 /// Gets a reference to the entry key
741 ///
742 /// # Examples
743 ///
744 /// ```
745 /// use toml_edit::Table;
746 ///
747 /// let mut map = Table::new();
748 ///
749 /// assert_eq!("foo", map.entry("foo").key());
750 /// ```
751 pub fn key(&self) -> &str {
752 self.entry.key().as_str()
753 }
754
755 /// Sets the value of the entry with the VacantEntry's key,
756 /// and returns a mutable reference to it
757 pub fn insert(self, value: Item) -> &'a mut Item {
758 let entry: VacantEntry<'_, InternalString, …> = self.entry;
759 let key: Key = self.key.unwrap_or_else(|| Key::new(key:entry.key().as_str()));
760 &mut entry.insert(TableKeyValue::new(key, value)).value
761 }
762}
763