Skip to content

fix: inefficient Vec<u8> to BytesMut conversion #6687

Merged
LesnyRumcajs merged 1 commit intomainfrom
hm/fix-insufficient-vec-to-bytes-mut
Mar 4, 2026
Merged

fix: inefficient Vec<u8> to BytesMut conversion #6687
LesnyRumcajs merged 1 commit intomainfrom
hm/fix-insufficient-vec-to-bytes-mut

Conversation

@hanabi1224
Copy link
Contributor

@hanabi1224 hanabi1224 commented Mar 4, 2026

Summary of changes

Vec<u8> cannot be directly converted to BytesMut, vec.into_iter().collect() should be less efficient than BytesMut::from(Bytes::from(vec))

https://docs.rs/bytes/latest/src/bytes/bytes_mut.rs.html#918

    // private

    // For now, use a `Vec` to manage the memory for us, but we may want to
    // change that in the future to some alternate allocator strategy.
    //
    // Thus, we don't expose an easy way to construct from a `Vec` since an
    // internal change could make a simple pattern (`BytesMut::from(vec)`)
    // suddenly a lot more expensive.
    #[inline]
    pub(crate) fn from_vec(vec: Vec<u8>) -> BytesMut {
        let mut vec = ManuallyDrop::new(vec);
        let ptr = vptr(vec.as_mut_ptr());
        let len = vec.len();
        let cap = vec.capacity();

        let original_capacity_repr = original_capacity_to_repr(cap);
        let data = (original_capacity_repr << ORIGINAL_CAPACITY_OFFSET) | KIND_VEC;

        BytesMut {
            ptr,
            len,
            cap,
            data: invalid_ptr(data),
        }
    }

Changes introduced in this pull request:

Reference issue to close (if applicable)

Closes

Other information and links

Change checklist

  • I have performed a self-review of my own code,
  • I have made corresponding changes to the documentation. All new code adheres to the team's documentation standards,
  • I have added tests that prove my fix is effective or that my feature works (if possible),
  • I have made sure the CHANGELOG is up-to-date. All user-facing changes should be reflected in this document.

Outside contributions

  • I have read and agree to the CONTRIBUTING document.
  • I have read and agree to the AI Policy document. I understand that failure to comply with the guidelines will lead to rejection of the pull request.

Summary by CodeRabbit

  • Refactor
    • Optimized internal memory representation in transaction data formatting processes to improve efficiency and resource usage.
    • Enhanced frame decoding operations with refined buffer management for better performance.
    • Improved type consistency across modules to strengthen code stability and maintainability across the codebase.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 4, 2026

Walkthrough

Type signatures in zstd decoding and Ethereum transaction formatting functions are updated from BytesMut to Bytes return types. All call sites and tests are adapted accordingly, with .into() conversions where necessary. No control flow changes or new functionality introduced.

Changes

Cohort / File(s) Summary
Zstd Frame Decoding
src/db/car/forest.rs
decode_zstd_single_frame helper returns Bytes instead of BytesMut; callers updated with .into() conversions for type compatibility.
Ethereum Transaction Formatting
src/eth/transaction.rs
Three public functions (format_u64, format_bigint, format_address) updated to return Bytes instead of BytesMut; call sites and tests refactored with slice() usage and type conversions.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • akaladarshi
  • LesnyRumcajs
🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title mentions 'inefficient Vec to BytesMut conversion' but the actual changes convert functions to return Bytes instead of BytesMut, which is the opposite direction and a different optimization strategy. Update the title to accurately reflect the main change: converting return types from BytesMut to Bytes in decode_zstd_single_frame and formatting functions (format_u64, format_bigint, format_address).
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch hm/fix-insufficient-vec-to-bytes-mut

Comment @coderabbitai help to get the list of available commands and usage tips.

@hanabi1224 hanabi1224 marked this pull request as ready for review March 4, 2026 08:30
@hanabi1224 hanabi1224 requested a review from a team as a code owner March 4, 2026 08:30
@hanabi1224 hanabi1224 requested review from LesnyRumcajs and akaladarshi and removed request for a team March 4, 2026 08:30
@hanabi1224 hanabi1224 changed the title fix: insufficient Vec<u8> to BytesMut conversion fix: inefficient Vec<u8> to BytesMut conversion Mar 4, 2026
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.

🧹 Nitpick comments (1)
src/eth/transaction.rs (1)

276-303: Add rustdoc on touched public formatting helpers.

Line 276, Line 290, and Line 302 are public APIs and should have concise /// docs describing zero/negative/None behavior.

As per coding guidelines Document all public functions and structs.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/eth/transaction.rs` around lines 276 - 303, Add concise rustdoc comments
to each public helper: document format_u64 to explain it returns a big-endian
minimal byte representation and returns an empty Bytes for zero; document
format_bigint to state it returns big-endian magnitude bytes for positive
values, returns an empty Bytes for zero, and errors for negative inputs (mention
the error via bail!); and document format_address to describe that it accepts
Option<EthAddress> and returns an empty Bytes when None and the address bytes
when Some. Place these /// comments immediately above the corresponding function
signatures (format_u64, format_bigint, format_address).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/eth/transaction.rs`:
- Around line 276-303: Add concise rustdoc comments to each public helper:
document format_u64 to explain it returns a big-endian minimal byte
representation and returns an empty Bytes for zero; document format_bigint to
state it returns big-endian magnitude bytes for positive values, returns an
empty Bytes for zero, and errors for negative inputs (mention the error via
bail!); and document format_address to describe that it accepts
Option<EthAddress> and returns an empty Bytes when None and the address bytes
when Some. Place these /// comments immediately above the corresponding function
signatures (format_u64, format_bigint, format_address).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c02029b6-614f-4100-a049-09fd1b88b935

📥 Commits

Reviewing files that changed from the base of the PR and between 4197ec9 and 8372b63.

📒 Files selected for processing (2)
  • src/db/car/forest.rs
  • src/eth/transaction.rs

@codecov
Copy link

codecov bot commented Mar 4, 2026

Codecov Report

❌ Patch coverage is 88.23529% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.52%. Comparing base (4197ec9) to head (8372b63).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/db/car/forest.rs 50.00% 0 Missing and 2 partials ⚠️
Additional details and impacted files
Files with missing lines Coverage Δ
src/eth/transaction.rs 86.67% <100.00%> (-0.04%) ⬇️
src/db/car/forest.rs 83.89% <50.00%> (ø)

... and 11 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 4197ec9...8372b63. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@LesnyRumcajs LesnyRumcajs added this pull request to the merge queue Mar 4, 2026
Merged via the queue into main with commit 0dea2f2 Mar 4, 2026
39 checks passed
@LesnyRumcajs LesnyRumcajs deleted the hm/fix-insufficient-vec-to-bytes-mut branch March 4, 2026 11:01
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