iavl
iavl copied to clipboard
chore: cleanup internal encoding logic
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.
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
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
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 f05dd3a6fc8e345e18bc009834952b04f24d1826 and 866bc1cce26c5cb97ac422bf702bae88056f74b5.
π 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 packageChanging the package name to
encoding_testfollows 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 testingThe 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 casesThe test cases properly cover important edge cases for overflow conditions, including
MaxInt32,MaxInt32+10, andMaxUint64, which are critical for validating the overflow protection added toDecodeBytes.
39-39: Correct function call with package prefixThe explicit package prefix
encoding.DecodeBytesis necessary and correct given the external test package setup.
45-45: Appropriate nolint comment for test codeThe
nolint:goseccomment is appropriate here since this is test code where the type conversion fromuint64tointis intentional and safe within the test context.
57-95: Comprehensive test coverage for Encode32BytesHashThe 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 Encode32BytesHashSliceThis test mirrors the
Encode32BytesHashtest 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 accuracyThis test ensures that
EncodeBytesSizecorrectly predicts the actual encoded size returned byEncodeBytesSlice, which is important for buffer allocation and validation.
145-153: Verifies uvarint size calculationThe test validates that
EncodeUvarintSizeaccurately predicts the bytes written byEncodeUvarint, ensuring consistency between size calculation and actual encoding.
155-163: Tests varint size calculationSimilar to the uvarint test, this ensures
EncodeVarintSizecorrectly predicts the encoded size for signed integers, including negative values.
165-172: Basic decode uvarint functionality testThe 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 testThis 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 lengthThe constant
hash32ByteLength = 32is appropriately named and provides clear documentation of the expected hash size, improving code readability and maintainability.
15-15: Improved documentation for sync.PoolsThe 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 functionThe
writeByteshelper function provides a clean abstraction for writing byte slices, improving code consistency and readability throughout the package.
41-42: Enhanced documentation and overflow protectionThe 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 documentationThe added godoc comments improve the API documentation by clearly describing what each decode function does.
Also applies to: 79-79
93-93: Cleaner EncodeBytes implementationThe refactoring removes unnecessary intermediate variable assignment and uses the new
writeByteshelper, making the code more concise and consistent.Also applies to: 96-96
99-108: Well-implemented Encode32BytesHash functionThe function correctly:
- Validates input length against the constant
- Provides clear error messages with expected vs actual lengths
- Uses the
writeByteshelper 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 encodingThe
Encode32BytesHashSlicefunction provides an efficient implementation by:
- Pre-allocating the exact output size (
1+hash32ByteLength)- Using direct byte assignment for the length prefix
- Using
copyfor the hash data- Maintaining the same validation as the writer-based version
This approach avoids intermediate buffer allocations.
142-142: Simplified return value handlingThe direct assignment of the
Writereturn value toerris 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.
πͺ§ 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
@coderabbitaiin a new review comment at the desired location with your query. Examples:@coderabbitai explain this code block.@coderabbitai modularize this function.
- PR comments: Tag
@coderabbitaiin 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 pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger an incremental review. This is useful when automatic reviews are disabled for the repository.@coderabbitai full reviewto do a full review from scratch and review all the files again.@coderabbitai summaryto regenerate the summary of the PR.@coderabbitai generate docstringsto generate docstrings for this PR.@coderabbitai generate sequence diagramto generate a sequence diagram of the changes in this PR.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai configurationto show the current CodeRabbit configuration for the repository.@coderabbitai helpto get help.
Other keywords and placeholders
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere in the PR title to generate the title automatically.
CodeRabbit Configuration File (.coderabbit.yaml)
- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile 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.
@Mergifyio backport release/v1.2.x
@Mergifyio backport release/v1.3.x
backport release/v1.2.x
π Waiting for conditions to match
- [ ]
merged[π backport requirement]
backport release/v1.3.x
π Waiting for conditions to match
- [ ]
merged[π backport requirement]