Skip to content

refactor(bytes): clarify shared alignment assertions - #841

Merged
Darksonn merged 1 commit into
tokio-rs:masterfrom
my-contributes:master
Jul 14, 2026
Merged

refactor(bytes): clarify shared alignment assertions#841
Darksonn merged 1 commit into
tokio-rs:masterfrom
my-contributes:master

Conversation

@bestgopher

Copy link
Copy Markdown
Contributor

Summary

This PR replaces the array-underflow-based compile-time checks:

const _: [(); 0 - mem::align_of::<Shared>() % 2] = [];

with explicit const assertions:

  const _: () = {
      assert!(
          mem::align_of::<Shared>() % 2 == 0,
          "Shared alignment must be divisible by 2 for pointer tagging"
      );
  };

This change is neither a bug fix nor a new feature. It preserves the
existing behavior and alignment invariant, while expressing that invariant
in a more direct and readable form.

Motivation

The current array-length expression works, but it is not particularly
beginner-friendly. A reader must work out that an odd alignment makes
mem::align_of::() % 2 equal to 1, which then causes 0 - 1 to
fail during const evaluation.

Using assert! states the requirement directly and also provides a clearer
diagnostic if the invariant is ever violated.

MSRV compatibility

Using assert! in a const context is supported starting with Rust 1.57,
as part of the stabilization of [panic! in const
contexts (https://blog.rust-lang.org/2021/12/02/Rust-1.57.0/#panic-in-const-contexts).

The bytes crate already declares Rust 1.57 as its
MSRV (https://github.com/tokio-rs/bytes/blob/master/Cargo.toml#L9), so this
change does not raise the minimum supported Rust version.

Validation

  • cargo fmt --all -- --check
  • cargo check
  • cargo check --no-default-features
  • cargo test

This is intentionally a small readability-only change. If the maintainers
consider it unnecessary or prefer the existing idiom, please feel free to
close this PR.

Replace array-underflow checks with const assert expressions.
Add diagnostics that explain the pointer-tagging alignment invariant.

Signed-off-by: bestgopher <84328409@qq.com>

@Darksonn Darksonn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks.

@Darksonn
Darksonn merged commit 002df10 into tokio-rs:master Jul 14, 2026
18 checks 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.

2 participants