From 1f52dc9e635da636e3febd2caed1a2191d65a5df Mon Sep 17 00:00:00 2001 From: Semenov Herman Date: Wed, 4 Sep 2024 13:49:00 +0300 Subject: [PATCH 1/2] Optimization where possible More info: - https://stackoverflow.com/questions/60784280/string-view-as-a-parameter-of-const-reference - https://stackoverflow.com/questions/57761077/return-const-value-prevent-move-semantics - https://stackoverflow.com/questions/62081977/why-is-there-no-optimization-for-checking-for-empty-string-via-comparison - https://stackoverflow.com/questions/37689228/difference-between-str-clear-and-str --- include/cleanse.h | 16 ++++++------ include/cpplint_state.h | 20 +++++++-------- include/error_suppressions.h | 8 +++--- include/file_linter.h | 12 ++++----- include/nest_info.h | 49 ++++++++++++++++-------------------- include/options.h | 38 +++++++++++++++------------- include/regex_utils.h | 2 +- include/states.h | 12 ++++----- include/string_utils.h | 2 +- src/cpplint_state.cpp | 4 +-- src/file_linter.cpp | 14 +++++------ src/options.cpp | 24 +++++++++--------- src/states.cpp | 14 +++++------ src/string_utils.cpp | 2 +- 14 files changed, 107 insertions(+), 110 deletions(-) diff --git a/include/cleanse.h b/include/cleanse.h index 909539a..1de8b27 100644 --- a/include/cleanse.h +++ b/include/cleanse.h @@ -81,20 +81,20 @@ class CleansedLines { */ std::string ReplaceAlternateTokens(const std::string& line); - size_t NumLines() const { return m_lines.size(); } + [[nodiscard]] size_t NumLines() const { return m_lines.size(); } - const std::string& GetLineAt(size_t id) const { return m_lines[id]; } - const std::string& GetElidedAt(size_t id) const { return m_elided[id]; } - const std::vector& GetElidedLines() const { + [[nodiscard]] const std::string& GetLineAt(size_t id) const { return m_lines[id]; } + [[nodiscard]] const std::string& GetElidedAt(size_t id) const { return m_elided[id]; } + [[nodiscard]] const std::vector& GetElidedLines() const { return m_elided; } - const std::string& GetRawLineAt(size_t id) const { return m_raw_lines[id]; } - const std::string& GetLineWithoutRawStringAt(size_t id) const { + [[nodiscard]] const std::string& GetRawLineAt(size_t id) const { return m_raw_lines[id]; } + [[nodiscard]] const std::string& GetLineWithoutRawStringAt(size_t id) const { return m_lines_without_raw_strings[id]; } - const std::vector& GetLinesWithoutRawStrings() const { + [[nodiscard]] const std::vector& GetLinesWithoutRawStrings() const { return m_lines_without_raw_strings; } - bool HasComment(size_t id) const { return m_has_comment[id]; } + [[nodiscard]] bool HasComment(size_t id) const { return m_has_comment[id]; } }; diff --git a/include/cpplint_state.h b/include/cpplint_state.h index e673690..3181ebd 100644 --- a/include/cpplint_state.h +++ b/include/cpplint_state.h @@ -57,7 +57,7 @@ class CppLintState { public: CppLintState(); - int OutputFormat() const { return m_output_format; } + [[nodiscard]] int OutputFormat() const { return m_output_format; } void SetOutputFormat(const std::string& output_format) { // Sets the output format for errors. if (output_format == "vs7") @@ -74,7 +74,7 @@ class CppLintState { m_output_format = OUTPUT_EMACS; } - bool Quiet() const { return m_quiet; } + [[nodiscard]] bool Quiet() const { return m_quiet; } bool SetQuiet(bool quiet) { // Sets the module's quiet settings, and returns the previous setting. bool last_quiet = m_quiet; @@ -82,7 +82,7 @@ class CppLintState { return last_quiet; } - int VerboseLevel() const { return m_verbose_level; } + [[nodiscard]] int VerboseLevel() const { return m_verbose_level; } int SetVerboseLevel(int level) { // Sets the module's verbosity, and returns the previous setting. int last_verbose_level = m_verbose_level; @@ -106,11 +106,11 @@ class CppLintState { m_errors_by_category.clear(); } - int ErrorCount() const { return m_error_count; } - int ErrorCount(const std::string& category) const; + [[nodiscard]] int ErrorCount() const { return m_error_count; } + [[nodiscard]] int ErrorCount(const std::string& category) const; void SetNumThreads(int num_threads) { m_num_threads = num_threads; } - int GetNumThreads() const { return m_num_threads; } + [[nodiscard]] int GetNumThreads() const { return m_num_threads; } // Bumps the module's error statistic. void IncrementErrorCount(const std::string& category); @@ -129,10 +129,10 @@ class CppLintState { // Print a summary of errors by category, and the total. void PrintErrorCounts(); - void PrintInfo(const std::string& message); - void PrintError(const std::string& message); + void PrintInfo(const std::string& message) const; + void PrintError(const std::string& message) const; - bool AddJUnitFailure(const std::string& filename, + static bool AddJUnitFailure(const std::string& filename, size_t linenum, const std::string& message, const std::string& category, @@ -145,5 +145,5 @@ class CppLintState { return false; } - std::string FormatJUnitXML() { return ""; } + static std::string FormatJUnitXML() { return ""; } }; diff --git a/include/error_suppressions.h b/include/error_suppressions.h index d6d9a28..09b99ed 100644 --- a/include/error_suppressions.h +++ b/include/error_suppressions.h @@ -147,19 +147,19 @@ class LineRange { m_end = end; } - std::string ToStr() const { + [[nodiscard]] std::string ToStr() const { return "[" + std::to_string(m_begin) + "-" + std::to_string(m_end) +"]"; } - bool Contain(size_t linenum) const { + [[nodiscard]] bool Contain(size_t linenum) const { return m_begin <= linenum && linenum <= m_end; } - bool ContainRange(const LineRange& other) const { + [[nodiscard]] bool ContainRange(const LineRange& other) const { return m_begin <= other.m_begin && other.m_end <= m_end; } - size_t GetBegin() { + [[nodiscard]] size_t GetBegin() const { return m_begin; } diff --git a/include/file_linter.h b/include/file_linter.h index 902c22b..8bbe292 100644 --- a/include/file_linter.h +++ b/include/file_linter.h @@ -31,7 +31,7 @@ class FileLinter { bool m_has_error; public: - FileLinter() {} + FileLinter() = default; FileLinter(const fs::path& file, CppLintState* state, const Options& options) : m_cpplint_state(state), m_options(options), @@ -48,8 +48,8 @@ class FileLinter { m_re_result(RegexCreateMatchData(16)), m_has_error(false) {} - fs::path GetRelativeFromRepository(const fs::path& file, const fs::path& repository); - fs::path GetRelativeFromSubdir(const fs::path& file, const fs::path& subdir); + static fs::path GetRelativeFromRepository(const fs::path& file, const fs::path& repository); + static fs::path GetRelativeFromSubdir(const fs::path& file, const fs::path& subdir); // Logs an error if no Copyright message appears at the top of the file. void CheckForCopyright(const std::vector& lines); @@ -69,9 +69,9 @@ class FileLinter { */ void CheckForHeaderGuard(const CleansedLines& clean_lines); - bool IsForwardClassDeclaration(const std::string& elided_line); + static bool IsForwardClassDeclaration(const std::string& elided_line); - bool IsMacroDefinition(const CleansedLines& clean_lines, + static bool IsMacroDefinition(const CleansedLines& clean_lines, const std::string& elided_line, size_t linenum); void CheckForNamespaceIndentation(const CleansedLines& clean_lines, @@ -231,7 +231,7 @@ class FileLinter { IncludeState* include_state); // Checks whether where function type arguments are expected. - bool ExpectingFunctionArgs(const CleansedLines& clean_lines, + static bool ExpectingFunctionArgs(const CleansedLines& clean_lines, const std::string& elided_line, size_t linenum); // Checks for a C-style cast by looking for the pattern. diff --git a/include/nest_info.h b/include/nest_info.h index 6c98b31..fd01503 100644 --- a/include/nest_info.h +++ b/include/nest_info.h @@ -44,7 +44,7 @@ class BlockInfo { m_check_namespace_indentation(false), m_block_type(BLOCK_INFO) {} - virtual ~BlockInfo() {} + virtual ~BlockInfo() = default; /* Run checks that applies to text up to the opening brace. @@ -75,21 +75,21 @@ class BlockInfo { This is convenient for verifying that an object is an instance of a _BlockInfo, but not an instance of any of the derived classes. */ - bool IsBlockInfo() const { return m_block_type == BLOCK_INFO; } - bool IsExternCInfo() const { return m_block_type == EXTERN_C_INFO; } - bool IsClassInfo() const { return m_block_type == CLASS_INFO; } - bool IsNamespaceInfo() const { return m_block_type == NAMESPACE_INFO; } + [[nodiscard]] bool IsBlockInfo() const { return m_block_type == BLOCK_INFO; } + [[nodiscard]] bool IsExternCInfo() const { return m_block_type == EXTERN_C_INFO; } + [[nodiscard]] bool IsClassInfo() const { return m_block_type == CLASS_INFO; } + [[nodiscard]] bool IsNamespaceInfo() const { return m_block_type == NAMESPACE_INFO; } - bool SeenOpenBrace() const { return m_seen_open_brace; } + [[nodiscard]] bool SeenOpenBrace() const { return m_seen_open_brace; } void SetSeenOpenBrace(bool seen_open_brace) { m_seen_open_brace = seen_open_brace; } - int OpenParentheses() const { return m_open_parentheses; } + [[nodiscard]] int OpenParentheses() const { return m_open_parentheses; } void IncOpenParentheses(int inc) { m_open_parentheses += inc; } - int InlineAsm() const { return m_inline_asm; } + [[nodiscard]] int InlineAsm() const { return m_inline_asm; } void SetInlineAsm(int inline_asm) { m_inline_asm = inline_asm; } - size_t StartingLinenum() const { return m_starting_linenum; } + [[nodiscard]] size_t StartingLinenum() const { return m_starting_linenum; } }; // Stores information about an 'extern "C"' block. @@ -124,13 +124,13 @@ class ClassInfo : public BlockInfo { void CheckEnd(const CleansedLines& clean_lines, size_t linenum, FileLinter* file_linter) override; - const std::string& Access() const { return m_access; } + [[nodiscard]] const std::string& Access() const { return m_access; } void SetAccess(const std::string& access) { m_access = access; } - bool IsStruct() const { return m_is_struct; } - size_t ClassIndent() const { return m_class_indent; } - const std::string& Name() const { return m_name; } - const std::string& Basename() const { return m_basename; } - size_t LastLine() { return m_last_line; } + [[nodiscard]] bool IsStruct() const { return m_is_struct; } + [[nodiscard]] size_t ClassIndent() const { return m_class_indent; } + [[nodiscard]] const std::string& Name() const { return m_name; } + [[nodiscard]] const std::string& Basename() const { return m_basename; } + [[nodiscard]] size_t LastLine() const { return m_last_line; } }; // Stores information about a namespace. @@ -140,9 +140,9 @@ class NamespaceInfo : public BlockInfo { public: NamespaceInfo(const std::string& name, size_t linenum) : - BlockInfo(linenum, false) { + BlockInfo(linenum, false), + m_name(name) { m_block_type = NAMESPACE_INFO; - m_name = name; m_check_namespace_indentation = true; } @@ -159,18 +159,13 @@ class PreprocessorInfo { std::vector m_stack_before_else; public: - explicit PreprocessorInfo(const std::vector& stack_before_if) { - // The entire nesting stack before #if - m_stack_before_if = stack_before_if; - - // The entire nesting stack up to #else - m_stack_before_else = {}; - - // Whether we have already seen #else or #elif - m_seen_else = false; + explicit PreprocessorInfo(const std::vector& stack_before_if) : + m_stack_before_if(stack_before_if), // The entire nesting stack before #if + m_stack_before_else({}), // The entire nesting stack up to #else + m_seen_else(false) { // Whether we have already seen #else or #elif } - bool SeenElse() { return m_seen_else; } + [[nodiscard]] bool SeenElse() const { return m_seen_else; } void SetSeenElse(bool seen_else) { m_seen_else = seen_else; } const std::vector& StackBeforeIf() { diff --git a/include/options.h b/include/options.h index 55f5301..e6c364b 100644 --- a/include/options.h +++ b/include/options.h @@ -17,8 +17,8 @@ class Filter { public: Filter() : m_sign(false), - m_category(""), - m_file(""), + m_category(), + m_file(), m_linenum(INDEX_NONE) {} explicit Filter(const std::string& filter) { @@ -27,9 +27,9 @@ class Filter { void ParseFilterSelector(const std::string& filter); - bool IsPositive() const { return m_sign; } + [[nodiscard]] bool IsPositive() const { return m_sign; } - bool IsMatched(const std::string& category, + [[nodiscard]] bool IsMatched(const std::string& category, const std::string& file, size_t linenum) const { return category.starts_with(m_category) && @@ -76,12 +76,13 @@ class Options { // Searches a list of filenames and replaces directories in the list with // all files descending from those directories. Files with extensions not in // the valid extensions list are excluded. - std::vector ExpandDirectories(const std::vector& filenames); + std::vector ExpandDirectories(const std::vector& filenames) const; // Filters out files listed in the --exclude command line switch. File paths // in the switch are evaluated relative to the current working directory - std::vector FilterExcludedFiles(std::vector filenames, - const std::vector& excludes); + static std::vector FilterExcludedFiles( + std::vector filenames, + const std::vector& excludes); public: Options() : @@ -102,28 +103,29 @@ class Options { std::vector ParseArguments(int argc, char** argv, CppLintState* cpplint_state); - const fs::path& Root() const { return m_root; } - const fs::path& Repository() const { return m_repository; } - size_t LineLength() const { return m_line_length; } + [[nodiscard]] const fs::path& Root() const { return m_root; } + [[nodiscard]] const fs::path& Repository() const { return m_repository; } + [[nodiscard]] size_t LineLength() const { return m_line_length; } - std::set GetAllExtensions() const; - std::set GetHeaderExtensions() const; + [[nodiscard]] std::set GetAllExtensions() const; + [[nodiscard]] std::set GetHeaderExtensions() const; bool ProcessConfigOverrides(const fs::path& filename, CppLintState* cpplint_state); - void PrintUsage(const std::string& message = ""); + void PrintUsage(const std::string& message = "") const; - int IncludeOrder() const { return m_include_order; } + [[nodiscard]] int IncludeOrder() const { return m_include_order; } - const std::vector& Filters() const { return m_filters; } + [[nodiscard]] const std::vector& Filters() const { return m_filters; } // Adds filters to the existing list of error-message filters. bool AddFilters(const std::string& filters); // Checks if the error is filtered or not. - bool ShouldPrintError(const std::string& category, - const std::string& filename, size_t linenum) const; + [[nodiscard]] bool ShouldPrintError( + const std::string& category, + const std::string& filename, size_t linenum) const; - bool Timing() const { return m_timing; } + [[nodiscard]] bool Timing() const { return m_timing; } }; diff --git a/include/regex_utils.h b/include/regex_utils.h index 16b581a..20a0186 100644 --- a/include/regex_utils.h +++ b/include/regex_utils.h @@ -260,7 +260,7 @@ inline void RegexReplace(const regex_code& regex, const std::string& fmt, std::string RegexEscape(const std::string& str); -inline std::string RegexEscape(const std::string_view& str) { +inline std::string RegexEscape(std::string_view str) { return RegexEscape(std::string(str)); } diff --git a/include/states.h b/include/states.h index 2457dc9..6244b35 100644 --- a/include/states.h +++ b/include/states.h @@ -41,7 +41,7 @@ class IncludeState { public: IncludeState() : m_section(0), - m_last_header(""), + m_last_header(), m_include_list({{}}) { ResetSection(""); } @@ -64,7 +64,7 @@ class IncludeState { - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. */ - std::string CanonicalizeAlphabeticalOrder(const std::string& header_path); + static std::string CanonicalizeAlphabeticalOrder(const std::string& header_path); // Check if a header is in alphabetical order with the previous header. bool IsInAlphabeticalOrder(const CleansedLines& clean_lines, @@ -79,7 +79,7 @@ class IncludeState { std::string CheckNextIncludeOrder(int header_type); std::vector>& LastIncludeList() { return m_include_list.back(); } - const auto& IncludeList() const { return m_include_list; } + [[nodiscard]] const auto& IncludeList() const { return m_include_list; } std::set GetIncludes() { std::set includes = {}; for (const auto& sublist : m_include_list) { @@ -102,10 +102,10 @@ class FunctionState { FunctionState() : m_in_a_function(false), m_lines_in_function(0), - m_current_function("") {} + m_current_function() {} // Start analyzing function body. - void Begin(const std::string function_name) { + void Begin(const std::string& function_name) { m_in_a_function = true; m_lines_in_function = 0; m_current_function = function_name; @@ -203,7 +203,7 @@ class NestingState { } // Check if current position is inside template argument list. - bool InTemplateArgumentList(const CleansedLines& clean_lines, size_t linenum, size_t pos); + static bool InTemplateArgumentList(const CleansedLines& clean_lines, size_t linenum, size_t pos); /*Update preprocessor stack. diff --git a/include/string_utils.h b/include/string_utils.h index 44e37bd..94831dd 100644 --- a/include/string_utils.h +++ b/include/string_utils.h @@ -148,7 +148,7 @@ size_t GetLastNonSpacePos(const std::string& str) noexcept; // Returns true if the string consists of only digits. bool StrIsDigit(const std::string& str) noexcept; -bool StrIsDigit(const std::string_view& str) noexcept; +bool StrIsDigit(std::string_view str) noexcept; // Remove items of set2 from set1. std::set SetDiff(const std::set& set1, diff --git a/src/cpplint_state.cpp b/src/cpplint_state.cpp index 54207a0..d4d4448 100644 --- a/src/cpplint_state.cpp +++ b/src/cpplint_state.cpp @@ -62,7 +62,7 @@ thread_local std::ostringstream cerr_buffer; // Flush streams when the buffer size is larger than this value static const std::streampos FLUSH_THRESHOLD = 1024; -void CppLintState::PrintInfo(const std::string& message) { +void CppLintState::PrintInfo(const std::string& message) const { // _quiet does not represent --quiet flag. // Hide infos from stdout to keep stdout pure for machine consumption if (m_output_format != OUTPUT_JUNIT && @@ -71,7 +71,7 @@ void CppLintState::PrintInfo(const std::string& message) { cout_buffer << message; } -void CppLintState::PrintError(const std::string& message) { +void CppLintState::PrintError(const std::string& message) const { if (m_output_format == OUTPUT_JUNIT) { // m_junit_errors.push_back(message); } else { diff --git a/src/file_linter.cpp b/src/file_linter.cpp index fd9644f..95eebc4 100644 --- a/src/file_linter.cpp +++ b/src/file_linter.cpp @@ -1551,7 +1551,7 @@ const regex_code RE_PATTERN_TYPES = static bool IsType(const CleansedLines& clean_lines, NestingState* nesting_state, - const std::string_view& expr, + std::string_view expr, regex_match& re_result) { // Check if expression looks like a type name, returns true if so. // Keep only the last token in the expression @@ -3211,7 +3211,7 @@ void FileLinter::CheckForNonConstReference(const CleansedLines& clean_lines, if (startpos != INDEX_NONE && startline < linenum) { // Found the matching < on an earlier line, collect all // pieces up to current line. - line = ""; + line.clear(); for (size_t i = startline; i < linenum + 1; i++) line += StrStrip(clean_lines.GetElidedAt(i)); } @@ -3721,7 +3721,7 @@ void FileLinter::ProcessLine(bool is_header_extension, typedef std::vector> header_patterns_t; // Other scripts may reach in and modify this pattern. -static const header_patterns_t CompileContainingTemplatesPatterns() { +static header_patterns_t CompileContainingTemplatesPatterns() { const std::vector>> HEADERS_CONTAINING_TEMPLATES = { { "deque", { "deque", } }, @@ -3774,7 +3774,7 @@ static const header_patterns_t CompileContainingTemplatesPatterns() { static const header_patterns_t RE_PATTERNS_CONTAINING_TEMPLATES = CompileContainingTemplatesPatterns(); -static const header_patterns_t CompileMaybeTemplatesPatterns() { +static header_patterns_t CompileMaybeTemplatesPatterns() { const std::vector>> HEADERS_MAYBE_TEMPLATES = { { "algorithm", { "copy", "max", "min", "min_element", "sort", "transform" } }, @@ -3795,7 +3795,7 @@ static const header_patterns_t RE_PATTERNS_MAYBE_TEMPLATES = CompileMaybeTemplatesPatterns(); // Non templated types or global objects -static const header_patterns_t CompileTypesOrObjsPatterns() { +static header_patterns_t CompileTypesOrObjsPatterns() { const std::vector>> HEADERS_TYPES_OR_OBJS = { // String and others are special -- it is a non-templatized type in STL. @@ -3817,7 +3817,7 @@ static const header_patterns_t RE_PATTERNS_TYPES_OR_OBJS = CompileTypesOrObjsPatterns(); // Non templated functions -static const regex_code CompileCstdioPatterns() { +static regex_code CompileCstdioPatterns() { const std::set HEADERS_CSTDIO_FUNCTIONS = { "fopen", "freopen", "fclose", "fflush", "setbuf", "setvbuf", "fread", @@ -3983,7 +3983,7 @@ void FileLinter::CacheVariables() { m_file_extension.size()); std::string ext = m_file.extension().string(); if (ext.empty()) - m_file_extension = ""; + m_file_extension.clear(); else m_file_extension = &(m_file.extension().string())[1]; m_all_extensions = m_options.GetAllExtensions(); diff --git a/src/options.cpp b/src/options.cpp index 8309af6..59b5aac 100644 --- a/src/options.cpp +++ b/src/options.cpp @@ -261,7 +261,7 @@ static const char* USAGE[] = { " file is located) and all sub-directories.\n" }; -void Options::PrintUsage(const std::string& message) { +void Options::PrintUsage(const std::string& message) const { /*Prints a brief usage string and exits, optionally with an error message. Args: @@ -276,7 +276,7 @@ void Options::PrintUsage(const std::string& message) { std::ostream* ostream = &std::cout; int status = 0; - if (message != "") { + if (!message.empty()) { ostream = &std::cerr; status = 1; } @@ -286,7 +286,7 @@ void Options::PrintUsage(const std::string& message) { USAGE[2] << header_exts_as_list << USAGE[3] << header_exts_as_opt << USAGE[4]; - if (message != "") + if (!message.empty()) *ostream << "\nFATAL ERROR: " << message << "\n"; exit(status); } @@ -386,7 +386,7 @@ std::vector Options::ParseArguments(int argc, char** argv, PrintUsage("Verbosity should be an integer. (" + opt + ")"); } else if (opt.starts_with("--filter=")) { std::string filters = ArgToValue(opt); - if (filters == "") + if (filters.empty()) PrintCategories(); bool added = AddFilters(filters); if (!added) { @@ -414,7 +414,7 @@ std::vector Options::ParseArguments(int argc, char** argv, PrintUsage("Line length should be an integer. (" + opt + ")"); } else if (opt.starts_with("--exclude=")) { std::string val = ArgToValue(opt); - if (val != "") { + if (!val.empty()) { excludes.emplace_back( fs::weakly_canonical(fs::absolute(val)).make_preferred()); } @@ -492,7 +492,7 @@ void Options::ProcessHppHeadersOption(const std::string& val) { } void Options::ProcessIncludeOrderOption(const std::string& val) { - if (val == "" || val == "default") + if (val.empty() || val == "default") m_include_order = INCLUDE_ORDER_DEFAULT; else if (val == "standardcfirst") m_include_order = INCLUDE_ORDER_STDCFIRST; @@ -546,7 +546,7 @@ static void ExpandDirectoriesRec(const fs::path& root, } } -std::vector Options::ExpandDirectories(const std::vector& filenames) { +std::vector Options::ExpandDirectories(const std::vector& filenames) const { std::vector filtered = {}; std::set extensions = GetAllExtensions(); for (const fs::path& f : filenames) { @@ -624,7 +624,7 @@ class CfgFile { line_length(INDEX_NONE), extensions({}), headers({}), - include_order("") + include_order() {} bool ReadFile(const fs::path& file, CppLintState* cpplint_state) { @@ -667,7 +667,7 @@ class CfgFile { } else if (name == "headers") { headers = ParseCommaSeparetedList(val); } else if (name == "includeorder") { - include_order = val; + include_order = std::move(val); } else { cpplint_state->PrintError( "Invalid configuration option (" + name + @@ -789,8 +789,8 @@ void Filter::ParseFilterSelector(const std::string& filter) { } else if (filter[0] == '-') { m_sign = false; } else { - m_category = ""; - m_file = ""; + m_category.clear(); + m_file.clear(); m_linenum = INDEX_NONE; return; } @@ -798,7 +798,7 @@ void Filter::ParseFilterSelector(const std::string& filter) { size_t colon_pos = filter.find(':', 1); if (colon_pos == std::string::npos) { m_category = filter.substr(1); - m_file = ""; + m_file.clear(); m_linenum = INDEX_NONE; return; } diff --git a/src/states.cpp b/src/states.cpp index 83a578e..ec50fb1 100644 --- a/src/states.cpp +++ b/src/states.cpp @@ -55,12 +55,12 @@ void IncludeState::ResetSection(const std::string& directive) { // The name of the current section. m_section = INITIAL_SECTION; // The path of last found header. - m_last_header = ""; + m_last_header.clear(); // Update list of includes. Note that we never pop from the // include list. if (InStrVec({ "if", "ifdef", "ifndef" }, directive)) - m_include_list.push_back({}); + m_include_list.emplace_back(); else if (directive == "else" || directive == "elif") m_include_list.back() = {}; } @@ -98,21 +98,21 @@ std::string IncludeState::CheckNextIncludeOrder(int header_type) { if (m_section <= C_SECTION) { m_section = C_SECTION; } else { - m_last_header = ""; + m_last_header.clear(); return error_message; } } else if (header_type == CPP_SYS_HEADER) { if (m_section <= CPP_SECTION) { m_section = CPP_SECTION; } else { - m_last_header = ""; + m_last_header.clear(); return error_message; } } else if (header_type == OTHER_SYS_HEADER) { if (m_section <= OTHER_SYS_SECTION) { m_section = OTHER_SYS_SECTION; } else { - m_last_header = ""; + m_last_header.clear(); return error_message; } } else if (header_type == LIKELY_MY_HEADER) { @@ -134,7 +134,7 @@ std::string IncludeState::CheckNextIncludeOrder(int header_type) { } if (last_section != m_section) - m_last_header = ""; + m_last_header.clear(); return ""; } @@ -264,7 +264,7 @@ void NestingState::UpdatePreprocessor(const std::string& line) { if (RegexMatch(RE_PATTERN_IF_MACRO, line)) { // Beginning of #if block, save the nesting stack here. The saved // stack will allow us to restore the parsing state in the #else case. - m_pp_stack.push(PreprocessorInfo(m_stack)); + m_pp_stack.emplace(m_stack); } else if (RegexMatch(RE_PATTERN_ELSE_MACRO, line)) { // Beginning of #else block if (!m_pp_stack.empty()) { diff --git a/src/string_utils.cpp b/src/string_utils.cpp index 43a477d..216d34e 100644 --- a/src/string_utils.cpp +++ b/src/string_utils.cpp @@ -346,7 +346,7 @@ bool StrIsDigit(const std::string& str) noexcept { return *start == '\0'; } -bool StrIsDigit(const std::string_view& str) noexcept { +bool StrIsDigit(std::string_view str) noexcept { if (str.empty()) return false; const char* start = str.data(); const char* end = start + str.size(); From 7b6e8f7a84208908830ea7de41e13acc42577219 Mon Sep 17 00:00:00 2001 From: Semenov Herman Date: Wed, 4 Sep 2024 13:49:21 +0300 Subject: [PATCH 2/2] Reserve where possible --- include/ThreadPool.h | 2 ++ src/cleanse.cpp | 8 ++++---- src/cpplint.cpp | 1 + 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/include/ThreadPool.h b/include/ThreadPool.h index c17e5f3..71efb7b 100644 --- a/include/ThreadPool.h +++ b/include/ThreadPool.h @@ -4,6 +4,7 @@ * Modified version of ThreadPool (https://github.com/progschj/ThreadPool/blob/master/ThreadPool.h) * Changes * - Replaced std::result_of with std::invoke_result_t for c++20 + * - Added reserve call for workers to preallocate threads */ #include @@ -39,6 +40,7 @@ class ThreadPool { inline ThreadPool::ThreadPool(size_t threads) : stop(false) { + workers.reserve(threads); for(size_t i = 0;i& raw_lines) { RegexMatch(R"(^(\s*)\S)", line, m_re_result); new_line = GetMatchStr(m_re_result, line, 1) + "\"\"" + line.substr(end + delimiter.size()); - delimiter = ""; + delimiter.clear(); } else { // Haven't found the end yet, append a blank line. new_line = "\"\""; @@ -115,7 +115,7 @@ CleansedLines::CleanseRawStrings(const std::vector& raw_lines) { // Raw string ended on same line new_line = match_str_1 + "\"\"" + std::string(match_str_3.substr(end + delimiter.size())); - delimiter = ""; + delimiter.clear(); } else { // Start of a multi-line raw string new_line = match_str_1 + "\"\""; @@ -280,9 +280,9 @@ CleansedLines::CleansedLines(std::vector& lines, line = ReplaceAlternateTokens(line); } } - m_lines.reserve(lines.size()); - m_elided.reserve(lines.size()); m_lines_without_raw_strings = CleanseRawStrings(m_raw_lines); + m_lines.reserve(m_lines_without_raw_strings.size()); + m_elided.reserve(m_lines_without_raw_strings.size()); size_t linenum = 0; for (const std::string& line : m_lines_without_raw_strings) { bool is_comment = false; diff --git a/src/cpplint.cpp b/src/cpplint.cpp index 6326e11..ad7d23d 100644 --- a/src/cpplint.cpp +++ b/src/cpplint.cpp @@ -45,6 +45,7 @@ int main(int argc, char** argv) { // Multi-threading ThreadPool pool(num_threads); std::vector> futures; + futures.reserve(filenames.size()); for (const fs::path& filename : filenames) { futures.push_back(pool.enqueue([&filename, &cpplint_state, &global_options]() { ProcessFile(filename, &cpplint_state, global_options);