perf: Avoid `Vec<&str>` allocation during line length checking

This commit is contained in:
Dmitry Dygalo 2022-09-03 20:50:55 +02:00
parent 4319bd1755
commit d9f656d552
No known key found for this signature in database
GPG Key ID: 0D78E60518FE18BB
1 changed files with 23 additions and 10 deletions

View File

@ -3,6 +3,22 @@ use rustpython_parser::ast::Location;
use crate::checks::{Check, CheckKind};
use crate::settings::Settings;
/// Whether the given line is too long and should be reported.
fn should_enforce_line_length(line: &str, limit: usize) -> bool {
if line.len() > limit {
let mut chunks = line.split_whitespace();
if let (Some(first), Some(_)) = (chunks.next(), chunks.next()) {
// Do not enforce the line length for commented lines with a single word
!(first == "#" && chunks.next().is_none())
} else {
// Single word / no printable chars - no way to make the line shorter
false
}
} else {
false
}
}
pub fn check_lines(checks: &mut Vec<Check>, contents: &str, settings: &Settings) {
let enforce_line_too_ling = settings.select.contains(CheckKind::LineTooLong.code());
@ -18,9 +34,7 @@ pub fn check_lines(checks: &mut Vec<Check>, contents: &str, settings: &Settings)
}
// Enforce line length.
if enforce_line_too_ling && line.len() > settings.line_length {
let chunks: Vec<&str> = line.split_whitespace().collect();
if !(chunks.len() == 1 || (chunks.len() == 2 && chunks[0] == "#")) {
if enforce_line_too_ling && should_enforce_line_length(line, settings.line_length) {
let check = Check {
kind: CheckKind::LineTooLong,
location: Location::new(row + 1, settings.line_length + 1),
@ -30,7 +44,6 @@ pub fn check_lines(checks: &mut Vec<Check>, contents: &str, settings: &Settings)
}
}
}
}
ignored.sort();
for index in ignored.iter().rev() {
checks.swap_remove(*index);