fix: Remove trailing lines before calculating max_lines (#261)

* fix: Remove trailing lines before calculating max_lines

Signed-off-by: Xuanwo <github@xuanwo.io>

* refactor: Code cleanup for max_lines

Signed-off-by: Xuanwo <github@xuanwo.io>
pull/264/head
Xuanwo 2022-04-22 15:50:26 +07:00 committed by GitHub
parent 80429e9697
commit a143d75727
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 15 additions and 6 deletions

@ -1,10 +1,8 @@
//! Manipulate lines of text and groups of lines.
use crate::positions::SingleLineSpan;
use std::{
cmp::{max, Ordering},
fmt,
};
use std::ops::Sub;
use std::{cmp::Ordering, fmt};
/// A distinct number type for line numbers, to prevent confusion with
/// other numerical data.
@ -165,7 +163,12 @@ pub trait MaxLine {
impl<S: AsRef<str>> MaxLine for S {
fn max_line(&self) -> LineNumber {
(max(1, self.as_ref().split('\n').count()) - 1).into()
self.as_ref()
.trim_end() // Remove extra trailing whitespaces.
.split('\n') // Split by `\n` to calculate lines.
.count()
.sub(1) // Sub 1 to make zero-indexed LineNumber
.into()
}
}
@ -239,7 +242,13 @@ mod tests {
#[test]
fn str_max_line_trailing_newline() {
let line: String = "foo\nbar\n".into();
assert_eq!(line.max_line().0, 2);
assert_eq!(line.max_line().0, 1);
}
#[test]
fn str_max_line_extra_trailing_newline() {
let line: String = "foo\nbar\n\n".into();
assert_eq!(line.max_line().0, 1);
}
#[test]