From d9f656d55249f7e7b15024f68cccbba1f9051794 Mon Sep 17 00:00:00 2001 From: Dmitry Dygalo Date: Sat, 3 Sep 2022 20:50:55 +0200 Subject: [PATCH] perf: Avoid `Vec<&str>` allocation during line length checking --- src/check_lines.rs | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/check_lines.rs b/src/check_lines.rs index 08c22ee843..453d74cd5f 100644 --- a/src/check_lines.rs +++ b/src/check_lines.rs @@ -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, contents: &str, settings: &Settings) { let enforce_line_too_ling = settings.select.contains(CheckKind::LineTooLong.code()); @@ -18,16 +34,13 @@ pub fn check_lines(checks: &mut Vec, 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] == "#")) { - let check = Check { - kind: CheckKind::LineTooLong, - location: Location::new(row + 1, settings.line_length + 1), - }; - if !check.is_inline_ignored(line) { - line_checks.push(check); - } + 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), + }; + if !check.is_inline_ignored(line) { + line_checks.push(check); } } }