buffer.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //! The output buffer that supports some helpful methods
  2. //! These are separate from the input so we can lend references between the two
  3. //!
  4. //!
  5. //!
  6. use std::fmt::{Result, Write};
  7. use dioxus_rsx::IfmtInput;
  8. use crate::{indent::IndentOptions, write_ifmt};
  9. /// The output buffer that tracks indent and string
  10. #[derive(Debug, Default)]
  11. pub struct Buffer {
  12. pub buf: String,
  13. pub indent_level: usize,
  14. pub indent: IndentOptions,
  15. }
  16. impl Buffer {
  17. // Create a new line and tab it to the current tab level
  18. pub fn tabbed_line(&mut self) -> Result {
  19. self.new_line()?;
  20. self.tab()
  21. }
  22. // Create a new line and tab it to the current tab level
  23. pub fn indented_tabbed_line(&mut self) -> Result {
  24. self.new_line()?;
  25. self.indented_tab()
  26. }
  27. pub fn tab(&mut self) -> Result {
  28. self.write_tabs(self.indent_level)
  29. }
  30. pub fn indented_tab(&mut self) -> Result {
  31. self.write_tabs(self.indent_level + 1)
  32. }
  33. pub fn write_tabs(&mut self, num: usize) -> std::fmt::Result {
  34. for _ in 0..num {
  35. write!(self.buf, "{}", self.indent.indent_str())?
  36. }
  37. Ok(())
  38. }
  39. pub fn new_line(&mut self) -> Result {
  40. writeln!(self.buf)
  41. }
  42. pub fn write_text(&mut self, text: &IfmtInput) -> Result {
  43. write_ifmt(text, &mut self.buf)
  44. }
  45. }
  46. impl std::fmt::Write for Buffer {
  47. fn write_str(&mut self, s: &str) -> std::fmt::Result {
  48. self.buf.push_str(s);
  49. Ok(())
  50. }
  51. }