Skip to content

Conversation

aljo242
Copy link

@aljo242 aljo242 commented May 27, 2025

add better encode and decode testing

add proper godoc

simplify the Encode32BytesHash and Encode32BytesHashSlice fns

Summary by CodeRabbit

  • New Features
    • Added support for encoding fixed-length 32-byte hashes, with validation and new helper functions.
  • Bug Fixes
    • Improved safety checks when decoding byte slices to prevent overflows and out-of-bounds errors.
  • Tests
    • Enhanced test coverage for encoding and decoding functions, including new tests for 32-byte hash encoding and varint handling.
    • Simplified and clarified existing test cases for better reliability.

Copy link

coderabbitai bot commented May 27, 2025

Walkthrough

The changes introduce new helper functions and constants for handling 32-byte hash encoding, add stricter validation and overflow checks in byte decoding, and refactor encoding logic for clarity and reuse. The test suite is updated to use an external test package, adds comprehensive tests for encoding/decoding functions, and simplifies some existing test cases.

Changes

File(s) Change Summary
internal/encoding/encoding.go Added hash32ByteLength constant, new writeBytes helper, stricter DecodeBytes validation, new Encode32BytesHash and Encode32BytesHashSlice functions, code refactoring, and improved comments.
internal/encoding/encoding_test.go Switched to black-box testing, added explicit package import, removed redundant DecodeBytes test cases, and added new tests for 32-byte hash encoding, byte slice encoding, and varint encoding/decoding.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Encoding

    Caller->>Encoding: Encode32BytesHash(w, bz)
    Encoding->>Encoding: Validate bz length == 32
    alt Valid
        Encoding->>w: Write length prefix (32)
        Encoding->>w: Write 32-byte hash
        Encoding-->>Caller: nil error
    else Invalid
        Encoding-->>Caller: error
    end
Loading
sequenceDiagram
    participant Caller
    participant Encoding

    Caller->>Encoding: DecodeBytes(bz)
    Encoding->>Encoding: Decode length prefix
    Encoding->>Encoding: Check for overflow and bounds
    alt Valid
        Encoding-->>Caller: Decoded bytes, bytes read, nil error
    else Invalid
        Encoding-->>Caller: error
    end
Loading

Suggested reviewers

  • julienrbrt

Poem

🐇
In the warren where bytes align,
New hash helpers now entwine.
With checks for bounds and overflow,
The tests all run, the green lights glow.
Thirty-two bytes, encoded right—
The rabbit hops with pure delight!

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.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 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 f05dd3a and 866bc1c.

📒 Files selected for processing (2)
  • internal/encoding/encoding.go (6 hunks)
  • internal/encoding/encoding_test.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
internal/encoding/encoding_test.go (1)
internal/encoding/encoding.go (11)
  • DecodeBytes (43-62)
  • Encode32BytesHash (100-108)
  • Encode32BytesHashSlice (111-119)
  • EncodeBytesSlice (122-131)
  • EncodeBytesSize (134-136)
  • EncodeUvarint (139-145)
  • EncodeUvarintSize (148-153)
  • EncodeVarint (156-165)
  • EncodeVarintSize (187-193)
  • DecodeUvarint (65-77)
  • DecodeVarint (80-89)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (go)
  • GitHub Check: Benchmarks
  • GitHub Check: Test
🔇 Additional comments (21)
internal/encoding/encoding_test.go (12)

1-1: Good practice: External test package

Changing the package name to encoding_test follows Go testing best practices by testing the package from an external perspective, ensuring the public API is properly exposed.


9-9: Necessary import for external testing

The explicit import of the internal encoding package is required due to the package name change and enables proper external testing.


27-29: Comprehensive overflow test cases

The test cases properly cover important edge cases for overflow conditions, including MaxInt32, MaxInt32+10, and MaxUint64, which are critical for validating the overflow protection added to DecodeBytes.


39-39: Correct function call with package prefix

The explicit package prefix encoding.DecodeBytes is necessary and correct given the external test package setup.


45-45: Appropriate nolint comment for test code

The nolint:gosec comment is appropriate here since this is test code where the type conversion from uint64 to int is intentional and safe within the test context.


57-95: Comprehensive test coverage for Encode32BytesHash

The test function provides excellent coverage with:

  • Valid 32-byte hash case with expected output verification
  • Error cases for both too short (31 bytes) and too long (33 bytes) inputs
  • Clear test structure with descriptive names

The test correctly validates both successful encoding and proper error handling for invalid input lengths.


97-134: Thorough testing of Encode32BytesHashSlice

This test mirrors the Encode32BytesHash test with appropriate coverage for the slice-returning variant. The test cases are well-structured and verify:

  • Correct encoding output for valid 32-byte input
  • Proper error handling for invalid lengths (both shorter and longer)
  • Different test data patterns to ensure robustness

136-143: Validates size calculation accuracy

This test ensures that EncodeBytesSize correctly predicts the actual encoded size returned by EncodeBytesSlice, which is important for buffer allocation and validation.


145-153: Verifies uvarint size calculation

The test validates that EncodeUvarintSize accurately predicts the bytes written by EncodeUvarint, ensuring consistency between size calculation and actual encoding.


155-163: Tests varint size calculation

Similar to the uvarint test, this ensures EncodeVarintSize correctly predicts the encoded size for signed integers, including negative values.


165-172: Basic decode uvarint functionality test

The test verifies round-trip encoding/decoding for uvarint values, ensuring the decode function works correctly with standard binary encoding.


174-181: Basic decode varint functionality test

This test validates round-trip encoding/decoding for signed varint values, including negative numbers, ensuring the decode function handles signed integers correctly.

internal/encoding/encoding.go (9)

13-13: Well-defined constant for hash length

The constant hash32ByteLength = 32 is appropriately named and provides clear documentation of the expected hash size, improving code readability and maintainability.


15-15: Improved documentation for sync.Pools

The added comments clearly explain the purpose of each pool, improving code documentation and making the optimization strategy explicit.

Also applies to: 22-22, 29-29


36-39: Simple and effective helper function

The writeBytes helper function provides a clean abstraction for writing byte slices, improving code consistency and readability throughout the package.


41-42: Enhanced documentation and overflow protection

The improved comments explain the function behavior and the explicit overflow check comments make the safety measures clear. This enhances code maintainability and security.

Also applies to: 49-49, 54-54


64-64: Clear function documentation

The added godoc comments improve the API documentation by clearly describing what each decode function does.

Also applies to: 79-79


93-93: Cleaner EncodeBytes implementation

The refactoring removes unnecessary intermediate variable assignment and uses the new writeBytes helper, making the code more concise and consistent.

Also applies to: 96-96


99-108: Well-implemented Encode32BytesHash function

The function correctly:

  • Validates input length against the constant
  • Provides clear error messages with expected vs actual lengths
  • Uses the writeBytes helper for consistency
  • Implements the fixed-length encoding as documented

The hard-coded single-byte length prefix (32) is appropriate for this specialized function.


110-119: Efficient slice-based hash encoding

The Encode32BytesHashSlice function provides an efficient implementation by:

  • Pre-allocating the exact output size (1+hash32ByteLength)
  • Using direct byte assignment for the length prefix
  • Using copy for the hash data
  • Maintaining the same validation as the writer-based version

This approach avoids intermediate buffer allocations.


142-142: Simplified return value handling

The direct assignment of the Write return value to err is cleaner than using the blank identifier, as the number of bytes written is not needed in these contexts.

Also applies to: 162-162

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@aljo242
Copy link
Author

aljo242 commented May 27, 2025

@Mergifyio backport release/v1.2.x

@aljo242
Copy link
Author

aljo242 commented May 27, 2025

@Mergifyio backport release/v1.3.x

Copy link
Contributor

mergify bot commented May 27, 2025

backport release/v1.2.x

🟠 Waiting for conditions to match

  • merged [📌 backport requirement]

Copy link
Contributor

mergify bot commented May 27, 2025

backport release/v1.3.x

🟠 Waiting for conditions to match

  • merged [📌 backport requirement]

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.

1 participant