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

chore(primitives): consolidated isValidHex usage #2031

Closed
wants to merge 4 commits into from

Conversation

abi87
Copy link
Collaborator

@abi87 abi87 commented Oct 1, 2024

Conslidated isValidHex usage via a generic function, instead of duplicating logic

Summary by CodeRabbit

  • New Features

    • Enhanced validation for hexadecimal strings, supporting both byte arrays and strings.
    • Streamlined error handling for formatting and validating hex inputs.
  • Bug Fixes

    • Improved clarity and conciseness in error checking for hex string validation.
  • Refactor

    • Consolidated validation logic into fewer functions for better maintainability and readability.

@abi87 abi87 self-assigned this Oct 1, 2024
Copy link
Contributor

coderabbitai bot commented Oct 1, 2024

Walkthrough

The pull request introduces significant changes to the hex package, specifically in the format.go and string.go files. It refactors the validation and formatting functions for hexadecimal strings, enhancing error handling and type management. The isValidHex function is updated to support both []byte and string types, while related functions are streamlined to improve code clarity and maintainability.

Changes

File Path Change Summary
mod/primitives/pkg/encoding/hex/format.go Refactored formatAndValidateText and formatAndValidateNumber for improved error handling and validation logic. Updated function signatures.
mod/primitives/pkg/encoding/hex/string.go Updated isValidHex to accept generic types, refactored NewStringStrict, and modified UnmarshalText for consistency in hex string validation.

Possibly related PRs

Suggested reviewers

  • nidhi-singh02
  • ocnc
  • itsdevbear

Poem

In the land of hex where numbers play,
A rabbit hops with joy today.
With functions sleek and errors few,
The code now shines, all fresh and new!
So let us dance and celebrate,
For cleaner code is truly great! 🐇✨


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 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

codecov bot commented Oct 1, 2024

Codecov Report

Attention: Patch coverage is 76.47059% with 4 lines in your changes missing coverage. Please review.

Project coverage is 22.42%. Comparing base (5bdacfc) to head (9710e4d).
Report is 13 commits behind head on main.

Files with missing lines Patch % Lines
mod/primitives/pkg/encoding/hex/format.go 69.23% 3 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2031      +/-   ##
==========================================
- Coverage   22.42%   22.42%   -0.01%     
==========================================
  Files         358      358              
  Lines       16012    16007       -5     
  Branches       12       12              
==========================================
- Hits         3591     3589       -2     
+ Misses      12272    12271       -1     
+ Partials      149      147       -2     
Files with missing lines Coverage Δ
mod/primitives/pkg/encoding/hex/string.go 83.49% <100.00%> (-0.47%) ⬇️
mod/primitives/pkg/encoding/hex/format.go 65.95% <69.23%> (+4.73%) ⬆️

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

🧹 Outside diff range comments (2)
mod/primitives/pkg/encoding/hex/string.go (2)

Line range hint 58-65: LGTM! Consider adding a hex character validation.

The updated isValidHex function with generic type parameter is a good improvement. It enhances code reusability and type safety by handling both []byte and string types.

Consider adding a check for valid hexadecimal characters after the prefix. This would make the function more robust:

func isValidHex[T []byte | string](str T) error {
	if len(str) == 0 {
		return ErrEmptyString
	} else if !has0xPrefix(str) {
		return ErrMissingPrefix
	}
	for _, c := range str[2:] {
		if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
			return errors.Wrapf(ErrInvalidString, "invalid hex character: %c", c)
		}
	}
	return nil
}

This addition ensures that all characters after the "0x" prefix are valid hexadecimal digits.


Line range hint 32-41: LGTM! Consider using NewStringStrict for consistency.

The updated UnmarshalText method correctly uses the new isValidHex function for validation, which ensures consistency across the package. The error handling is appropriate and provides context.

For even better consistency, consider using NewStringStrict instead of directly assigning the validated string:

func (s *String) UnmarshalText(text []byte) error {
	str, err := NewStringStrict(text)
	if err != nil {
		return err
	}
	*s = str
	return nil
}

This change would ensure that all string creation goes through the same path, potentially catching any future invariants that might be added to NewStringStrict.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 320256c and 95a43f7.

📒 Files selected for processing (2)
  • mod/primitives/pkg/encoding/hex/format.go (2 hunks)
  • mod/primitives/pkg/encoding/hex/string.go (2 hunks)
🔇 Additional comments (2)
mod/primitives/pkg/encoding/hex/string.go (1)

70-73: LGTM! Good simplification of NewStringStrict.

The refactored NewStringStrict function is a clear improvement. It leverages the new isValidHex function for validation, which simplifies the code and improves maintainability. The error handling is consistent with the rest of the codebase.

mod/primitives/pkg/encoding/hex/format.go (1)

61-71: ⚠️ Potential issue

Clarify handling of missing prefix and empty input

In the formatAndValidateText function, when isValidHex(input) returns ErrMissingPrefix, the function returns nil, nil with the comment // empty strings are allowed. This could conflate two cases:

  1. The input is empty.
  2. The input is non-empty but missing the 0x prefix.

Returning nil, nil in both cases might lead to unintended behavior. Consider explicitly checking for empty input and handling missing prefixes separately to avoid confusion and ensure correct processing.

To verify how different inputs are handled, you can run the following script:

Comment on lines 79 to 80
if err := isValidHex(input); err != nil {
return *new(T), err
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Simplify zero value initialization for generic type T

In the formatAndValidateNumber function, using *new(T) to obtain a zero value of type T can be less readable and may cause confusion. Consider using var zero T for clarity and to align with Go conventions.

Apply this diff to improve readability:

 if err := isValidHex(input); err != nil {
-	return *new(T), err
+	var zero T
+	return zero, err
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err := isValidHex(input); err != nil {
return *new(T), err
if err := isValidHex(input); err != nil {
var zero T
return zero, err

if len(input) == 0 {
switch err := isValidHex(input); {
case err == nil:
input = input[2:]
Copy link
Contributor

Choose a reason for hiding this comment

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

can leave a comment to bypass nilaway given that isValidHex assumes that the string must be prefixed by 0x, so we know its safe to strip if err was nil

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Niaway is definitely allucinating here. Not sure how to suppress the error, since //nolint:nilawa does not seem to work

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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Files that changed from the base of the PR and between 95a43f7 and 9710e4d.

📒 Files selected for processing (2)
  • mod/primitives/pkg/encoding/hex/format.go (2 hunks)
  • mod/primitives/pkg/encoding/hex/string.go (2 hunks)
🔇 Additional comments (3)
mod/primitives/pkg/encoding/hex/format.go (2)

61-71: Improved error handling enhances code clarity

Refactoring the error handling in formatAndValidateText using a switch statement with errors.Is improves readability and maintainability. The logic correctly handles valid hex inputs, empty strings, and returns appropriate errors for invalid cases.


79-81: Use of var zero T improves readability

Replacing *new(T) with var zero T for zero value initialization enhances readability and aligns with Go conventions.

mod/primitives/pkg/encoding/hex/string.go (1)

Line range hint 58-65: LGTM!

The isValidHex function has been correctly updated to accept a generic type parameter T []byte | string, allowing it to handle both []byte and string inputs seamlessly. The usage of len(str) and has0xPrefix(str) remains appropriate for both types.

if len(input)%2 != 0 {
return nil, ErrOddLength
}
return input, nil
}

// formatAndValidateNumber checks the input text for a hex number.
func formatAndValidateNumber[T []byte | string](input T) (T, error) {
// realistically, this shouldn't rarely error if called on
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Typographical error in comment

There's a typographical error in the comment which could cause confusion. Consider correcting it for clarity.

Suggested change:

-// realistically, this shouldn't rarely error if called on unwrapped hex.String
+// Realistically, this should rarely error if called on unwrapped hex.String
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// realistically, this shouldn't rarely error if called on
// Realistically, this should rarely error if called on unwrapped hex.String

Comment on lines +70 to +73
if err := isValidHex(s); err != nil {
return "", err
}
return String(str), nil
return String(s), nil
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix type conversion when returning String(s) with generic type T.

In NewStringStrict, s is of generic type T, which can be either []byte or string. Since String is defined as type String string, directly converting []byte to String without first converting it to string may lead to a compile-time error when s is a []byte. Ensure that s is converted to string before casting to String.

Apply the following diff to fix the type conversion:

 func NewStringStrict[T []byte | string](s T) (String, error) {
 	if err := isValidHex(s); err != nil {
 		return "", err
 	}
-	return String(s), nil
+	return String(string(s)), nil
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err := isValidHex(s); err != nil {
return "", err
}
return String(str), nil
return String(s), nil
if err := isValidHex(s); err != nil {
return "", err
}
return String(string(s)), nil

@abi87
Copy link
Collaborator Author

abi87 commented Oct 7, 2024

Replaced by #2048

@abi87 abi87 closed this Oct 7, 2024
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