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

Feature: Random package #31

Merged
merged 6 commits into from
Nov 4, 2024
Merged

Conversation

guisithos
Copy link
Contributor

@guisithos guisithos commented Oct 31, 2024

Besides what was mentioned in issue #28, I took the liberty of also adding an option to handle slices with Pick() and Shuffle().

Example of use:

// Generate a secure random string (like for an API key)
key, err := rand.StringWithLength(32)
if err != nil {
    return err
}

// Randomly select a winner from a list
participants := []string{"Alice", "Bob", "Charlie"}
winner, err := rand.Pick(participants)

Summary by CodeRabbit

  • New Features

    • Introduced a package for generating random numbers and strings with various methods for number generation, string creation, element picking, and shuffling.
    • Added customizable options for string length and character sets.
  • Tests

    • Implemented a comprehensive suite of unit tests to ensure the correctness and reliability of random generation functionalities.

Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Walkthrough

The changes introduce a new package rand that provides functionalities for generating random numbers and strings. Key functions include generating random numbers, strings, and shuffling slices, along with error handling for various failure scenarios. A corresponding test file rand_test.go is added, containing unit tests for each function to ensure correctness and reliability.

Changes

File Change Summary
rand/rand.go Added a new package for random number and string generation with functions: Number, NumberInRange, String, StringWithLength, Pick, Shuffle, StringWithCharset, and constants for default charset and length.
rand/rand_test.go Introduced unit tests for the functions in the rand package, including tests for error handling and output validation. Added a helper function contains for slice checks.

Possibly related issues

  • [FEATURE] random package (rand) #28: This issue proposes a feature for a random generation package, which aligns with the newly introduced rand package functionalities for generating random numbers and strings.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 23de3ca and 37f6067.

📒 Files selected for processing (1)
  • rand/rand_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • rand/rand_test.go

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

🧹 Outside diff range and nitpick comments (5)
rand/rand.go (3)

43-43: Fix typos in function documentation.

There are typos in the documentation:

  • Line 43: "using the both default cons" should be "using both default constants"
  • Line 95: "using both defautl const" should be "using both default constants"

Also applies to: 95-95


60-60: Fix typo in error message.

"generaet" should be "generate"


1-116: Consider adding memory zeroing for sensitive applications.

While the implementation is secure using crypto/rand, for highly sensitive applications (e.g., generating cryptographic keys), consider adding memory zeroing after use.

You might want to add a note in the package documentation about this consideration, and potentially provide specialized functions for sensitive use cases that implement secure cleanup.

rand/rand_test.go (2)

28-70: Add edge cases to strengthen the test coverage.

The test structure is good, but consider adding these test cases:

  • Boundary values (when result equals min or max)
  • Integer overflow scenarios
  • Large ranges

Add these test cases to the test suite:

 tests := []struct {
     name    string
     min     int64
     max     int64
     wantErr bool
 }{
     // ... existing cases ...
+    {
+        name:    "success - large range",
+        min:     math.MinInt64,
+        max:     math.MaxInt64,
+        wantErr: false,
+    },
+    {
+        name:    "success - boundary test",
+        min:     -1,
+        max:     1,
+        wantErr: false,
+    },
 }

200-253: Add comprehensive charset test cases.

Consider adding these scenarios:

  1. Very long string generation
  2. Unicode character support
  3. Repeated characters in charset
  4. Single character charset

Add these test cases:

 tests := []struct {
     // ... existing cases ...
+    {
+        name:    "success - very long string",
+        length:  10000,
+        charset: "abc",
+        wantLen: 10000,
+        wantErr: false,
+    },
+    {
+        name:    "success - unicode charset",
+        length:  10,
+        charset: "🎲🎮🎯",
+        wantLen: 10,
+        wantErr: false,
+    },
+    {
+        name:    "success - repeated charset chars",
+        length:  10,
+        charset: "aaa",
+        wantLen: 10,
+        wantErr: false,
+    },
+    {
+        name:    "success - single char charset",
+        length:  10,
+        charset: "x",
+        wantLen: 10,
+        wantErr: false,
+    },
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5825eed and c12c656.

📒 Files selected for processing (2)
  • rand/rand.go (1 hunks)
  • rand/rand_test.go (1 hunks)
🔇 Additional comments (2)
rand/rand_test.go (2)

1-7: LGTM!

Package declaration and imports are appropriate for the test file.


94-134: LGTM!

TestStringWithLength has good coverage of edge cases and proper error handling.

rand/rand.go Outdated Show resolved Hide resolved
rand/rand.go Outdated Show resolved Hide resolved
rand/rand.go Outdated Show resolved Hide resolved
rand/rand_test.go Show resolved Hide resolved
rand/rand_test.go Outdated Show resolved Hide resolved
rand/rand_test.go Outdated Show resolved Hide resolved
rand/rand_test.go Show resolved Hide resolved
rand/rand_test.go Outdated Show resolved Hide resolved
kashifkhan0771 and others added 2 commits November 1, 2024 11:55
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Kashif Khan <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Kashif Khan <[email protected]>
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: 7

🧹 Outside diff range and nitpick comments (1)
rand/rand.go (1)

18-24: Consider the range of values returned by Number().

The Number() function returns values from 0 to math.MaxInt64 - 1. If the intention is to include math.MaxInt64, consider adjusting the implementation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c12c656 and dd9280d.

📒 Files selected for processing (1)
  • rand/rand.go (1 hunks)
🔇 Additional comments (3)
rand/rand.go (3)

75-87: Ensure consistent handling of empty slices in Pick() and Shuffle().

While Pick() returns an error when the slice is empty, Shuffle() did not handle this case. With the updated check, both functions now consistently handle empty slices.


26-47: Great job addressing modulo bias in NumberInRange().

Implementing rejection sampling to eliminate modulo bias enhances the uniformity of the random number generation.


54-122: Reduce code duplication between StringWithLength() and StringWithCharset().

Both functions share similar logic. Consider refactoring StringWithLength() to call StringWithCharset() with the default charset.

This suggestion aligns with a previous review comment and is still applicable.

rand/rand.go Outdated Show resolved Hide resolved
rand/rand.go Outdated Show resolved Hide resolved
rand/rand.go Outdated Show resolved Hide resolved
rand/rand.go Outdated Show resolved Hide resolved
rand/rand.go Outdated Show resolved Hide resolved
rand/rand.go Show resolved Hide resolved
rand/rand.go Outdated Show resolved Hide resolved
Copy link
Owner

@kashifkhan0771 kashifkhan0771 left a comment

Choose a reason for hiding this comment

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

I just took a quick look. Overall looks ok. I resolved/committed some suggestions from coderabbitai. Please check other comments from bot and If they can be resolved.

I'll do a more detail review later on. Thank you for your contribution!

}

// Pick returns a random element from the provided slice
func Pick[T any](slice []T) (T, error) {
Copy link
Owner

Choose a reason for hiding this comment

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

Thanks for adding these additional Functions ❤️

@kashifkhan0771 kashifkhan0771 linked an issue Nov 1, 2024 that may be closed by this pull request
rand/rand.go Show resolved Hide resolved
rand/rand.go Show resolved Hide resolved
Signed-off-by: Guilherme Thomas <[email protected]>
Signed-off-by: Guilherme Thomas <[email protected]>
@guisithos
Copy link
Contributor Author

I followed coderabbitai advices, did some changes and updated my files.

rand/rand_test.go Show resolved Hide resolved
Signed-off-by: Guilherme Thomas <[email protected]>
Copy link
Owner

@kashifkhan0771 kashifkhan0771 left a comment

Choose a reason for hiding this comment

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

LGTM! Thanks for the contribution @guisithos

@kashifkhan0771 kashifkhan0771 merged commit 987c698 into kashifkhan0771:main Nov 4, 2024
1 check 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.

[FEATURE] random package (rand)
3 participants