Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix line number being reset on each Indented write_str call #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 39 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
unused_parens,
while_true
)]

use core::fmt;

/// The set of supported formats for indentation
Expand Down Expand Up @@ -155,6 +156,7 @@ pub enum Format<'a> {
#[allow(missing_debug_implementations)]
pub struct Indented<'a, D: ?Sized> {
inner: &'a mut D,
line_number: usize,
needs_indent: bool,
format: Format<'a>,
}
Expand Down Expand Up @@ -203,23 +205,25 @@ where
T: fmt::Write + ?Sized,
{
fn write_str(&mut self, s: &str) -> fmt::Result {
for (ind, line) in s.split('\n').enumerate() {
if ind > 0 {
for (i, line) in s.split('\n').enumerate() {
if i > 0 {
self.inner.write_char('\n')?;
self.needs_indent = true;
}

if self.needs_indent {
// Don't render the line unless its actually got text on it
// Don't render the line unless it actually has text on it
if line.is_empty() {
continue;
}

self.format.insert_indentation(ind, &mut self.inner)?;
self.format
.insert_indentation(self.line_number, &mut self.inner)?;
self.line_number += 1;
self.needs_indent = false;
}

self.inner.write_fmt(format_args!("{}", line))?;
self.inner.write_str(line)?;
}

Ok(())
Expand All @@ -230,6 +234,7 @@ where
pub fn indented<D: ?Sized>(f: &mut D) -> Indented<'_, D> {
Indented {
inner: f,
line_number: 0,
needs_indent: true,
format: Format::Uniform {
indentation: " ",
Expand Down Expand Up @@ -427,6 +432,17 @@ mod tests {
assert_eq!(expected, output);
}

#[test]
fn empty_lines() {
let input = "\n\n\nverify\n\nthis";
let expected = "\n\n\n verify\n\n this";
let output = &mut String::new();

write!(indented(output).with_str(" "), "{}", input).unwrap();

assert_eq!(expected, output);
}

#[test]
fn trailing_newlines() {
let input = "verify\nthis\n";
Expand All @@ -448,6 +464,24 @@ mod tests {

assert_eq!(expected, output);
}

#[test]
fn several_interpolations_keep_monotonic_line_numbers() {
let input = '\n';
let expected = "verify\n this\n and this";
let output = &mut String::new();

write!(
indented(output).with_format(Format::Custom {
inserter: &mut move |line_no, f| { write!(f, "{:spaces$}", "", spaces = line_no) }
}),
"verify{}this{0}and this",
input
)
.unwrap();

assert_eq!(expected, output);
}
}

#[cfg(all(test, feature = "std"))]
Expand Down