toml/ser/document/
buffer.rs1use alloc::collections::BTreeMap;
2
3use toml_writer::TomlWrite as _;
4
5use crate::alloc_prelude::*;
6
7#[derive(Debug)]
9pub struct Buffer {
10 output: String,
11 allocation_pool: String,
12 insertions: BTreeMap<(InsertionOffset, Pos), String>,
14 next_table_pos: Pos,
15}
16
17impl Default for Buffer {
18 fn default() -> Self {
19 Self {
20 output: String::with_capacity(128),
21 allocation_pool: String::new(),
22 insertions: BTreeMap::new(),
23 next_table_pos: Pos::default(),
24 }
25 }
26}
27
28impl Buffer {
29 pub fn new() -> Self {
31 Default::default()
32 }
33
34 pub fn clear(&mut self) {
36 self.output.clear();
37 self.insertions.clear();
38 self.next_table_pos = Pos::default();
39 }
40
41 pub(crate) fn root_table(&mut self) -> Table {
42 self.new_table(String::new())
43 }
44
45 pub(crate) fn child_table(
46 &mut self,
47 parent: &mut Table,
48 write_key: impl FnOnce(&mut String) -> Result<(), super::Error>,
49 ) -> Result<Table, super::Error> {
50 let encoded_key = self.child_encoded_key(parent, write_key)?;
51 Ok(self.new_table(encoded_key))
52 }
53
54 pub(crate) fn child_encoded_key(
55 &mut self,
56 parent: &mut Table,
57 write_key: impl FnOnce(&mut String) -> Result<(), super::Error>,
58 ) -> Result<String, super::Error> {
59 let mut encoded_key = core::mem::take(&mut self.allocation_pool);
60 if !parent.encoded_key.is_empty() {
61 encoded_key.push_str(&parent.encoded_key);
62 encoded_key.key_sep()?;
63 }
64 write_key(&mut encoded_key)?;
65 self.begin_children(parent);
66 Ok(encoded_key)
67 }
68
69 pub(crate) fn element_table(&mut self, encoded_key: &str) -> Table {
70 let mut element_key = core::mem::take(&mut self.allocation_pool);
71 element_key.push_str(encoded_key);
72 let mut table = self.new_table(element_key);
73 table.array = true;
74 table
75 }
76
77 fn new_table(&mut self, encoded_key: String) -> Table {
78 let pos = self.next_table_pos();
79 Table {
80 encoded_key,
81 pos,
82 insert_at: None,
83 started: false,
84 array: false,
85 }
86 }
87
88 fn next_table_pos(&mut self) -> Pos {
89 let pos = self.next_table_pos;
90 self.next_table_pos.0 += 1;
91 pos
92 }
93
94 fn begin_children(&mut self, table: &mut Table) {
95 if table.insert_at.is_none() {
96 if table.array && !table.started {
98 self.ensure_body(table);
99 }
100 table.insert_at = Some(self.insertion_offset());
101 }
102 }
103
104 pub(crate) fn ensure_body(&mut self, table: &mut Table) -> &mut String {
105 let (dst, offset) = if let Some(offset) = table.insert_at {
106 (
107 self.insertions.entry((offset, table.pos)).or_default(),
108 offset,
109 )
110 } else {
111 let offset = self.insertion_offset();
112 (&mut self.output, offset)
113 };
114 if !table.started {
115 if offset != InsertionOffset::start() {
116 dst.push('\n');
117 }
118 table
119 .write_header(dst)
120 .expect("writing to a String cannot fail");
121 table.started = true;
122 }
123 dst
124 }
125
126 fn insertion_offset(&self) -> InsertionOffset {
127 InsertionOffset(self.output.len())
128 }
129
130 pub(crate) fn push(&mut self, mut table: Table) {
131 if required_table(&table) {
132 self.ensure_body(&mut table);
133 }
134 self.recycle_allocation(table.encoded_key);
135 }
136
137 pub(crate) fn recycle_allocation(&mut self, mut encoded_key: String) {
138 if self.allocation_pool.capacity() < encoded_key.capacity() {
139 encoded_key.clear();
140 self.allocation_pool = encoded_key;
141 }
142 }
143
144 pub(crate) fn into_string(mut self) -> String {
145 for ((offset, _), mut text) in self.insertions.into_iter().rev() {
146 if offset == InsertionOffset::start() && !self.output.is_empty() {
147 text.push('\n');
148 }
149 self.output.insert_str(offset.0, &text);
150 }
151 self.output
152 }
153}
154
155impl core::fmt::Display for Buffer {
156 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
157 let mut start = InsertionOffset::start();
158 let mut leading_section = false;
159 for (&(offset, _), text) in &self.insertions {
160 if leading_section {
161 f.write_str("\n")?;
162 }
163 f.write_str(&self.output[start.0..offset.0])?;
164 f.write_str(text)?;
165 start = offset;
166 leading_section = offset == InsertionOffset::start();
167 }
168 if leading_section && !self.output.is_empty() {
169 f.write_str("\n")?;
170 }
171 f.write_str(&self.output[start.0..])
172 }
173}
174
175#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
176struct Pos(usize);
177
178#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
179struct InsertionOffset(usize);
180
181impl InsertionOffset {
182 const fn start() -> Self {
183 Self(0)
184 }
185}
186
187fn required_table(table: &Table) -> bool {
188 !table.started && table.insert_at.is_none() && !table.encoded_key.is_empty()
190}
191
192#[derive(Debug)]
193pub(crate) struct Table {
194 encoded_key: String,
195 pos: Pos,
196 insert_at: Option<InsertionOffset>,
198 started: bool,
199 array: bool,
200}
201
202impl Table {
203 fn write_header(&self, dst: &mut String) -> core::fmt::Result {
204 if !self.encoded_key.is_empty() {
205 if self.array {
206 dst.open_array_of_tables_header()?;
207 } else {
208 dst.open_table_header()?;
209 }
210 dst.push_str(&self.encoded_key);
211 if self.array {
212 dst.close_array_of_tables_header()?;
213 } else {
214 dst.close_table_header()?;
215 }
216 dst.newline()?;
217 }
218 Ok(())
219 }
220}