buffer.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. /// The output buffer that tracks indent and string
  9. #[derive(Debug, Default)]
  10. pub struct Buffer {
  11. pub buf: String,
  12. pub indent: usize,
  13. }
  14. impl Buffer {
  15. // Create a new line and tab it to the current tab level
  16. pub fn tabbed_line(&mut self) -> Result {
  17. self.new_line()?;
  18. self.tab()
  19. }
  20. // Create a new line and tab it to the current tab level
  21. pub fn indented_tabbed_line(&mut self) -> Result {
  22. self.new_line()?;
  23. self.indented_tab()
  24. }
  25. pub fn tab(&mut self) -> Result {
  26. self.write_tabs(self.indent)
  27. }
  28. pub fn indented_tab(&mut self) -> Result {
  29. self.write_tabs(self.indent + 1)
  30. }
  31. pub fn write_tabs(&mut self, num: usize) -> std::fmt::Result {
  32. for _ in 0..num {
  33. write!(self.buf, " ")?
  34. }
  35. Ok(())
  36. }
  37. pub fn new_line(&mut self) -> Result {
  38. writeln!(self.buf)
  39. }
  40. pub fn write_text(&mut self, text: &IfmtInput) -> Result {
  41. write!(self.buf, "\"{}\"", text.source.as_ref().unwrap().value())
  42. }
  43. }
  44. impl std::fmt::Write for Buffer {
  45. fn write_str(&mut self, s: &str) -> std::fmt::Result {
  46. self.buf.push_str(s);
  47. Ok(())
  48. }
  49. }