Skip to content

Commit

Permalink
add zero allocation indenting function
Browse files Browse the repository at this point in the history
  • Loading branch information
cmrschwarz committed Jul 17, 2024
1 parent 51808b9 commit cace44d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,7 @@ pub fn indent_aware_write(
}

if let Some(indent) = rc.get_indent_string() {
out.write(support::str::with_indent(v, indent).as_ref())?;
support::str::write_indented(v, indent, out)?;
} else {
out.write(v.as_ref())?;
}
Expand Down
20 changes: 20 additions & 0 deletions src/support.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
pub mod str {
use std::io::{Result, Write};

use crate::Output;

#[derive(Debug)]
pub struct StringWriter {
buf: Vec<u8>,
Expand Down Expand Up @@ -70,6 +72,24 @@ pub mod str {
output
}

/// like `with_indent`, but writing straight into the output
pub fn write_indented(s: &str, indent: &str, w: &mut dyn Output) -> std::io::Result<()> {
let mut i = 0;
let len = s.len();
loop {
let Some(next_newline) = s[i..].find('\n') else {
w.write(&s[i..])?;
return Ok(());
};
w.write(&s[i..i + next_newline + 1])?;
i += next_newline + 1;
if i == len {
return Ok(());
}
w.write(indent)?;
}
}

#[inline]
pub(crate) fn whitespace_matcher(c: char) -> bool {
c == ' ' || c == '\t'
Expand Down

0 comments on commit cace44d

Please sign in to comment.