Writing &[u8] to BufWriter, changing each \n to \n followed by $k$ spaces

I have a &[u8] that I want to write to a BufWriter. This is simple:

bw: &mut BufWriter;
data: &[u8];
buf.write_all(data)?

Now, we have some fixed $k$, and every time we write a \n, we want to write \n followed by $k$ spaces instead.

This is not too bad, we can iter over data, and for each char, see if it is a \n ....

This seems awfully silly, writing characters one by one to a BufWriter.

Is there a better approach ?

You can split by \n, write each segment, and then, if the segment ends in \n, follow it with k spaces

let spaces = b" ".repeat(k);
for segment in buf.split_inclusive(|c| *c == b'\n'); {
    buf.write_all(segment)?;
    // Only writes the spaces if there's a newline
    if segment.ends_with(b"\n") {
        buf.write_all(&spaces)?;
    }
}
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.