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

Remove expsensive regex for hex parsing #116

Merged
merged 1 commit into from
Jan 8, 2025

Conversation

maerki
Copy link
Contributor

@maerki maerki commented Jan 7, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved hex color string parsing and validation
    • Enhanced handling of hex color string input with more robust checks
    • Updated hex color initialization to support a wider range of hex string formats

Copy link

coderabbitai bot commented Jan 7, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 SwiftLint (0.57.0)
Sources/UBUserInterface/UIColor/UIColor+HEX.swift

[
{
"character" : 16,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 98,
"reason" : "Variable name 'ub_hexString' should only contain alphanumeric and other allowed characters",
"rule_id" : "identifier_name",
"severity" : "Error",
"type" : "Identifier Name"
},
{
"character" : 13,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 99,
"reason" : "Variable name 'r' should be between 3 and 40 characters long",
"rule_id" : "identifier_name",
"severity" : "Error",
"type" : "Identifier Name"
},
{
"character" : 13,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 100,
"reason" : "Variable name 'g' should be between 3 and 40 characters long",
"rule_id" : "identifier_name",
"severity" : "Error",
"type" : "Identifier Name"
},
{
"character" : 13,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 101,
"reason" : "Variable name 'b' should be between 3 and 40 characters long",
"rule_id" : "identifier_name",
"severity" : "Error",
"type" : "Identifier Name"
},
{
"character" : 13,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 102,
"reason" : "Variable name 'a' should be between 3 and 40 characters long",
"rule_id" : "identifier_name",
"severity" : "Error",
"type" : "Identifier Name"
},
{
"character" : null,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 55,
"reason" : "Line should be 120 characters or less; currently it has 191 characters",
"rule_id" : "line_length",
"severity" : "Warning",
"type" : "Line Length"
},
{
"character" : null,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 93,
"reason" : "Line should be 120 characters or less; currently it has 121 characters",
"rule_id" : "line_length",
"severity" : "Warning",
"type" : "Line Length"
},
{
"character" : 1,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 10,
"reason" : "A doc comment should be attached to a declaration",
"rule_id" : "orphaned_doc_comment",
"severity" : "Warning",
"type" : "Orphaned Doc Comment"
},
{
"character" : 13,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 78,
"reason" : "Case statements should vertically aligned with their closing brace",
"rule_id" : "switch_case_alignment",
"severity" : "Warning",
"type" : "Switch and Case Statement Alignment"
},
{
"character" : 13,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 80,
"reason" : "Case statements should vertically aligned with their closing brace",
"rule_id" : "switch_case_alignment",
"severity" : "Warning",
"type" : "Switch and Case Statement Alignment"
},
{
"character" : 13,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 82,
"reason" : "Case statements should vertically aligned with their closing brace",
"rule_id" : "switch_case_alignment",
"severity" : "Warning",
"type" : "Switch and Case Statement Alignment"
},
{
"character" : 13,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 84,
"reason" : "Case statements should vertically aligned with their closing brace",
"rule_id" : "switch_case_alignment",
"severity" : "Warning",
"type" : "Switch and Case Statement Alignment"
},
{
"character" : 13,
"file" : "/Sources/UBUserInterface/UIColor/UIColor+HEX.swift",
"line" : 86,
"reason" : "Case statements should vertically aligned with their closing brace",
"rule_id" : "switch_case_alignment",
"severity" : "Warning",
"type" : "Switch and Case Statement Alignment"
}
]

Walkthrough

The pull request modifies the UIColor+HEX.swift file, specifically updating the hex string initialization method for UIColor. The changes enhance the hex string parsing logic by improving input validation, removing regex-based checks, and expanding support for hex value representation. The method now handles hex strings with more robust length and character validation, supporting 3, 4, 6, and 8 character formats while allowing optional '#' prefix removal.

Changes

File Change Summary
Sources/UBUserInterface/UIColor/UIColor+HEX.swift Updated ub_hexString initializer to:
- Trim whitespace and newline characters
- Remove regex validation
- Add length and hex digit validation
- Change hexValue type from UInt32 to UInt64
- Simplify hex string parsing logic

Poem

🎨 A Rabbit's Hex Color Tale 🐰

With whiskers twitching, code so bright,
Hex strings now parse with pure delight!
No regex maze, just simple might,
From three to eight, colors take flight,
A rainbow coded, pixel-perfect sight! 🌈


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

sonarqubecloud bot commented Jan 7, 2025

Copy link

@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: 1

🧹 Nitpick comments (1)
Sources/UBUserInterface/UIColor/UIColor+HEX.swift (1)

66-69: Consider adding more specific validation error handling.

The new validation logic is clean and efficient. However, consider separating the length and character validation to provide more specific error feedback during debugging.

-        guard [3, 4, 6, 8].contains(hexString.count),
-              hexString.allSatisfy({ $0.isHexDigit }) else {
+        guard [3, 4, 6, 8].contains(hexString.count) else {
+            return nil // Invalid hex string length
+        }
+        guard hexString.allSatisfy({ $0.isHexDigit }) else {
             return nil
+            return nil // Invalid hex characters
         }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9767a49 and 7b387fd.

📒 Files selected for processing (1)
  • Sources/UBUserInterface/UIColor/UIColor+HEX.swift (2 hunks)
🔇 Additional comments (3)
Sources/UBUserInterface/UIColor/UIColor+HEX.swift (3)

61-61: LGTM! Improved whitespace handling.

Using .whitespacesAndNewlines instead of just .whitespaces makes the method more robust by handling additional whitespace characters.


63-64: LGTM! Efficient '#' prefix handling.

The new implementation using hasPrefix and dropFirst is more performant than the previous regex-based approach.


72-74: LGTM! Improved hex value parsing.

Using UInt64 with Scanner.scanHexInt64 is more robust and safer against potential overflow compared to the previous implementation.

Comment on lines +83 to +87
self.init(hex6: UInt32(hexValue))
case 8:
self.init(hex8: hexValue)
self.init(hex8: UInt32(hexValue))
default:
fatalError("Should not be able to get other then 3-4-6-8 hex. Check regex")
fatalError("Unexpected hex string length. This should not occur.")
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider replacing fatalError with nil return.

While the validation ensures this case should never occur, using fatalError in an initializer might be too aggressive. Consider returning nil instead to maintain the failable initializer pattern.

             case 8:
                 self.init(hex8: UInt32(hexValue))
             default:
-                fatalError("Unexpected hex string length. This should not occur.")
+                return nil // This case is prevented by the guard statement above
         }

Committable suggestion skipped: line range outside the PR's diff.

@maerki maerki merged commit 632555a into main Jan 8, 2025
3 of 5 checks passed
@maerki maerki deleted the feature/hex-parsing-improvement branch January 8, 2025 07:40
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.

2 participants