Skip to main content

quick_xml/
writer.rs

1//! Contains high-level interface for an events-based XML emitter.
2
3use std::borrow::Cow;
4use std::io::{self, Write};
5
6use crate::encoding::UTF8_BOM;
7use crate::events::attributes::Attribute;
8use crate::events::{BytesCData, BytesPI, BytesStart, BytesText, Event};
9
10#[cfg(feature = "async-tokio")]
11mod async_tokio;
12
13/// XML writer. Writes XML [`Event`]s to a [`std::io::Write`] or [`tokio::io::AsyncWrite`] implementor.
14#[cfg(feature = "serialize")]
15use {crate::se::SeError, serde::Serialize};
16
17/// A struct that holds a writer configuration.
18///
19/// Current writer configuration can be retrieved by calling [`Writer::config()`]
20/// and changed by changing properties of the object returned by a call to
21/// [`Writer::config_mut()`].
22///
23/// [`Writer::config()`]: crate::writer::Writer::config
24/// [`Writer::config_mut()`]: crate::writer::Writer::config_mut
25#[derive(Debug, Default, Clone, PartialEq, Eq)]
26#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
27#[cfg_attr(feature = "serde-types", derive(serde::Deserialize, serde::Serialize))]
28#[non_exhaustive]
29pub struct Config {
30    /// Whether to add a space before the closing slash in empty elements.
31    /// According to the [W3C guidelines], this is recommended as for maximum compatibility.
32    ///
33    /// When set to `true`, empty elements will be terminated with "` />`".
34    /// When set to `false`, empty elements will be terminated with "`/>`".
35    ///
36    /// Default: `false`
37    ///
38    /// # Example
39    ///
40    /// ```
41    /// # use pretty_assertions::assert_eq;
42    /// use quick_xml::reader::Reader;
43    /// use quick_xml::writer::Writer;
44    /// use std::io::Cursor;
45    ///
46    /// let mut writer = Writer::new(Cursor::new(Vec::new()));
47    /// writer.config_mut().add_space_before_slash_in_empty_elements = true;
48    ///
49    /// writer.create_element("tag")
50    ///     .with_attribute(("attr1", "value1"))
51    ///     .write_empty()
52    ///     .unwrap();
53    ///
54    /// let result = writer.into_inner().into_inner();
55    /// let expected = r#"<tag attr1="value1" />"#;
56    /// assert_eq!(result, expected.as_bytes());
57    /// ```
58    ///
59    /// [W3C guidelines]: https://www.w3.org/TR/xhtml1/#guidelines
60    pub add_space_before_slash_in_empty_elements: bool,
61}
62
63/// XML writer. Writes XML [`Event`]s to a [`std::io::Write`] implementor.
64///
65/// # Examples
66///
67/// ```
68/// # use pretty_assertions::assert_eq;
69/// use quick_xml::events::{Event, BytesEnd, BytesStart};
70/// use quick_xml::reader::Reader;
71/// use quick_xml::writer::Writer;
72/// use std::io::Cursor;
73///
74/// let xml = r#"<this_tag k1="v1" k2="v2"><child>text</child></this_tag>"#;
75/// let mut reader = Reader::from_str(xml);
76/// let mut writer = Writer::new(Cursor::new(Vec::new()));
77/// loop {
78///     match reader.read_event() {
79///         Ok(Event::Start(e)) if e.name().as_ref() == "this_tag" => {
80///
81///             // creates a new element ... alternatively we could reuse `e` by calling
82///             // `e.into_owned()`
83///             let mut elem = BytesStart::new("my_elem");
84///
85///             // collect existing attributes
86///             elem.extend_attributes(e.attributes().map(|attr| attr.unwrap()));
87///
88///             // copy existing attributes, adds a new my-key="some value" attribute
89///             elem.push_attribute(("my-key", "some value"));
90///
91///             // writes the event to the writer
92///             assert!(writer.write_event(Event::Start(elem)).is_ok());
93///         },
94///         Ok(Event::End(e)) if e.name().as_ref() == "this_tag" => {
95///             assert!(writer.write_event(Event::End(BytesEnd::new("my_elem"))).is_ok());
96///         },
97///         Ok(Event::Eof) => break,
98///         // we can either move or borrow the event to write, depending on your use-case
99///         Ok(e) => assert!(writer.write_event(e.borrow()).is_ok()),
100///         Err(e) => panic!("Error at position {}: {:?}", reader.error_position(), e),
101///     }
102/// }
103///
104/// let result = writer.into_inner().into_inner();
105/// let expected = r#"<my_elem k1="v1" k2="v2" my-key="some value"><child>text</child></my_elem>"#;
106/// assert_eq!(result, expected.as_bytes());
107/// ```
108#[derive(Clone)]
109pub struct Writer<W> {
110    /// underlying writer
111    writer: W,
112
113    /// writer configuration
114    config: Config,
115
116    /// indentation configuration and state; stored separately from
117    /// other configuration since it also tracks writer state
118    indent: Option<Indentation>,
119}
120
121impl<W> Writer<W> {
122    /// Creates a `Writer` from a generic writer.
123    pub const fn new(inner: W) -> Writer<W> {
124        Writer {
125            writer: inner,
126            config: Config {
127                add_space_before_slash_in_empty_elements: false,
128            },
129            indent: None,
130        }
131    }
132
133    /// Creates a `Writer` with configured indents from a generic writer.
134    pub fn new_with_indent(inner: W, indent_char: u8, indent_size: usize) -> Writer<W> {
135        Writer {
136            writer: inner,
137            config: Config {
138                add_space_before_slash_in_empty_elements: false,
139            },
140            indent: Some(Indentation::new(indent_char, indent_size)),
141        }
142    }
143
144    /// Consumes this `Writer`, returning the underlying writer.
145    pub fn into_inner(self) -> W {
146        self.writer
147    }
148
149    /// Get a mutable reference to the underlying writer.
150    pub fn get_mut(&mut self) -> &mut W {
151        &mut self.writer
152    }
153
154    /// Get a reference to the underlying writer.
155    pub const fn get_ref(&self) -> &W {
156        &self.writer
157    }
158
159    /// Returns reference to the writer configuration
160    pub const fn config(&self) -> &Config {
161        &self.config
162    }
163
164    /// Returns mutable reference to the writer configuration
165    pub fn config_mut(&mut self) -> &mut Config {
166        &mut self.config
167    }
168
169    /// Provides a simple, high-level API for writing XML elements.
170    ///
171    /// Returns an [`ElementWriter`] that simplifies setting attributes and writing
172    /// content inside the element.
173    ///
174    /// # Example
175    ///
176    /// ```
177    /// # use quick_xml::Result;
178    /// # fn main() -> Result<()> {
179    /// use quick_xml::events::{BytesStart, BytesText, Event};
180    /// use quick_xml::writer::Writer;
181    /// use quick_xml::Error;
182    /// use std::io::Cursor;
183    ///
184    /// let mut writer = Writer::new(Cursor::new(Vec::new()));
185    ///
186    /// // writes <tag attr1="value1"/>
187    /// writer.create_element("tag")
188    ///     .with_attribute(("attr1", "value1"))  // chain `with_attribute()` calls to add many attributes
189    ///     .write_empty()?;
190    ///
191    /// // writes <tag attr1="value1" attr2="value2">with some text inside</tag>
192    /// writer.create_element("tag")
193    ///     .with_attributes(vec![("attr1", "value1"), ("attr2", "value2")].into_iter())  // or add attributes from an iterator
194    ///     .write_text_content(BytesText::new("with some text inside"))?;
195    ///
196    /// // writes <tag><fruit quantity="0">apple</fruit><fruit quantity="1">orange</fruit></tag>
197    /// writer.create_element("tag")
198    ///     // We need to provide error type, because it is not named somewhere explicitly
199    ///     .write_inner_content(|writer| {
200    ///         let fruits = ["apple", "orange"];
201    ///         for (quant, item) in fruits.iter().enumerate() {
202    ///             writer
203    ///                 .create_element("fruit")
204    ///                 .with_attribute(("quantity", quant.to_string().as_str()))
205    ///                 .write_text_content(BytesText::new(item))?;
206    ///         }
207    ///         Ok(())
208    ///     })?;
209    /// # Ok(())
210    /// # }
211    /// ```
212    #[must_use]
213    pub fn create_element<'a, N>(&'a mut self, name: N) -> ElementWriter<'a, W>
214    where
215        N: Into<Cow<'a, str>>,
216    {
217        ElementWriter {
218            writer: self,
219            start_tag: BytesStart::new(name),
220            state: AttributeIndent::NoneAttributesWritten,
221            spaces: String::new(),
222        }
223    }
224}
225
226impl<W: Write> Writer<W> {
227    /// Write a [Byte-Order-Mark] character to the document.
228    ///
229    /// # Example
230    ///
231    /// ```rust
232    /// # use quick_xml::Result;
233    /// # fn main() -> Result<()> {
234    /// use quick_xml::events::{BytesStart, BytesText, Event};
235    /// use quick_xml::writer::Writer;
236    /// use quick_xml::Error;
237    /// use std::io::Cursor;
238    ///
239    /// let mut buffer = Vec::new();
240    /// let mut writer = Writer::new_with_indent(&mut buffer, b' ', 4);
241    ///
242    /// writer.write_bom()?;
243    /// writer
244    ///     .create_element("empty")
245    ///     .with_attribute(("attr1", "value1"))
246    ///     .write_empty()
247    ///     .expect("failure");
248    ///
249    /// assert_eq!(
250    ///     std::str::from_utf8(&buffer).unwrap(),
251    ///     "\u{FEFF}<empty attr1=\"value1\"/>"
252    /// );
253    /// # Ok(())
254    /// # }
255    /// ```
256    /// [Byte-Order-Mark]: https://unicode.org/faq/utf_bom.html#BOM
257    pub fn write_bom(&mut self) -> io::Result<()> {
258        self.write(UTF8_BOM)
259    }
260
261    /// Writes the given event to the underlying writer.
262    pub fn write_event<'a, E: Into<Event<'a>>>(&mut self, event: E) -> io::Result<()> {
263        let mut next_should_line_break = true;
264        let result = match event.into() {
265            Event::Start(e) => {
266                let result = self.write_wrapped("<", &e, ">");
267                if let Some(i) = self.indent.as_mut() {
268                    i.grow();
269                }
270                result
271            }
272            Event::End(e) => {
273                if let Some(i) = self.indent.as_mut() {
274                    i.shrink();
275                }
276                self.write_wrapped("</", &e, ">")
277            }
278            Event::Empty(e) => self.write_wrapped(
279                "<",
280                &e,
281                if self.config.add_space_before_slash_in_empty_elements {
282                    " />"
283                } else {
284                    "/>"
285                },
286            ),
287            Event::Text(e) => {
288                next_should_line_break = false;
289                self.write(e.as_bytes())
290            }
291            Event::Comment(e) => self.write_wrapped("<!--", &e, "-->"),
292            Event::CData(e) => {
293                next_should_line_break = false;
294                self.write(b"<![CDATA[")?;
295                self.write(e.as_bytes())?;
296                self.write(b"]]>")
297            }
298            Event::Decl(e) => self.write_wrapped("<?", &e, "?>"),
299            Event::PI(e) => self.write_wrapped("<?", &e, "?>"),
300            Event::DocType(e) => self.write_wrapped("<!DOCTYPE ", &e, ">"),
301            Event::GeneralRef(e) => self.write_wrapped("&", &e, ";"),
302            Event::Eof => Ok(()),
303        };
304        if let Some(i) = self.indent.as_mut() {
305            i.should_line_break = next_should_line_break;
306        }
307        result
308    }
309
310    /// Writes bytes
311    #[inline]
312    pub(crate) fn write(&mut self, value: &[u8]) -> io::Result<()> {
313        self.writer.write_all(value)
314    }
315
316    #[inline]
317    fn write_wrapped(&mut self, before: &str, value: &str, after: &str) -> io::Result<()> {
318        if let Some(ref i) = self.indent {
319            if i.should_line_break {
320                self.writer.write_all(b"\n")?;
321                self.writer.write_all(i.current().as_bytes())?;
322            }
323        }
324        self.write(before.as_bytes())?;
325        self.write(value.as_bytes())?;
326        self.write(after.as_bytes())?;
327        Ok(())
328    }
329
330    /// Manually write a newline and indentation at the proper level.
331    ///
332    /// This can be used when the heuristic to line break and indent after any
333    /// [`Event`] apart from [`Text`] fails such as when a [`Start`] occurs directly
334    /// after [`Text`].
335    ///
336    /// This method will do nothing if `Writer` was not constructed with [`new_with_indent`].
337    ///
338    /// [`Text`]: Event::Text
339    /// [`Start`]: Event::Start
340    /// [`new_with_indent`]: Self::new_with_indent
341    pub fn write_indent(&mut self) -> io::Result<()> {
342        if let Some(ref i) = self.indent {
343            self.writer.write_all(b"\n")?;
344            self.writer.write_all(i.current().as_bytes())?;
345        }
346        Ok(())
347    }
348
349    /// Write an arbitrary serializable type
350    ///
351    /// Note: If you are attempting to write XML in a non-UTF-8 encoding, this may not
352    /// be safe to use. Rust basic types assume UTF-8 encodings.
353    ///
354    /// ```rust
355    /// # use pretty_assertions::assert_eq;
356    /// # use serde::Serialize;
357    /// # use quick_xml::events::{BytesStart, Event};
358    /// # use quick_xml::writer::Writer;
359    /// # use quick_xml::se::SeError;
360    /// # fn main() -> Result<(), SeError> {
361    /// #[derive(Debug, PartialEq, Serialize)]
362    /// struct MyData {
363    ///     question: String,
364    ///     answer: u32,
365    /// }
366    ///
367    /// let data = MyData {
368    ///     question: "The Ultimate Question of Life, the Universe, and Everything".into(),
369    ///     answer: 42,
370    /// };
371    ///
372    /// let mut buffer = Vec::new();
373    /// let mut writer = Writer::new_with_indent(&mut buffer, b' ', 4);
374    ///
375    /// let start = BytesStart::new("root");
376    /// let end = start.to_end();
377    ///
378    /// writer.write_event(Event::Start(start.clone()))?;
379    /// writer.write_serializable("my_data", &data)?;
380    /// writer.write_event(Event::End(end))?;
381    ///
382    /// assert_eq!(
383    ///     std::str::from_utf8(&buffer)?,
384    ///     r#"<root>
385    ///     <my_data>
386    ///         <question>The Ultimate Question of Life, the Universe, and Everything</question>
387    ///         <answer>42</answer>
388    ///     </my_data>
389    /// </root>"#
390    /// );
391    /// # Ok(())
392    /// # }
393    /// ```
394    #[cfg(feature = "serialize")]
395    pub fn write_serializable<T: Serialize>(
396        &mut self,
397        tag_name: &str,
398        content: &T,
399    ) -> Result<(), SeError> {
400        use crate::se::{Indent, Serializer};
401
402        self.write_indent()?;
403        let mut fmt = ToFmtWrite(&mut self.writer);
404        let mut serializer = Serializer::with_root(&mut fmt, Some(tag_name))?;
405
406        if let Some(indent) = &mut self.indent {
407            serializer.set_indent(Indent::Borrow(indent));
408        }
409
410        content.serialize(serializer)?;
411
412        Ok(())
413    }
414}
415
416/// Track indent inside elements state
417///
418/// ```mermaid
419/// stateDiagram-v2
420///     [*] --> NoneAttributesWritten
421///     NoneAttributesWritten --> Spaces : .with_attribute()
422///     NoneAttributesWritten --> WriteConfigured : .new_line()
423///
424///     Spaces --> Spaces : .with_attribute()
425///     Spaces --> WriteSpaces : .new_line()
426///
427///     WriteSpaces --> Spaces : .with_attribute()
428///     WriteSpaces --> WriteSpaces : .new_line()
429///
430///     Configured --> Configured : .with_attribute()
431///     Configured --> WriteConfigured : .new_line()
432///
433///     WriteConfigured --> Configured : .with_attribute()
434///     WriteConfigured --> WriteConfigured : .new_line()
435/// ```
436#[derive(Debug)]
437enum AttributeIndent {
438    /// Initial state. `ElementWriter` was just created and no attributes written yet
439    NoneAttributesWritten,
440    /// Write specified count of spaces to indent before writing attribute in `with_attribute()`
441    WriteSpaces(usize),
442    /// Keep space indent that should be used if `new_line()` would be called
443    Spaces(usize),
444    /// Write specified count of indent characters before writing attribute in `with_attribute()`
445    WriteConfigured(usize),
446    /// Keep indent that should be used if `new_line()` would be called
447    Configured(usize),
448}
449
450/// A struct to write an element. Contains methods to add attributes and inner
451/// elements to the element
452pub struct ElementWriter<'a, W> {
453    writer: &'a mut Writer<W>,
454    start_tag: BytesStart<'a>,
455    state: AttributeIndent,
456    /// Contains spaces used to write space indents of attributes
457    spaces: String,
458}
459
460impl<'a, W> ElementWriter<'a, W> {
461    /// Adds an attribute to this element.
462    pub fn with_attribute<'b, I>(mut self, attr: I) -> Self
463    where
464        I: Into<Attribute<'b>>,
465    {
466        self.write_attr(attr.into());
467        self
468    }
469
470    /// Add additional attributes to this element using an iterator.
471    ///
472    /// The yielded items must be convertible to [`Attribute`] using `Into`.
473    pub fn with_attributes<'b, I>(mut self, attributes: I) -> Self
474    where
475        I: IntoIterator,
476        I::Item: Into<Attribute<'b>>,
477    {
478        let mut iter = attributes.into_iter();
479        if let Some(attr) = iter.next() {
480            self.write_attr(attr.into());
481            self.start_tag.extend_attributes(iter);
482        }
483        self
484    }
485
486    /// Push a new line inside an element between attributes. Note, that this
487    /// method does nothing if [`Writer`] was created without indentation support.
488    ///
489    /// # Examples
490    ///
491    /// The following code
492    ///
493    /// ```
494    /// # use quick_xml::writer::Writer;
495    /// let mut buffer = Vec::new();
496    /// let mut writer = Writer::new_with_indent(&mut buffer, b' ', 2);
497    /// writer
498    ///   .create_element("element")
499    ///     //.new_line() (1)
500    ///     .with_attribute(("first", "1"))
501    ///     .with_attribute(("second", "2"))
502    ///     .new_line()
503    ///     .with_attributes([
504    ///         ("third", "3"),
505    ///         ("fourth", "4"),
506    ///     ])
507    ///     //.new_line() (2)
508    ///     .write_empty();
509    /// ```
510    /// will produce the following XMLs:
511    /// ```xml
512    /// <!-- result of the code above. Spaces always is used -->
513    /// <element first="1" second="2"
514    ///          third="3" fourth="4"/>
515    ///
516    /// <!-- if uncomment only (1) - indent depends on indentation
517    ///      settings - 2 spaces here -->
518    /// <element
519    ///   first="1" second="2"
520    ///   third="3" fourth="4"/>
521    ///
522    /// <!-- if uncomment only (2). Spaces always is used  -->
523    /// <element first="1" second="2"
524    ///          third="3" fourth="4"
525    /// />
526    /// ```
527    pub fn new_line(mut self) -> Self {
528        if let Some(i) = self.writer.indent.as_mut() {
529            match self.state {
530                // .new_line() called just after .create_element().
531                // Use element indent to additionally indent attributes
532                AttributeIndent::NoneAttributesWritten => {
533                    self.state = AttributeIndent::WriteConfigured(i.indent_size)
534                }
535
536                AttributeIndent::WriteSpaces(_) => {}
537                // .new_line() called when .with_attribute() was called at least once.
538                // The spaces should be used to indent
539                // Plan saved indent
540                AttributeIndent::Spaces(indent) => {
541                    self.state = AttributeIndent::WriteSpaces(indent)
542                }
543
544                AttributeIndent::WriteConfigured(_) => {}
545                // .new_line() called when .with_attribute() was called at least once.
546                // The configured indent characters should be used to indent
547                // Plan saved indent
548                AttributeIndent::Configured(indent) => {
549                    self.state = AttributeIndent::WriteConfigured(indent)
550                }
551            }
552            self.start_tag.push_newline();
553        };
554        self
555    }
556
557    /// Writes attribute and maintain indentation state
558    fn write_attr<'b>(&mut self, attr: Attribute<'b>) {
559        if let Some(i) = self.writer.indent.as_mut() {
560            // Save the indent that we should use next time when .new_line() be called
561            self.state = match self.state {
562                // Neither .new_line() or .with_attribute() yet called
563                // If newline inside attributes will be requested, we should indent them
564                // by the length of tag name and +1 for `<` and +1 for one space
565                AttributeIndent::NoneAttributesWritten => {
566                    self.start_tag.push_attribute(attr);
567                    AttributeIndent::Spaces(self.start_tag.name().as_ref().len() + 2)
568                }
569
570                // Indent was requested by previous call to .new_line(), write it
571                // New line was already written
572                AttributeIndent::WriteSpaces(indent) => {
573                    if self.spaces.len() < indent {
574                        self.spaces = " ".repeat(indent);
575                    }
576                    self.start_tag.push_indent(&self.spaces[..indent]);
577                    self.start_tag.push_attr(attr);
578                    AttributeIndent::Spaces(indent)
579                }
580                // .new_line() was not called, but .with_attribute() was.
581                // use the previously calculated indent
582                AttributeIndent::Spaces(indent) => {
583                    self.start_tag.push_attribute(attr);
584                    AttributeIndent::Spaces(indent)
585                }
586
587                // Indent was requested by previous call to .new_line(), write it
588                // New line was already written
589                AttributeIndent::WriteConfigured(indent) => {
590                    self.start_tag.push_indent(i.additional(indent));
591                    self.start_tag.push_attr(attr);
592                    AttributeIndent::Configured(indent)
593                }
594                // .new_line() was not called, but .with_attribute() was.
595                // use the previously calculated indent
596                AttributeIndent::Configured(indent) => {
597                    self.start_tag.push_attribute(attr);
598                    AttributeIndent::Configured(indent)
599                }
600            };
601        } else {
602            self.start_tag.push_attribute(attr);
603        }
604    }
605}
606
607impl<'a, W: Write> ElementWriter<'a, W> {
608    /// Write some text inside the current element.
609    pub fn write_text_content(self, text: BytesText) -> io::Result<&'a mut Writer<W>> {
610        self.writer
611            .write_event(Event::Start(self.start_tag.borrow()))?;
612        self.writer.write_event(Event::Text(text))?;
613        self.writer
614            .write_event(Event::End(self.start_tag.to_end()))?;
615        Ok(self.writer)
616    }
617
618    /// Write a CData event `<![CDATA[...]]>` inside the current element.
619    pub fn write_cdata_content(self, text: BytesCData) -> io::Result<&'a mut Writer<W>> {
620        self.writer
621            .write_event(Event::Start(self.start_tag.borrow()))?;
622        self.writer.write_event(Event::CData(text))?;
623        self.writer
624            .write_event(Event::End(self.start_tag.to_end()))?;
625        Ok(self.writer)
626    }
627
628    /// Write a processing instruction `<?...?>` inside the current element.
629    pub fn write_pi_content(self, pi: BytesPI) -> io::Result<&'a mut Writer<W>> {
630        self.writer
631            .write_event(Event::Start(self.start_tag.borrow()))?;
632        self.writer.write_event(Event::PI(pi))?;
633        self.writer
634            .write_event(Event::End(self.start_tag.to_end()))?;
635        Ok(self.writer)
636    }
637
638    /// Write an empty (self-closing) tag.
639    pub fn write_empty(self) -> io::Result<&'a mut Writer<W>> {
640        self.writer.write_event(Event::Empty(self.start_tag))?;
641        Ok(self.writer)
642    }
643
644    /// Create a new scope for writing XML inside the current element.
645    pub fn write_inner_content<F>(self, closure: F) -> io::Result<&'a mut Writer<W>>
646    where
647        F: FnOnce(&mut Writer<W>) -> io::Result<()>,
648    {
649        self.writer
650            .write_event(Event::Start(self.start_tag.borrow()))?;
651        closure(self.writer)?;
652        self.writer
653            .write_event(Event::End(self.start_tag.to_end()))?;
654        Ok(self.writer)
655    }
656}
657#[cfg(feature = "serialize")]
658pub(crate) struct ToFmtWrite<T>(pub T);
659
660#[cfg(feature = "serialize")]
661impl<T> std::fmt::Write for ToFmtWrite<T>
662where
663    T: std::io::Write,
664{
665    fn write_str(&mut self, s: &str) -> std::fmt::Result {
666        self.0.write_all(s.as_bytes()).map_err(|_| std::fmt::Error)
667    }
668}
669
670#[derive(Debug, Clone)]
671pub(crate) struct Indentation {
672    /// todo: this is an awkward fit as it has no impact on indentation logic, but it is
673    /// only applicable when an indentation exists. Potentially refactor later
674    should_line_break: bool,
675    /// The character to be used for indentations (e.g. ` ` or `\t`)
676    indent_char: char,
677    /// How many instances of the indent character ought to be used for each level of indentation
678    indent_size: usize,
679    /// Used as a cache for the string used for indentation
680    indents: String,
681    /// The current amount of indentation
682    current_indent_len: usize,
683}
684
685impl Indentation {
686    pub fn new(indent_char: u8, indent_size: usize) -> Self {
687        let indent_char = char::from(indent_char);
688        Self {
689            should_line_break: false,
690            indent_char,
691            indent_size,
692            indents: std::iter::repeat(indent_char).take(128).collect(),
693            current_indent_len: 0,
694        }
695    }
696
697    /// Increase indentation by one level
698    pub fn grow(&mut self) {
699        self.current_indent_len += self.indent_size;
700        self.ensure(self.current_indent_len);
701    }
702
703    /// Decrease indentation by one level. Do nothing, if level already zero
704    pub fn shrink(&mut self) {
705        self.current_indent_len = self.current_indent_len.saturating_sub(self.indent_size);
706    }
707
708    /// Returns indent string for current level
709    pub fn current(&self) -> &str {
710        &self.indents[..self.current_indent_len]
711    }
712
713    /// Returns indent with current indent plus additional indent
714    pub fn additional(&mut self, additional_indent: usize) -> &str {
715        let new_len = self.current_indent_len + additional_indent;
716        self.ensure(new_len);
717        &self.indents[..new_len]
718    }
719
720    fn ensure(&mut self, new_len: usize) {
721        while self.indents.len() < new_len {
722            self.indents.push(self.indent_char);
723        }
724    }
725}