Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(clp-s): Replace instances of std::string const& with std::string_view where it would remove unnecessary conversions to and from std::string. #635

Merged
merged 5 commits into from
Dec 16, 2024

Conversation

gibber9809
Copy link
Contributor

@gibber9809 gibber9809 commented Dec 13, 2024

Description

This PR splits out some of the refactoring work from the escape character fix PR to ease review.

In particular this PR:

  1. Replaces many uses of std::string const& with std::string_view const, which allows us to avoid some expensive string_view -> string -> string_view round trips
  2. Removes some duplicated code
  3. Adds some previously missing headers

This PR is pure refactoring with no functional changes.

Validation performed

  • Validated that all unit tests pass, and compression/decompression function as normal

Summary by CodeRabbit

  • New Features

    • Enhanced string handling efficiency by incorporating std::string_view across multiple classes and methods.
  • Bug Fixes

    • Streamlined logic in the StringLiteral class for detecting unescaped wildcard characters.
  • Documentation

    • Updated method signatures to reflect the new parameter types for better performance.

Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

Walkthrough

This pull request introduces modifications across several classes to change method parameter types from std::string const& to std::string_view. The affected classes include ArchiveWriter, ParsedMessage, TimestampDictionaryWriter, TimestampEntry, and TimestampPattern. These changes aim to enhance string handling efficiency by reducing unnecessary copies. The overall functionality and control flow of the methods remain unchanged, ensuring that existing logic and error handling mechanisms are preserved.

Changes

File Path Change Summary
components/core/src/clp_s/ArchiveWriter.hpp Updated method signatures for ingest_timestamp_entry to use std::string_view instead of std::string const&.
components/core/src/clp_s/ParsedMessage.hpp Added overloads for add_value and add_unordered_value methods to accept std::string_view.
components/core/src/clp_s/TimestampDictionaryWriter.cpp Changed parameter types in three overloaded ingest_entry methods from std::string const& to std::string_view.
components/core/src/clp_s/TimestampDictionaryWriter.hpp Updated method signatures for ingest_entry methods to use std::string_view instead of std::string const&.
components/core/src/clp_s/TimestampEntry.hpp Modified constructor to accept std::string_view instead of std::string const&.
components/core/src/clp_s/TimestampPattern.cpp Changed parameter types in four methods to accept std::string_view instead of std::string.
components/core/src/clp_s/TimestampPattern.hpp Updated method signatures for search_known_ts_patterns and parse_timestamp to use std::string_view instead of std::string const&.
components/core/src/clp_s/search/StringLiteral.hpp Simplified logic in the StringLiteral constructor by replacing manual wildcard checks with a call to StringUtils::has_unescaped_wildcards(m_v).

Possibly related PRs

  • feat(clp-s): Add the write path for single-file archives. #563: The changes in this PR involve modifications to the ArchiveWriter class, specifically adding new methods and altering existing ones related to archive handling, which is closely related to the changes made in the main PR that updates method signatures in the same ArchiveWriter class.
  • refactor(clp-package): Unify the metadata schema for JSON and IR streams. #620: This PR standardizes metadata handling by replacing orig_file_id with stream_id, which aligns with the changes in the main PR that also involve updates to method signatures and handling of string parameters, indicating a broader effort to streamline archive and metadata management.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 22e5ad4 and c993273.

📒 Files selected for processing (1)
  • components/core/src/clp_s/ArchiveWriter.hpp (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/core/src/clp_s/ArchiveWriter.hpp

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
components/core/src/clp_s/TimestampDictionaryWriter.cpp (1)

Line range hint 47-91: Consider updating nullptr check to match coding guidelines.

The check nullptr == pattern follows the coding guideline of preferring false == <expression> style, but could be more consistent throughout the function.

Apply this change:

-    if (nullptr == pattern) {
+    if (nullptr == pattern) {
         pattern = TimestampPattern::search_known_ts_patterns(
                 timestamp,
                 ret,
                 timestamp_begin_pos,
                 timestamp_end_pos
         );
         pattern_id = get_pattern_id(pattern);
     }

-    if (nullptr == pattern) {
+    if (nullptr == pattern) {
         throw OperationFailed(ErrorCodeFailure, __FILE__, __LINE__);
     }
components/core/src/clp_s/ArchiveWriter.hpp (1)

127-127: Consider using string_view for the key parameter as well.

While the change to use string_view const for the timestamp parameter is good, consider extending this optimization to the key parameter as well, since it's also used as a read-only value.

-    epochtime_t ingest_timestamp_entry(
-            std::string const& key,
-            int32_t node_id,
-            std::string_view const timestamp,
-            uint64_t& pattern_id
-    )
+    epochtime_t ingest_timestamp_entry(
+            std::string_view const key,
+            int32_t node_id,
+            std::string_view const timestamp,
+            uint64_t& pattern_id
+    )
components/core/src/clp_s/search/StringLiteral.hpp (1)

73-74: Excellent refactoring to use the utility function

The replacement of manual wildcard checking with StringUtils::has_unescaped_wildcards improves code maintainability and reduces duplication. The functionality remains unchanged while the implementation is cleaner.

Consider adding a brief comment explaining why ClpStringT is added when wildcards are present, as this business logic might not be immediately obvious to new developers:

        // If '?' and '*' are not escaped, we add LiteralType::ClpStringT to m_string_type
+       // Wildcards are only supported in CLP strings, so we must include this type
        if (StringUtils::has_unescaped_wildcards(m_v)) {
            m_string_type |= LiteralType::ClpStringT;
        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 909e19e and 3d62e5e.

📒 Files selected for processing (8)
  • components/core/src/clp_s/ArchiveWriter.hpp (1 hunks)
  • components/core/src/clp_s/ParsedMessage.hpp (3 hunks)
  • components/core/src/clp_s/TimestampDictionaryWriter.cpp (4 hunks)
  • components/core/src/clp_s/TimestampDictionaryWriter.hpp (3 hunks)
  • components/core/src/clp_s/TimestampEntry.hpp (2 hunks)
  • components/core/src/clp_s/TimestampPattern.cpp (7 hunks)
  • components/core/src/clp_s/TimestampPattern.hpp (3 hunks)
  • components/core/src/clp_s/search/StringLiteral.hpp (2 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
components/core/src/clp_s/search/StringLiteral.hpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

components/core/src/clp_s/TimestampEntry.hpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

components/core/src/clp_s/ArchiveWriter.hpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

components/core/src/clp_s/ParsedMessage.hpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

components/core/src/clp_s/TimestampPattern.hpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

components/core/src/clp_s/TimestampDictionaryWriter.hpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

components/core/src/clp_s/TimestampDictionaryWriter.cpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

components/core/src/clp_s/TimestampPattern.cpp (1)

Pattern **/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

🔇 Additional comments (17)
components/core/src/clp_s/TimestampPattern.cpp (5)

7-7: LGTM: Required header for string_view support.

The addition of the <string_view> header is necessary and correctly placed in the include section.


75-75: LGTM: Efficient string_view usage for read-only operations.

The change to std::string_view const is appropriate here as the method only needs read access to the string data. This change can improve performance by avoiding unnecessary string copies.


93-93: LGTM: Consistent string_view usage.

The change maintains consistency with other method signatures and is appropriate for the read-only string operations performed.


310-310: LGTM: Appropriate use of string_view for pattern searching.

The change to std::string_view is well-suited for this search operation as it provides efficient read-only access to the string data.


346-346: LGTM: Efficient string handling for timestamp parsing.

The use of std::string_view here is particularly beneficial as it can improve performance in the numerous string comparison operations performed during timestamp parsing.

components/core/src/clp_s/ParsedMessage.hpp (2)

6-6: LGTM: Required header added

The addition of the string_view header is necessary for the new overloads.


38-40: LGTM: Proper string_view handling

The implementation correctly creates owned std::string objects from string_view parameters before storing them in containers. This is necessary since string_view doesn't own its data and the referenced string must outlive the view.

Also applies to: 63-65

components/core/src/clp_s/TimestampDictionaryWriter.hpp (2)

4-4: LGTM: Required headers added

The addition of cstdint and string_view headers is appropriate for the types used in the class.

Also applies to: 8-8


52-54: LGTM: Consistent string_view usage

The method signatures have been updated to use string_view consistently across all overloads. This change aligns with the PR objective of optimizing string handling.

Also applies to: 64-64, 66-66

components/core/src/clp_s/TimestampEntry.hpp (2)

6-6: LGTM: Required header added

The addition of the string_view header is necessary for the constructor parameter.


Line range hint 47-53: LGTM: Proper string ownership handling

The constructor correctly initializes m_key_name as a std::string from the string_view parameter, ensuring proper ownership of the string data.

components/core/src/clp_s/TimestampDictionaryWriter.cpp (3)

3-5: LGTM! Appropriate header includes added.

The addition of <cstdint> and <string_view> headers is correct and necessary for the refactoring.


Line range hint 93-106: LGTM! Consistent parameter type usage.

The function correctly uses string_view const for the key parameter while maintaining the original logic for double timestamp handling.


Line range hint 108-121: LGTM! Consistent parameter type usage.

The function correctly uses string_view const for the key parameter while maintaining the original logic for int64_t timestamp handling.

components/core/src/clp_s/TimestampPattern.hpp (2)

Line range hint 9-91: LGTM! Appropriate header inclusion and parameter type update.

The addition of <string_view> header and the parameter type change to string_view const in search_known_ts_patterns is consistent with the refactoring objective.


Line range hint 125-129: LGTM! Consistent parameter type update.

The parameter type change to string_view const in parse_timestamp is consistent with the refactoring objective.

components/core/src/clp_s/search/StringLiteral.hpp (1)

7-7: Verify the Utils.hpp header inclusion

The addition of this header appears correct for accessing StringUtils::has_unescaped_wildcards, but let's verify its existence and accessibility.

✅ Verification successful

Include directive is correct and properly accessible

The Utils.hpp header exists at the expected relative path (../Utils.hpp from components/core/src/clp_s/search/StringLiteral.hpp), and it contains the required has_unescaped_wildcards function within the StringUtils namespace. The inclusion is appropriate for the refactoring changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and content of Utils.hpp
# Expected: Find the header file and confirm it contains the required function

# Check if the file exists
fd -t f "Utils.hpp" -x echo "Found: {}"

# Verify the function exists in the file
ast-grep --pattern 'namespace StringUtils {
  $$$
  bool has_unescaped_wildcards($_) {
    $$$
  }
  $$$
}'

Length of output: 389


Script:

#!/bin/bash
# Let's check the content of the Utils.hpp file in the clp_s directory since that's the one referenced in the relative path
cat ./components/core/src/clp_s/Utils.hpp

# Also check for any references to has_unescaped_wildcards in this file
rg "has_unescaped_wildcards" ./components/core/src/clp_s/Utils.hpp

Length of output: 10127

@@ -69,18 +70,8 @@ class StringLiteral : public Literal {
}

// If '?' and '*' are not escaped, we add LiteralType::ClpStringT to m_string_type
Copy link
Contributor

@haiqi96 haiqi96 Dec 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am personally fine with having this comment since I love reading, lol
But since we were talking about comments, what's your opinion? @kirkrodrigues

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I read the code, I get the same message as the comment (without a loss of speed), so I would drop this comment. Also, this is a minor in this case, but it's possible one day we introduce a new wildcard, making this comment inaccurate (and it's hard to reliably track down these types of inaccurate comments).

@@ -124,7 +124,7 @@ class ArchiveWriter {
epochtime_t ingest_timestamp_entry(
std::string const& key,
int32_t node_id,
std::string const& timestamp,
std::string_view const timestamp,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for string_view, I believe we don't need the extra const at end.
@LinZhihao-723 what's our standard?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True, we don't need to add const since the view is immutable

gibber9809 and others added 2 commits December 13, 2024 15:30
Co-authored-by: haiqi96 <14502009+haiqi96@users.noreply.github.com>
@gibber9809 gibber9809 changed the title chore(clp-s): Refactor several components to use const string_view. chore(clp-s): Refactor several components to use string_view. Dec 13, 2024
@gibber9809 gibber9809 requested a review from haiqi96 December 13, 2024 20:42
@@ -71,7 +73,7 @@ append_padded_value_notz(int value, char padding_character, size_t max_length, s
* @return true if conversion succeeds, false otherwise
*/
static bool convert_string_to_number(
string const& str,
std::string_view str,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry I missed this one.
nit: this file has been using "using std::string". how about we do the same for std::string_view, so we get rid of the std:: and it's consistent with the rest of file?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking a bit more at the file it looks like its already a bit inconsistent with using std:: even for things it declared as using. I'll go through and remove all of the using to make things consistent.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually on second though it mostly isn't using std::, so I'll just change the few other exceptions to be consistent.

@haiqi96
Copy link
Contributor

haiqi96 commented Dec 13, 2024

Following https://github.com/commitizen/conventional-commit-types/blob/master/index.json. chore refers to "Other changes that don't modify src or test files".

For this PR, I believe we should use "refactor"

@gibber9809 gibber9809 changed the title chore(clp-s): Refactor several components to use string_view. refactor(clp-s): Refactor several components to use string_view. Dec 13, 2024
@gibber9809 gibber9809 requested a review from haiqi96 December 13, 2024 21:32
@haiqi96
Copy link
Contributor

haiqi96 commented Dec 13, 2024

Looks good to me.
@LinZhihao-723 can you do a final pass?

@haiqi96
Copy link
Contributor

haiqi96 commented Dec 13, 2024

@coderabbitai
Can't think of a better title for the PR, any suggestions?

Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

Tip

For best results, initiate chat on the files or code changes.

@haiqi96: Here are some suggestions for the PR title:

  • refactor(clp-s): Replace std::string const& with std::string_view to improve performance
  • refactor(clp-s): Optimize string handling by adopting std::string_view
  • refactor(clp-s): Enhance performance by refactoring to std::string_view
  • refactor(clp-s): Eliminate unnecessary string copies using std::string_view

These titles highlight the core changes and the performance benefits of using std::string_view. Let me know if any of these work for you.

haiqi96
haiqi96 previously approved these changes Dec 13, 2024
@@ -47,9 +49,9 @@ class TimestampDictionaryWriter {
* @return the epoch time corresponding to the string timestamp
*/
epochtime_t ingest_entry(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not mandatory, but since it seems like a small change, do you want to change the callers in ArchiveWriter to also use string_views?

Copy link
Contributor

@haiqi96 haiqi96 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new change looks good to me.

Nit: we can add #include to archiveWriter.hpp, but I feel it is not necessarily relevant to this PR.

Copy link
Member

@kirkrodrigues kirkrodrigues left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the PR title, how about:

refactor(clp-s): Replace instances of `std::string const&` with `std::string_view` where it would remove unnecessary conversions to and from `std::string`.

@kirkrodrigues
Copy link
Member

macOS build failure is unrelated to this PR and should be resolved by #636.

@gibber9809 gibber9809 changed the title refactor(clp-s): Refactor several components to use string_view. refactor(clp-s): Replace instances of std::string const& with std::string_view where it would remove unnecessary conversions to and from std::string. Dec 16, 2024
@gibber9809 gibber9809 merged commit 9b1a04b into y-scope:main Dec 16, 2024
17 of 21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants