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#[derive(Clone, Debug, Default)]
12pub struct Table {
13 pub(crate) decor: Decor,
15 pub(crate) implicit: bool,
17 pub(crate) dotted: bool,
19 doc_position: Option<usize>,
23 pub(crate) span: Option<std::ops::Range<usize>>,
24 pub(crate) items: KeyValuePairs,
25}
26
27impl Table {
31 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 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
61impl Table {
63 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, 'c>(
74 &'s self,
75 parent: &[&'s Key],
76 values: &'c 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 pub fn fmt(&mut self) {
103 decorate_table(self);
104 }
105
106 pub fn sort_values(&mut self) {
110 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 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 pub fn set_implicit(&mut self, implicit: bool) {
175 self.implicit = implicit;
176 }
177
178 pub fn is_implicit(&self) -> bool {
180 self.implicit
181 }
182
183 pub fn set_dotted(&mut self, yes: bool) {
185 self.dotted = yes;
186 }
187
188 pub fn is_dotted(&self) -> bool {
190 self.dotted
191 }
192
193 pub fn set_position(&mut self, doc_position: usize) {
195 self.doc_position = Some(doc_position);
196 }
197
198 pub fn position(&self) -> Option<usize> {
204 self.doc_position
205 }
206
207 pub fn decor_mut(&mut self) -> &mut Decor {
209 &mut self.decor
210 }
211
212 pub fn decor(&self) -> &Decor {
214 &self.decor
215 }
216
217 pub fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor> {
219 self.items.get_mut(key).map(|kv| &mut kv.key.decor)
220 }
221
222 pub fn key_decor(&self, key: &str) -> Option<&Decor> {
224 self.items.get(key).map(|kv| &kv.key.decor)
225 }
226
227 pub(crate) fn span(&self) -> Option<std::ops::Range<usize>> {
229 self.span.clone()
230 }
231
232 pub(crate) fn despan(&mut self, input: &str) {
233 self.span = None;
234 self.decor.despan(input);
235 for kv in self.items.values_mut() {
236 kv.key.despan(input);
237 kv.value.despan(input);
238 }
239 }
240}
241
242impl Table {
243 pub fn iter(&self) -> Iter<'_> {
245 Box::new(
246 self.items
247 .iter()
248 .filter(|(_, kv)| !kv.value.is_none())
249 .map(|(key, kv)| (&key[..], &kv.value)),
250 )
251 }
252
253 pub fn iter_mut(&mut self) -> IterMut<'_> {
255 Box::new(
256 self.items
257 .iter_mut()
258 .filter(|(_, kv)| !kv.value.is_none())
259 .map(|(_, kv)| (kv.key.as_mut(), &mut kv.value)),
260 )
261 }
262
263 pub fn len(&self) -> usize {
265 self.items.iter().filter(|i| !(i.1).value.is_none()).count()
266 }
267
268 pub fn is_empty(&self) -> bool {
270 self.len() == 0
271 }
272
273 pub fn clear(&mut self) {
275 self.items.clear()
276 }
277
278 pub fn entry<'a>(&'a mut self, key: &str) -> Entry<'a> {
280 match self.items.entry(key.into()) {
282 indexmap::map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { entry }),
283 indexmap::map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry { entry, key: None }),
284 }
285 }
286
287 pub fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a> {
289 match self.items.entry(key.get().into()) {
291 indexmap::map::Entry::Occupied(entry) => Entry::Occupied(OccupiedEntry { entry }),
292 indexmap::map::Entry::Vacant(entry) => Entry::Vacant(VacantEntry {
293 entry,
294 key: Some(key.to_owned()),
295 }),
296 }
297 }
298
299 pub fn get<'a>(&'a self, key: &str) -> Option<&'a Item> {
301 self.items.get(key).and_then(|kv| {
302 if !kv.value.is_none() {
303 Some(&kv.value)
304 } else {
305 None
306 }
307 })
308 }
309
310 pub fn get_mut<'a>(&'a mut self, key: &str) -> Option<&'a mut Item> {
312 self.items.get_mut(key).and_then(|kv| {
313 if !kv.value.is_none() {
314 Some(&mut kv.value)
315 } else {
316 None
317 }
318 })
319 }
320
321 pub fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)> {
323 self.items.get(key).and_then(|kv| {
324 if !kv.value.is_none() {
325 Some((&kv.key, &kv.value))
326 } else {
327 None
328 }
329 })
330 }
331
332 pub fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)> {
334 self.items.get_mut(key).and_then(|kv| {
335 if !kv.value.is_none() {
336 Some((kv.key.as_mut(), &mut kv.value))
337 } else {
338 None
339 }
340 })
341 }
342
343 pub fn contains_key(&self, key: &str) -> bool {
345 if let Some(kv) = self.items.get(key) {
346 !kv.value.is_none()
347 } else {
348 false
349 }
350 }
351
352 pub fn contains_table(&self, key: &str) -> bool {
354 if let Some(kv) = self.items.get(key) {
355 kv.value.is_table()
356 } else {
357 false
358 }
359 }
360
361 pub fn contains_value(&self, key: &str) -> bool {
363 if let Some(kv) = self.items.get(key) {
364 kv.value.is_value()
365 } else {
366 false
367 }
368 }
369
370 pub fn contains_array_of_tables(&self, key: &str) -> bool {
372 if let Some(kv) = self.items.get(key) {
373 kv.value.is_array_of_tables()
374 } else {
375 false
376 }
377 }
378
379 pub fn insert(&mut self, key: &str, item: Item) -> Option<Item> {
381 let kv = TableKeyValue::new(Key::new(key), item);
382 self.items.insert(key.into(), kv).map(|kv| kv.value)
383 }
384
385 pub fn insert_formatted(&mut self, key: &Key, item: Item) -> Option<Item> {
387 let kv = TableKeyValue::new(key.to_owned(), item);
388 self.items.insert(key.get().into(), kv).map(|kv| kv.value)
389 }
390
391 pub fn remove(&mut self, key: &str) -> Option<Item> {
393 self.items.shift_remove(key).map(|kv| kv.value)
394 }
395
396 pub fn remove_entry(&mut self, key: &str) -> Option<(Key, Item)> {
398 self.items.shift_remove(key).map(|kv| (kv.key, kv.value))
399 }
400
401 pub fn retain<F>(&mut self, mut keep: F)
408 where
409 F: FnMut(&str, &mut Item) -> bool,
410 {
411 self.items
412 .retain(|key, key_value| keep(key, &mut key_value.value));
413 }
414}
415
416impl std::fmt::Display for Table {
417 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
418 use crate::encode::Encode;
419 let children = self.get_values();
420 for (key_path, value) in children {
422 key_path.as_slice().encode(f, None, DEFAULT_KEY_DECOR)?;
423 write!(f, "=")?;
424 value.encode(f, None, DEFAULT_VALUE_DECOR)?;
425 writeln!(f)?;
426 }
427 Ok(())
428 }
429}
430
431impl<K: Into<Key>, V: Into<Value>> Extend<(K, V)> for Table {
432 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
433 for (key, value) in iter {
434 let key = key.into();
435 let value = Item::Value(value.into());
436 let value = TableKeyValue::new(key, value);
437 self.items.insert(value.key.get().into(), value);
438 }
439 }
440}
441
442impl<K: Into<Key>, V: Into<Value>> FromIterator<(K, V)> for Table {
443 fn from_iter<I>(iter: I) -> Self
444 where
445 I: IntoIterator<Item = (K, V)>,
446 {
447 let mut table = Table::new();
448 table.extend(iter);
449 table
450 }
451}
452
453impl IntoIterator for Table {
454 type Item = (InternalString, Item);
455 type IntoIter = IntoIter;
456
457 fn into_iter(self) -> Self::IntoIter {
458 Box::new(self.items.into_iter().map(|(k, kv)| (k, kv.value)))
459 }
460}
461
462impl<'s> IntoIterator for &'s Table {
463 type Item = (&'s str, &'s Item);
464 type IntoIter = Iter<'s>;
465
466 fn into_iter(self) -> Self::IntoIter {
467 self.iter()
468 }
469}
470
471pub(crate) type KeyValuePairs = IndexMap<InternalString, TableKeyValue>;
472
473fn decorate_table(table: &mut Table) {
474 for (key_decor, value) in table
475 .items
476 .iter_mut()
477 .filter(|&(_, ref kv)| kv.value.is_value())
478 .map(|(_, kv)| (&mut kv.key.decor, kv.value.as_value_mut().unwrap()))
479 {
480 key_decor.clear();
481 value.decor_mut().clear();
482 }
483}
484
485pub(crate) const DEFAULT_KEY_DECOR: (&str, &str) = ("", " ");
487pub(crate) const DEFAULT_TABLE_DECOR: (&str, &str) = ("\n", "");
488pub(crate) const DEFAULT_KEY_PATH_DECOR: (&str, &str) = ("", "");
489
490#[derive(Debug, Clone)]
491pub(crate) struct TableKeyValue {
492 pub(crate) key: Key,
493 pub(crate) value: Item,
494}
495
496impl TableKeyValue {
497 pub(crate) fn new(key: Key, value: Item) -> Self {
498 TableKeyValue { key, value }
499 }
500}
501
502pub type IntoIter = Box<dyn Iterator<Item = (InternalString, Item)>>;
504pub type Iter<'a> = Box<dyn Iterator<Item = (&'a str, &'a Item)> + 'a>;
506pub type IterMut<'a> = Box<dyn Iterator<Item = (KeyMut<'a>, &'a mut Item)> + 'a>;
508
509pub trait TableLike: crate::private::Sealed {
511 fn iter(&self) -> Iter<'_>;
513 fn iter_mut(&mut self) -> IterMut<'_>;
515 fn len(&self) -> usize {
517 self.iter().filter(|&(_, v)| !v.is_none()).count()
518 }
519 fn is_empty(&self) -> bool {
521 self.len() == 0
522 }
523 fn clear(&mut self);
525 fn entry<'a>(&'a mut self, key: &str) -> Entry<'a>;
527 fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a>;
529 fn get<'s>(&'s self, key: &str) -> Option<&'s Item>;
531 fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item>;
533 fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)>;
535 fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)>;
537 fn contains_key(&self, key: &str) -> bool;
539 fn insert(&mut self, key: &str, value: Item) -> Option<Item>;
541 fn remove(&mut self, key: &str) -> Option<Item>;
543
544 fn get_values(&self) -> Vec<(Vec<&Key>, &Value)>;
548
549 fn fmt(&mut self);
551 fn sort_values(&mut self);
555 fn set_dotted(&mut self, yes: bool);
557 fn is_dotted(&self) -> bool;
559
560 fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor>;
562 fn key_decor(&self, key: &str) -> Option<&Decor>;
564}
565
566impl TableLike for Table {
567 fn iter(&self) -> Iter<'_> {
568 self.iter()
569 }
570 fn iter_mut(&mut self) -> IterMut<'_> {
571 self.iter_mut()
572 }
573 fn clear(&mut self) {
574 self.clear();
575 }
576 fn entry<'a>(&'a mut self, key: &str) -> Entry<'a> {
577 self.entry(key)
578 }
579 fn entry_format<'a>(&'a mut self, key: &Key) -> Entry<'a> {
580 self.entry_format(key)
581 }
582 fn get<'s>(&'s self, key: &str) -> Option<&'s Item> {
583 self.get(key)
584 }
585 fn get_mut<'s>(&'s mut self, key: &str) -> Option<&'s mut Item> {
586 self.get_mut(key)
587 }
588 fn get_key_value<'a>(&'a self, key: &str) -> Option<(&'a Key, &'a Item)> {
589 self.get_key_value(key)
590 }
591 fn get_key_value_mut<'a>(&'a mut self, key: &str) -> Option<(KeyMut<'a>, &'a mut Item)> {
592 self.get_key_value_mut(key)
593 }
594 fn contains_key(&self, key: &str) -> bool {
595 self.contains_key(key)
596 }
597 fn insert(&mut self, key: &str, value: Item) -> Option<Item> {
598 self.insert(key, value)
599 }
600 fn remove(&mut self, key: &str) -> Option<Item> {
601 self.remove(key)
602 }
603
604 fn get_values(&self) -> Vec<(Vec<&Key>, &Value)> {
605 self.get_values()
606 }
607 fn fmt(&mut self) {
608 self.fmt()
609 }
610 fn sort_values(&mut self) {
611 self.sort_values()
612 }
613 fn is_dotted(&self) -> bool {
614 self.is_dotted()
615 }
616 fn set_dotted(&mut self, yes: bool) {
617 self.set_dotted(yes)
618 }
619
620 fn key_decor_mut(&mut self, key: &str) -> Option<&mut Decor> {
621 self.key_decor_mut(key)
622 }
623 fn key_decor(&self, key: &str) -> Option<&Decor> {
624 self.key_decor(key)
625 }
626}
627
628pub enum Entry<'a> {
630 Occupied(OccupiedEntry<'a>),
632 Vacant(VacantEntry<'a>),
634}
635
636impl<'a> Entry<'a> {
637 pub fn key(&self) -> &str {
649 match self {
650 Entry::Occupied(e) => e.key(),
651 Entry::Vacant(e) => e.key(),
652 }
653 }
654
655 pub fn or_insert(self, default: Item) -> &'a mut Item {
658 match self {
659 Entry::Occupied(entry) => entry.into_mut(),
660 Entry::Vacant(entry) => entry.insert(default),
661 }
662 }
663
664 pub fn or_insert_with<F: FnOnce() -> Item>(self, default: F) -> &'a mut Item {
667 match self {
668 Entry::Occupied(entry) => entry.into_mut(),
669 Entry::Vacant(entry) => entry.insert(default()),
670 }
671 }
672}
673
674pub struct OccupiedEntry<'a> {
676 pub(crate) entry: indexmap::map::OccupiedEntry<'a, InternalString, TableKeyValue>,
677}
678
679impl<'a> OccupiedEntry<'a> {
680 pub fn key(&self) -> &str {
692 self.entry.key().as_str()
693 }
694
695 pub fn key_mut(&mut self) -> KeyMut<'_> {
697 self.entry.get_mut().key.as_mut()
698 }
699
700 pub fn get(&self) -> &Item {
702 &self.entry.get().value
703 }
704
705 pub fn get_mut(&mut self) -> &mut Item {
707 &mut self.entry.get_mut().value
708 }
709
710 pub fn into_mut(self) -> &'a mut Item {
713 &mut self.entry.into_mut().value
714 }
715
716 pub fn insert(&mut self, mut value: Item) -> Item {
718 std::mem::swap(&mut value, &mut self.entry.get_mut().value);
719 value
720 }
721
722 pub fn remove(self) -> Item {
724 self.entry.shift_remove().value
725 }
726}
727
728pub struct VacantEntry<'a> {
730 pub(crate) entry: indexmap::map::VacantEntry<'a, InternalString, TableKeyValue>,
731 pub(crate) key: Option<Key>,
732}
733
734impl<'a> VacantEntry<'a> {
735 pub fn key(&self) -> &str {
747 self.entry.key().as_str()
748 }
749
750 pub fn insert(self, value: Item) -> &'a mut Item {
753 let entry = self.entry;
754 let key = self.key.unwrap_or_else(|| Key::new(entry.key().as_str()));
755 &mut entry.insert(TableKeyValue::new(key, value)).value
756 }
757}