Skip to content

Commit

Permalink
Preserve last newline even if not indented
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Jan 29, 2023
1 parent 5586b97 commit 31694b5
Showing 1 changed file with 3 additions and 27 deletions.
30 changes: 3 additions & 27 deletions src/unindent.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::iter::Peekable;
use std::slice::Split;

pub fn unindent(s: &str) -> String {
Expand Down Expand Up @@ -90,11 +89,11 @@ fn count_spaces(line: &[u8]) -> Option<usize> {

// Based on core::str::StrExt.
trait BytesExt {
fn lines(&self) -> Lines;
fn lines(&self) -> Split<u8, fn(&u8) -> bool>;
}

impl BytesExt for [u8] {
fn lines(&self) -> Lines {
fn lines(&self) -> Split<u8, fn(&u8) -> bool> {
fn is_newline(b: &u8) -> bool {
*b == b'\n'
}
Expand All @@ -103,29 +102,6 @@ impl BytesExt for [u8] {
} else {
self
};
Lines {
split: bytestring.split(is_newline as fn(&u8) -> bool).peekable(),
}
}
}

struct Lines<'a> {
split: Peekable<Split<'a, u8, fn(&u8) -> bool>>,
}

impl<'a> Iterator for Lines<'a> {
type Item = &'a [u8];

fn next(&mut self) -> Option<Self::Item> {
match self.split.next() {
None => None,
Some(fragment) => {
if fragment.is_empty() && self.split.peek().is_none() {
None
} else {
Some(fragment)
}
}
}
bytestring.split(is_newline as fn(&u8) -> bool)
}
}

0 comments on commit 31694b5

Please sign in to comment.