1use std::str::FromStr;
2
3use crate::table::Iter;
4use crate::{Item, RawString, Table};
5
6/// Type representing a TOML document
7#[derive(Debug, Clone)]
8pub struct Document {
9 pub(crate) root: Item,
10 // Trailing comments and whitespaces
11 pub(crate) trailing: RawString,
12 pub(crate) original: Option<String>,
13 pub(crate) span: Option<std::ops::Range<usize>>,
14}
15
16impl Document {
17 /// Creates an empty document
18 pub fn new() -> Self {
19 Default::default()
20 }
21
22 /// Returns a reference to the root item.
23 pub fn as_item(&self) -> &Item {
24 &self.root
25 }
26
27 /// Returns a mutable reference to the root item.
28 pub fn as_item_mut(&mut self) -> &mut Item {
29 &mut self.root
30 }
31
32 /// Returns a reference to the root table.
33 pub fn as_table(&self) -> &Table {
34 self.root.as_table().expect("root should always be a table")
35 }
36
37 /// Returns a mutable reference to the root table.
38 pub fn as_table_mut(&mut self) -> &mut Table {
39 self.root
40 .as_table_mut()
41 .expect("root should always be a table")
42 }
43
44 /// Returns an iterator over the root table.
45 pub fn iter(&self) -> Iter<'_> {
46 self.as_table().iter()
47 }
48
49 /// Set whitespace after last element
50 pub fn set_trailing(&mut self, trailing: impl Into<RawString>) {
51 self.trailing = trailing.into();
52 }
53
54 /// Whitespace after last element
55 pub fn trailing(&self) -> &RawString {
56 &self.trailing
57 }
58
59 /// # Panics
60 ///
61 /// If run on on a `Document` not generated by the parser
62 pub(crate) fn despan(&mut self) {
63 self.span = None;
64 self.root.despan(self.original.as_deref().unwrap());
65 self.trailing.despan(self.original.as_deref().unwrap());
66 }
67}
68
69impl Default for Document {
70 fn default() -> Self {
71 Self {
72 root: Item::Table(Table::with_pos(doc_position:Some(0))),
73 trailing: Default::default(),
74 original: Default::default(),
75 span: Default::default(),
76 }
77 }
78}
79
80#[cfg(feature = "parse")]
81impl FromStr for Document {
82 type Err = crate::TomlError;
83
84 /// Parses a document from a &str
85 fn from_str(s: &str) -> Result<Self, Self::Err> {
86 let mut d: Document = crate::parser::parse_document(raw:s)?;
87 d.despan();
88 Ok(d)
89 }
90}
91
92impl std::ops::Deref for Document {
93 type Target = Table;
94
95 fn deref(&self) -> &Self::Target {
96 self.as_table()
97 }
98}
99
100impl std::ops::DerefMut for Document {
101 fn deref_mut(&mut self) -> &mut Self::Target {
102 self.as_table_mut()
103 }
104}
105
106impl From<Table> for Document {
107 fn from(root: Table) -> Self {
108 Self {
109 root: Item::Table(root),
110 ..Default::default()
111 }
112 }
113}
114