Skip to content

Commit

Permalink
diff: rewrite find_line/nonword_ranges() by using iterator adapters
Browse files Browse the repository at this point in the history
I don't think .scan() is descriptive name, but it looks slightly better than
placing accumulator out of the closure.
  • Loading branch information
yuja committed Jun 19, 2024
1 parent 5f2f13a commit f8b87f6
Showing 1 changed file with 11 additions and 24 deletions.
35 changes: 11 additions & 24 deletions lib/src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,13 @@ use std::slice;
use itertools::Itertools;

pub fn find_line_ranges(text: &[u8]) -> Vec<Range<usize>> {
let mut ranges = vec![];
let mut start = 0;
loop {
match text[start..].iter().position(|b| *b == b'\n') {
None => {
break;
}
Some(i) => {
ranges.push(start..start + i + 1);
start += i + 1;
}
}
}
if start < text.len() {
ranges.push(start..text.len());
}
ranges
text.split_inclusive(|b| *b == b'\n')
.scan(0, |total, line| {
let start = *total;
*total += line.len();
Some(start..*total)
})
.collect()
}

fn is_word_byte(b: u8) -> bool {
Expand Down Expand Up @@ -73,13 +63,10 @@ pub fn find_word_ranges(text: &[u8]) -> Vec<Range<usize>> {
}

pub fn find_nonword_ranges(text: &[u8]) -> Vec<Range<usize>> {
let mut ranges = vec![];
for (i, b) in text.iter().enumerate() {
if !is_word_byte(*b) {
ranges.push(i..i + 1);
}
}
ranges
text.iter()
.positions(|b| !is_word_byte(*b))
.map(|i| i..i + 1)
.collect()
}

struct Histogram<'a> {
Expand Down

0 comments on commit f8b87f6

Please sign in to comment.