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)?;
}
}