buffer.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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::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: usize,
  14. }
  15. impl Buffer {
  16. // Create a new line and tab it to the current tab level
  17. pub fn tabbed_line(&mut self) -> Result {
  18. self.new_line()?;
  19. self.tab()
  20. }
  21. // Create a new line and tab it to the current tab level
  22. pub fn indented_tabbed_line(&mut self) -> Result {
  23. self.new_line()?;
  24. self.indented_tab()
  25. }
  26. pub fn tab(&mut self) -> Result {
  27. self.write_tabs(self.indent)
  28. }
  29. pub fn indented_tab(&mut self) -> Result {
  30. self.write_tabs(self.indent + 1)
  31. }
  32. pub fn write_tabs(&mut self, num: usize) -> std::fmt::Result {
  33. for _ in 0..num {
  34. write!(self.buf, " ")?
  35. }
  36. Ok(())
  37. }
  38. pub fn new_line(&mut self) -> Result {
  39. writeln!(self.buf)
  40. }
  41. pub fn write_text(&mut self, text: &IfmtInput) -> Result {
  42. write_ifmt(text, &mut self.buf)
  43. }
  44. }
  45. impl std::fmt::Write for Buffer {
  46. fn write_str(&mut self, s: &str) -> std::fmt::Result {
  47. self.buf.push_str(s);
  48. Ok(())
  49. }
  50. }