rust-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Rust — Comprehensive Review

Rust — 全方位代码审查

Four review lenses. Pick the section that matches what you're reviewing — apply multiple if the file spans concerns (e.g. an async tokio service with FFI bindings).
LensSection
Source code — ownership, errors, trait design, unsafeSource review
Test code — unit, integration, async, mocking, proptestTest review
tokio async — task mgmt, sync primitives, channelsTokio async review
FFI — extern, repr(C), strings, callbacks, unsafe boundaryFFI review
For writing or setting up Rust (not reviewing it), see
rust-author
.

四个审查维度。选择与你要审查内容匹配的章节——如果文件涉及多个关注点(例如带有FFI绑定的异步Tokio服务),可同时应用多个维度。
审查维度对应章节
源代码 — 所有权、错误处理、trait设计、unsafe代码源代码审查
测试代码 — 单元测试、集成测试、异步测试、Mock、proptest测试代码审查
Tokio异步 — 任务管理、同步原语、通道Tokio异步审查
FFI — extern块、repr(C)、字符串、回调、unsafe边界FFI审查
如果是编写或搭建Rust项目(而非审查),请查看
rust-author

Source review

源代码审查

Rust Code Review

Rust代码审查

Review Workflow

审查流程

Follow this sequence to avoid false positives and catch edition-specific issues:
  1. Check
    Cargo.toml
    — Note the Rust edition (2018, 2021, 2024) and MSRV if set. Edition 2024 introduces breaking changes to unsafe semantics, RPIT lifetime capture, temporary scoping, and
    !
    type fallback. This determines which patterns apply. Check workspace structure if present.
  2. Check dependencies — Note key crates (thiserror vs anyhow, tokio features, serde features). These inform which patterns are expected.
  3. Scan changed files — Read full functions, not just diffs. Many Rust bugs hide in ownership flow across a function.
  4. Check each category — Work through the checklist below, loading references as needed.
  5. Verify before reporting — Load beagle-rust:review-verification-protocol before submitting findings.
遵循以下步骤,避免误报并捕捉版本相关问题:
  1. 检查
    Cargo.toml
    — 记录Rust版本(2018、2021、2024)以及设置的MSRV(最低支持Rust版本)。2024版本对unsafe语义、RPIT生命周期捕获、临时作用域和
    !
    类型回退引入了破坏性变更。这将决定适用哪些模式。如果存在工作区结构,也需检查。
  2. 检查依赖项 — 记录关键 crate(thiserror vs anyhow、tokio特性、serde特性)。这些将明确预期的代码模式。
  3. 扫描变更文件 — 阅读完整函数,而非仅查看差异。许多Rust bug隐藏在函数内的所有权流转中。
  4. 检查每个类别 — 按照下方清单逐一检查,必要时查阅参考文档。
  5. 报告前验证 — 在提交审查结果前,加载
    beagle-rust:review-verification-protocol

Output Format

输出格式

Report findings as:
text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.
按以下格式报告问题:
text
[文件:行号] 问题标题
严重程度: Critical | Major | Minor | Informational
问题描述及其影响。

Quick Reference

快速参考

Issue TypeReference
Ownership transfers, borrowing, lifetimes, clone traps, iteratorsreferences/ownership-borrowing.md
Lifetime variance, covariance/invariance, memory regionsreferences/lifetime-variance.md
Result/Option handling, thiserror, anyhow, error context, Error traitreferences/error-handling.md
Async pitfalls, Send/Sync bounds, runtime blockingreferences/async-concurrency.md
Send/Sync semantics, atomics, memory ordering, lock patternsreferences/concurrency-primitives.md
Type layout, alignment, repr, PhantomData, generics vs dyn Traitreferences/types-layout.md
Unsafe code, API design, derive patterns, clippy patternsreferences/common-mistakes.md
Safety contracts, raw pointers, MaybeUninit, soundness, Mirireferences/unsafe-deep.md
For development guidance on performance, pointer types, type state, clippy config, iterators, generics, and documentation, use the
beagle-rust:rust-best-practices
skill.
问题类型参考文档
所有权转移、借用、生命周期、克隆陷阱、迭代器references/ownership-borrowing.md
生命周期方差、协变/不变性、内存区域references/lifetime-variance.md
Result/Option处理、thiserror、anyhow、错误上下文、Error traitreferences/error-handling.md
异步陷阱、Send/Sync约束、运行时阻塞references/async-concurrency.md
Send/Sync语义、原子操作、内存顺序、锁模式references/concurrency-primitives.md
类型布局、对齐方式、repr、PhantomData、泛型vs dyn Traitreferences/types-layout.md
Unsafe代码、API设计、derive模式、clippy模式references/common-mistakes.md
安全契约、裸指针、MaybeUninit、安全性、Mirireferences/unsafe-deep.md
关于性能、指针类型、类型状态、clippy配置、迭代器、泛型和文档的开发指导,请使用
beagle-rust:rust-best-practices
技能。

Review Checklist

审查清单

Ownership and Borrowing

所有权与借用

  • No unnecessary
    .clone()
    to silence the borrow checker (hiding design issues)
  • No
    .clone()
    inside loops — prefer
    .cloned()
    or
    .copied()
    on iterators
  • No cloning to avoid lifetime annotations (take ownership explicitly or restructure)
  • References have appropriate lifetimes (not overly broad
    'static
    when shorter lifetime works)
  • Edition 2024: RPIT (
    -> impl Trait
    ) captures all in-scope lifetimes by default; use
    + use<'a>
    for precise capture control
  • &str
    preferred over
    String
    ,
    &[T]
    over
    Vec<T>
    in function parameters
  • impl AsRef<T>
    or
    Into<T>
    used for flexible API parameters
  • No dangling references or use-after-move
  • Interior mutability (
    Cell
    ,
    RefCell
    ,
    Mutex
    ) used only when shared mutation is genuinely needed
  • Small types (≤24 bytes) derive
    Copy
    and are passed by value
  • Cow<'_, T>
    used when ownership is ambiguous
  • Iterator chains preferred over index-based loops for collection transforms
  • No premature
    .collect()
    — pass iterators directly when the consumer accepts them
  • .sum()
    preferred over
    .fold()
    for summation (compiler optimizes better)
  • _or_else
    variants used when fallbacks involve allocation
  • Edition 2024:
    if let
    temporaries drop at end of the
    if let
    — code relying on temporaries living through the else branch needs restructuring
  • Edition 2024:
    Box<[T]>
    implements
    IntoIterator
    — prefer direct iteration over
    into_vec()
    first
  • 无不必要的
    .clone()
    来规避借用检查(这会隐藏设计问题)
  • 循环内无
    .clone()
    — 优先在迭代器上使用
    .cloned()
    .copied()
  • 无通过克隆来避免生命周期注解的情况(明确获取所有权或重构代码)
  • 引用具有合适的生命周期(当较短生命周期可行时,不使用过于宽泛的
    'static
  • 2024版本:RPIT(
    -> impl Trait
    )默认捕获所有作用域内的生命周期;使用
    + use<'a>
    进行精确捕获控制
  • 函数参数优先使用
    &str
    而非
    String
    &[T]
    而非
    Vec<T>
  • 使用
    impl AsRef<T>
    Into<T>
    实现灵活的API参数
  • 无悬垂引用或使用已转移所有权的值
  • 仅在真正需要共享可变状态时使用内部可变性(
    Cell
    RefCell
    Mutex
  • 小型类型(≤24字节)派生
    Copy
    并按值传递
  • 当所有权不明确时使用
    Cow<'_, T>
  • 集合转换优先使用迭代器链而非基于索引的循环
  • 避免过早调用
    .collect()
    — 当消费者支持时,直接传递迭代器
  • 求和优先使用
    .sum()
    而非
    .fold()
    (编译器优化效果更好)
  • 当回退操作涉及内存分配时,使用
    _or_else
    变体
  • 2024版本
    if let
    中的临时值在
    if let
    结束时销毁 — 依赖临时值贯穿else分支的代码需要重构
  • 2024版本
    Box<[T]>
    实现了
    IntoIterator
    — 优先直接迭代,而非先调用
    into_vec()

Error Handling

错误处理

  • Result<T, E>
    used for recoverable errors, not
    panic!
    /
    unwrap
    /
    expect
  • Error types provide context (thiserror with
    #[error("...")]
    or manual
    Display
    )
  • ?
    operator used with proper
    From
    implementations or
    .map_err()
  • unwrap()
    /
    expect()
    only in tests, examples, or provably-safe contexts
  • Error variants are specific enough to be actionable by callers
  • anyhow
    used in applications,
    thiserror
    in libraries (or clear rationale for alternatives)
  • _or_else
    variants used when fallbacks involve allocation (
    ok_or_else
    ,
    unwrap_or_else
    )
  • let-else
    used for early returns on failure (
    let Ok(x) = expr else { return ... }
    )
  • inspect_err
    used for error logging,
    map_err
    for error transformation
  • 可恢复错误使用
    Result<T, E>
    ,而非
    panic!
    /
    unwrap
    /
    expect
  • 错误类型提供上下文(使用带
    #[error("...")]
    的thiserror或手动实现
    Display
  • ?
    运算符与正确的
    From
    实现或
    .map_err()
    配合使用
  • unwrap()
    /
    expect()
    仅用于测试、示例或可证明安全的场景
  • 错误变体足够具体,便于调用方处理
  • 应用程序使用
    anyhow
    ,库使用
    thiserror
    (或有明确理由选择其他方案)
  • 当回退操作涉及内存分配时,使用
    _or_else
    变体(
    ok_or_else
    unwrap_or_else
  • 使用
    let-else
    实现失败时的提前返回(
    let Ok(x) = expr else { return ... }
  • 使用
    inspect_err
    记录错误,使用
    map_err
    转换错误

Traits and Types

Trait与类型

  • Traits are minimal and cohesive (single responsibility)
  • derive
    macros appropriate for the type (
    Clone
    ,
    Debug
    ,
    PartialEq
    used correctly)
  • Newtypes used to prevent primitive obsession (e.g.,
    struct UserId(Uuid)
    not bare
    Uuid
    )
  • From
    /
    Into
    implementations are lossless and infallible;
    TryFrom
    for fallible conversions
  • Sealed traits used when external implementations shouldn't be allowed
  • Default implementations provided where they make sense
  • Send + Sync
    bounds verified for types shared across threads
  • #[diagnostic::on_unimplemented]
    used on public traits to provide clear error messages when users forget to implement them
  • Trait保持最小化且内聚(单一职责)
  • derive
    宏适用于对应类型(正确使用
    Clone
    Debug
    PartialEq
  • 使用Newtype避免原始类型痴迷(例如
    struct UserId(Uuid)
    而非裸
    Uuid
  • From
    /
    Into
    实现是无损且无失败的;
    TryFrom
    用于可失败的转换
  • 当不允许外部实现时,使用密封Trait
  • 在合理的情况下提供默认实现
  • 验证跨线程共享类型的
    Send + Sync
    约束
  • 公共Trait上使用
    #[diagnostic::on_unimplemented]
    ,以便用户忘记实现时提供清晰的错误消息

Unsafe Code

Unsafe代码

  • unsafe
    blocks have safety comments explaining invariants
  • unsafe
    is minimal — only the truly unsafe operation is inside the block
  • Safety invariants are documented and upheld by surrounding safe code
  • No undefined behavior (null pointer deref, data races, invalid memory access)
  • unsafe
    trait implementations justify why the contract is upheld
  • Edition 2024:
    unsafe fn
    bodies use explicit
    unsafe {}
    blocks around unsafe ops (
    unsafe_op_in_unsafe_fn
    is deny)
  • Edition 2024:
    extern "C" {}
    blocks written as
    unsafe extern "C" {}
  • Edition 2024:
    #[no_mangle]
    and
    #[export_name]
    written as
    #[unsafe(no_mangle)]
    and
    #[unsafe(export_name)]
  • unsafe
    块带有安全注释,解释不变量
  • unsafe
    范围最小化 — 仅将真正不安全的操作放在块内
  • 安全不变量已文档化,并由周围的安全代码维护
  • 无未定义行为(空指针解引用、数据竞争、无效内存访问)
  • unsafe
    trait实现需证明契约已被遵守
  • 2024版本
    unsafe fn
    主体在不安全操作周围使用显式
    unsafe {}
    块(
    unsafe_op_in_unsafe_fn
    设为deny)
  • 2024版本
    extern "C" {}
    块需写成
    unsafe extern "C" {}
  • 2024版本
    #[no_mangle]
    #[export_name]
    需写成
    #[unsafe(no_mangle)]
    #[unsafe(export_name)]

Naming and Style

命名与风格

  • Types are
    PascalCase
    , functions/methods
    snake_case
    , constants
    SCREAMING_SNAKE_CASE
  • Modules use
    snake_case
  • is_
    ,
    has_
    ,
    can_
    prefixes for boolean-returning methods
  • Builder pattern methods take and return
    self
    (not
    &mut self
    ) for chaining
  • Public items have doc comments (
    ///
    )
  • #[must_use]
    on functions where ignoring the return value is likely a bug
  • Imports ordered: std → external crates → workspace → crate/super
  • #[expect(clippy::...)]
    preferred over
    #[allow(...)]
    for lint suppression
  • 类型使用
    PascalCase
    ,函数/方法使用
    snake_case
    ,常量使用
    SCREAMING_SNAKE_CASE
  • 模块使用
    snake_case
  • 返回布尔值的方法使用
    is_
    has_
    can_
    前缀
  • Builder模式方法接收并返回
    self
    (而非
    &mut self
    )以支持链式调用
  • 公共项带有文档注释(
    ///
  • 对忽略返回值可能导致bug的函数使用
    #[must_use]
  • 导入顺序:std → 外部crate → 工作区 → crate/super
  • 抑制lint时优先使用
    #[expect(clippy::...)]
    而非
    #[allow(...)]

Performance

性能

Detailed guidance:
beagle-rust:rust-best-practices
skill (references/performance.md)
  • No unnecessary allocations in hot paths (prefer
    &str
    over
    String
    ,
    &[T]
    over
    Vec<T>
    )
  • collect()
    type is specified or inferable
  • Iterators preferred over indexed loops for collection transforms
  • Vec::with_capacity()
    used when size is known
  • No redundant
    .to_string()
    /
    .to_owned()
    chains
  • No intermediate
    .collect()
    when passing iterators directly works
  • .sum()
    preferred over
    .fold()
    for summation
  • Static dispatch (
    impl Trait
    ) used over dynamic (
    dyn Trait
    ) unless flexibility required
详细指导:
beagle-rust:rust-best-practices
技能(references/performance.md)
  • 热路径中无不必要的内存分配(优先使用
    &str
    而非
    String
    &[T]
    而非
    Vec<T>
  • collect()
    的类型已指定或可推断
  • 集合转换优先使用迭代器而非索引循环
  • 已知大小时使用
    Vec::with_capacity()
  • 无冗余的
    .to_string()
    /
    .to_owned()
    链式调用
  • 当可直接传递迭代器时,避免中间的
    .collect()
  • 求和优先使用
    .sum()
    而非
    .fold()
  • 优先使用静态分发(
    impl Trait
    )而非动态分发(
    dyn Trait
    ),除非需要灵活性

Clippy Configuration

Clippy配置

Detailed guidance:
beagle-rust:rust-best-practices
skill (references/clippy-config.md)
  • Workspace-level lints configured in
    Cargo.toml
    (
    [workspace.lints.clippy]
    or
    [lints.clippy]
    )
  • #[expect(clippy::lint)]
    used over
    #[allow(...)]
    — warns when suppression becomes stale
  • Justification comment present when suppressing any lint
  • Key lints enforced:
    redundant_clone
    ,
    large_enum_variant
    ,
    needless_collect
    ,
    perf
    group
  • cargo clippy --all-targets --all-features -- -D warnings
    passes
  • Doc lints enabled for library crates (
    missing_docs
    ,
    broken_intra_doc_links
    )
详细指导:
beagle-rust:rust-best-practices
技能(references/clippy-config.md)
  • 工作区级lint在
    Cargo.toml
    中配置(
    [workspace.lints.clippy]
    [lints.clippy]
  • 使用
    #[expect(clippy::lint)]
    而非
    #[allow(...)]
    — 当抑制不再需要时会发出警告
  • 抑制任何lint时都有理由注释
  • 强制执行关键lint:
    redundant_clone
    large_enum_variant
    needless_collect
    perf
  • cargo clippy --all-targets --all-features -- -D warnings
    执行通过
  • 库crate启用文档lint(
    missing_docs
    broken_intra_doc_links

Type State Pattern

类型状态模式

Detailed guidance:
beagle-rust:rust-best-practices
skill (references/type-state-pattern.md)
  • PhantomData<State>
    used for zero-cost compile-time state machines (not runtime enums/booleans)
  • State transitions consume
    self
    and return new state type (prevents reuse of old state)
  • Only applicable methods available per state (invalid operations are compile errors)
  • Pattern used where it adds safety value (builders with required fields, connection states, workflows)
  • Not overused for trivial state (simple enums are fine when runtime flexibility needed)
详细指导:
beagle-rust:rust-best-practices
技能(references/type-state-pattern.md)
  • 使用
    PhantomData<State>
    实现零成本编译时状态机(而非运行时枚举/布尔值)
  • 状态转换消耗
    self
    并返回新状态类型(防止旧状态被重复使用)
  • 每个状态仅提供适用的方法(无效操作在编译时就会报错)
  • 在能提升安全性的场景使用该模式(带有必填字段的Builder、连接状态、工作流)
  • 不为 trivial 状态过度使用该模式(当需要运行时灵活性时,简单枚举即可)

Severity Calibration

严重程度校准

Critical (Block Merge)

Critical(阻止合并)

  • unsafe
    code with unsound invariants or undefined behavior
  • Use-after-free or dangling reference patterns
  • unwrap()
    on user input or external data in production code
  • Data races (concurrent mutation without synchronization)
  • Memory leaks via circular
    Arc<Mutex<...>>
    without weak references
  • 存在不安全不变量或未定义行为的
    unsafe
    代码
  • 使用已释放内存或悬垂引用的模式
  • 生产代码中对用户输入或外部数据使用
    unwrap()
  • 无同步的并发修改导致的数据竞争
  • 无弱引用的循环
    Arc<Mutex<...>>
    导致内存泄漏

Major (Should Fix)

Major(应修复)

  • Errors returned without context (bare
    return err
    equivalent)
  • .clone()
    masking ownership design issues in hot paths
  • Missing
    Send
    /
    Sync
    bounds on types used across threads
  • panic!
    for recoverable errors in library code
  • Overly broad
    'static
    lifetimes hiding API design issues
  • 返回无上下文的错误(等效于裸
    return err
  • 热路径中通过
    .clone()
    掩盖所有权设计问题
  • 跨线程使用的类型缺少
    Send
    /
    Sync
    约束
  • 库代码中对可恢复错误使用
    panic!
  • 过于宽泛的
    'static
    生命周期隐藏API设计问题

Minor (Consider Fixing)

Minor(考虑修复)

  • Missing doc comments on public items
  • String
    parameter where
    &str
    or
    impl AsRef<str>
    would work
  • Derive macros missing for types that should have them
  • Unused feature flags in
    Cargo.toml
  • Suboptimal iterator chains (multiple allocations where one suffices)
  • 公共项缺少文档注释
  • 参数使用
    String
    ,而
    &str
    impl AsRef<str>
    更合适
  • 应为类型派生的宏缺失
  • Cargo.toml
    中存在未使用的特性标志
  • 次优的迭代器链(多次内存分配可合并为一次)

Informational (Note Only)

Informational(仅作提示)

  • Suggestions to introduce newtypes for domain modeling
  • Refactoring ideas for trait design
  • Performance optimizations without measured impact
  • Suggestions to add
    #[must_use]
    or
    #[non_exhaustive]
  • 建议为领域建模引入Newtype
  • Trait设计的重构思路
  • 无实测影响的性能优化建议
  • 添加
    #[must_use]
    #[non_exhaustive]
    的建议

When to Load References

何时查阅参考文档

  • Reviewing ownership, borrows, lifetimes, clone traps → ownership-borrowing.md
  • Reviewing lifetime variance, covariance/invariance, multiple lifetime params → lifetime-variance.md
  • Reviewing Result/Option handling, error types, Error trait impls → error-handling.md
  • Reviewing async code, tokio usage, task management → async-concurrency.md
  • Reviewing Send/Sync, atomics, memory ordering, mutexes, lock patterns → concurrency-primitives.md
  • Reviewing type layout, alignment, repr, PhantomData, generics vs dyn → types-layout.md
  • Reviewing unsafe code, API design, derive macros, clippy patterns → common-mistakes.md
  • Reviewing safety contracts, raw pointers, MaybeUninit, soundness → unsafe-deep.md
  • Reviewing performance, pointer types, type state, generics, iterators, documentation →
    beagle-rust:rust-best-practices
    skill
  • 审查所有权、借用、生命周期、克隆陷阱 → ownership-borrowing.md
  • 审查生命周期方差、协变/不变性、多个生命周期参数 → lifetime-variance.md
  • 审查Result/Option处理、错误类型、Error trait实现 → error-handling.md
  • 审查异步代码、tokio使用、任务管理 → async-concurrency.md
  • 审查Send/Sync、原子操作、内存顺序、互斥锁、锁模式 → concurrency-primitives.md
  • 审查类型布局、对齐方式、repr、PhantomData、泛型vs dyn → types-layout.md
  • 审查unsafe代码、API设计、derive宏、clippy模式 → common-mistakes.md
  • 审查安全契约、裸指针、MaybeUninit、安全性 → unsafe-deep.md
  • 审查性能、指针类型、类型状态、泛型、迭代器、文档 →
    beagle-rust:rust-best-practices
    技能

Valid Patterns (Do NOT Flag)

有效模式(无需标记)

These are acceptable Rust patterns — reporting them wastes developer time:
  • .clone()
    in tests
    — Clarity over performance in test code
  • unwrap()
    in tests and examples
    — Acceptable where panicking on failure is intentional
  • Box<dyn Error>
    in simple binaries
    — Not every application needs custom error types
  • String
    fields in structs
    — Owned data in structs is correct;
    &str
    fields require lifetime parameters
  • #[allow(dead_code)]
    during development
    — Common during iteration
  • todo!()
    /
    unimplemented!()
    in new code
    — Valid placeholder during active development
  • .expect("reason")
    with clear message
    — Self-documenting and acceptable for invariants
  • use super::*
    in test modules
    — Standard pattern for
    #[cfg(test)]
    modules
  • Type aliases for complex types
    type Result<T> = std::result::Result<T, MyError>
    is idiomatic
  • impl Trait
    in return position
    — Zero-cost abstraction, standard pattern
  • Turbofish syntax
    collect::<Vec<_>>()
    is idiomatic when type inference needs help
  • _
    prefix for intentionally unused variables
    — Compiler convention
  • #[expect(clippy::...)]
    with justification
    — Self-cleaning lint suppression
  • Arc::clone(&arc)
    — Explicit Arc cloning is idiomatic and recommended
  • std::sync::Mutex
    for short critical sections in async
    — Tokio docs recommend this
  • for
    loops over iterators
    — When early exit or side effects are needed
  • async fn
    in trait definitions
    — Stable since 1.75;
    async-trait
    crate only needed for
    dyn Trait
    or pre-1.75 MSRV
  • LazyCell
    /
    LazyLock
    from std
    — Stable since 1.80; replaces
    once_cell
    and
    lazy_static
    for new code
  • + use<'a, T>
    precise capture syntax
    — Edition 2024 syntax for controlling RPIT lifetime capture
这些是可接受的Rust模式——报告它们会浪费开发者时间:
  • 测试中的
    .clone()
    — 测试代码中清晰度优先于性能
  • 测试和示例中的
    unwrap()
    — 在失败时故意panic是可接受的
  • 简单二进制文件中的
    Box<dyn Error>
    — 并非每个应用都需要自定义错误类型
  • 结构体中的
    String
    字段
    — 结构体中使用自有数据是正确的;
    &str
    字段需要生命周期参数
  • 开发期间的
    #[allow(dead_code)]
    — 迭代开发中常见
  • 新代码中的
    todo!()
    /
    unimplemented!()
    — 活跃开发期间的有效占位符
  • 带有清晰消息的
    .expect("reason")
    — 自文档化,适用于不变量检查
  • 测试模块中的
    use super::*
    #[cfg(test)]
    模块的标准模式
  • 复杂类型的类型别名
    type Result<T> = std::result::Result<T, MyError>
    是惯用写法
  • 返回位置的
    impl Trait
    — 零成本抽象,标准模式
  • Turbofish语法 — 当类型推断需要帮助时,
    collect::<Vec<_>>()
    是惯用写法
  • 有意未使用变量的
    _
    前缀
    — 编译器约定
  • 带有理由的
    #[expect(clippy::...)]
    — 自清理式lint抑制
  • Arc::clone(&arc)
    — 显式Arc克隆是惯用且推荐的写法
  • 异步代码中短临界区使用
    std::sync::Mutex
    — Tokio文档推荐此做法
  • 迭代器上的
    for
    循环
    — 当需要提前退出或副作用时适用
  • Trait定义中的
    async fn
    — 自1.75版本起稳定;仅当需要
    dyn Trait
    或MSRV低于1.75时才需要
    async-trait
    crate
  • std中的
    LazyCell
    /
    LazyLock
    — 自1.80版本起稳定;替代新代码中的
    once_cell
    lazy_static
  • + use<'a, T>
    精确捕获语法
    — 2024版本中用于控制RPIT生命周期捕获的语法

Context-Sensitive Rules

上下文敏感规则

Only flag these issues when the specific conditions apply:
IssueFlag ONLY IF
Missing error contextError crosses module boundary without context
Unnecessary
.clone()
In hot path or repeated call, not test/setup code
Missing doc commentsItem is
pub
and not in a
#[cfg(test)]
module
unwrap()
usage
In production code path, not test/example/provably-safe
Missing
Send + Sync
Type is actually shared across thread/task boundaries
Overly broad lifetimeA shorter lifetime would work AND the API is public
Missing
#[must_use]
Function returns a value that callers commonly ignore
Stale
#[allow]
suppression
Should be
#[expect]
for self-cleaning lint management
Missing
Copy
derive
Type is ≤24 bytes with all-Copy fields and used frequently
Edition 2024:
!
type fallback
Match on
Result<T, !>
or diverging expressions where
()
fallback was assumed —
!
now falls back to
!
not
()
Edition 2024:
r#gen
identifier
Code uses
gen
as an identifier — must be
r#gen
in edition 2024 (reserved keyword)
仅当特定条件满足时才标记这些问题:
问题仅在以下情况标记
缺少错误上下文错误跨模块边界传递时无上下文
不必要的
.clone()
位于热路径或重复调用中,而非测试/初始化代码
缺少文档注释项为
pub
且不在
#[cfg(test)]
模块中
unwrap()
使用
位于生产代码路径中,而非测试/示例/可证明安全的场景
缺少
Send + Sync
类型实际跨线程/任务边界共享
过于宽泛的生命周期较短生命周期可行且API为公共API
缺少
#[must_use]
函数返回值常被调用方忽略
过时的
#[allow]
抑制
应使用
#[expect]
实现自清理式lint管理
缺少
Copy
派生
类型≤24字节且所有字段均为Copy类型,且频繁使用
2024版本
!
类型回退
匹配
Result<T, !>
或发散表达式时,假设
()
回退——现在
!
回退到
!
而非
()
2024版本
r#gen
标识符
代码使用
gen
作为标识符——2024版本中必须写成
r#gen
(保留关键字)

Before Submitting Findings

提交审查结果前

Load and follow
beagle-rust:review-verification-protocol
before reporting any issue.
<!-- cross-ref:start -->
在报告任何问题前,加载并遵循
beagle-rust:review-verification-protocol
<!-- cross-ref:start -->

See also (related skills — Code review family)

另请参阅(相关技能 — 代码审查系列)

If your issue relates to:
  • CodeRabbit-powered review (default) — check
    code-review
    if appropriate.
  • auto-apply CodeRabbit review comments — check
    autofix
    if appropriate.
  • Python + pytest review (type safety, async, fixtures) — check
    python-code-review
    if appropriate.
  • Rust test review — check
    rust-testing-code-review
    if appropriate.
  • tokio async review — check
    tokio-async-code-review
    if appropriate.
  • Rust FFI review — check
    ffi-code-review
    if appropriate.
  • Deep Agents code review — check
    deepagents-code-review
    if appropriate.
  • SQLAlchemy 2.0 review — check
    sqlalchemy-code-review
    if appropriate.
<!-- cross-ref:end -->
如果你的问题涉及:
  • CodeRabbit驱动的审查(默认) — 若合适,请查看
    code-review
  • 自动应用CodeRabbit审查评论 — 若合适,请查看
    autofix
  • Python + pytest审查(类型安全、异步、fixtures) — 若合适,请查看
    python-code-review
  • Rust测试审查 — 若合适,请查看
    rust-testing-code-review
  • Tokio异步审查 — 若合适,请查看
    tokio-async-code-review
  • Rust FFI审查 — 若合适,请查看
    ffi-code-review
  • Deep Agents代码审查 — 若合适,请查看
    deepagents-code-review
  • SQLAlchemy 2.0审查 — 若合适,请查看
    sqlalchemy-code-review
<!-- cross-ref:end -->

Test review

测试代码审查

Rust Testing Code Review

Rust测试代码审查

Review Workflow

审查流程

  1. Check Rust edition — Note edition in
    Cargo.toml
    (2021 vs 2024). Edition 2024 changes temporary scoping in
    if let
    and tail expressions, and makes
    #[expect]
    the preferred lint suppression
  2. Check test organization — Unit tests in
    #[cfg(test)]
    modules, integration tests in
    tests/
    directory
  3. Check async test setup
    #[tokio::test]
    for async tests, proper runtime configuration. Check for
    async-trait
    on mocks that could use native
    async fn
    in traits
  4. Check assertions — Meaningful messages, correct assertion type. Review
    if let
    assertions for edition 2024 temporary scope changes
  5. Check test isolation — No shared mutable state between tests, proper setup/teardown. Prefer
    LazyLock
    over
    lazy_static!
    /
    once_cell
    for shared fixtures
  6. Check coverage patterns — Error paths tested, edge cases covered
  1. 检查Rust版本 — 记录
    Cargo.toml
    中的版本(2021 vs 2024)。2024版本改变了
    if let
    和尾表达式中的临时作用域,并将
    #[expect]
    作为首选lint抑制方式
  2. 检查测试组织 — 单元测试位于
    #[cfg(test)]
    模块中,集成测试位于
    tests/
    目录下
  3. 检查异步测试设置 — 异步测试使用
    #[tokio::test]
    ,运行时配置正确。检查Mock是否可使用Trait中的原生
    async fn
    ,而非
    async-trait
  4. 检查断言 — 消息有意义,断言类型正确。针对2024版本的临时作用域变化,审查
    if let
    断言
  5. 检查测试隔离 — 测试间无共享可变状态,设置/清理正确。共享fixture优先使用
    LazyLock
    而非
    lazy_static!
    /
    once_cell
  6. 检查覆盖模式 — 测试错误路径,覆盖边缘情况

Output Format

输出格式

Report findings as:
text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.
按以下格式报告问题:
text
[文件:行号] 问题标题
严重程度: Critical | Major | Minor | Informational
问题描述及其影响。

Quick Reference

快速参考

Issue TypeReference
Unit tests, assertions, naming, snapshots, rstest, doc tests,
#[expect]
,
LazyLock
fixtures, tail expression scope
references/unit-tests.md
Integration tests, async testing, fixtures, test databases, native
async fn
mocks,
if let
temporary scope
references/integration-tests.md
Fuzzing, property-based testing, Miri, Loom, benchmarking, compile_fail, custom harness, mocking strategiesreferences/advanced-testing.md
问题类型参考文档
单元测试、断言、命名、快照、rstest、文档测试、
#[expect]
LazyLock
fixture、尾表达式作用域
references/unit-tests.md
集成测试、异步测试、fixtures、测试数据库、原生
async fn
Mock、
if let
临时作用域
references/integration-tests.md
模糊测试、基于属性的测试、Miri、Loom、基准测试、compile_fail、自定义测试 harness、Mock策略references/advanced-testing.md

Review Checklist

审查清单

Test Structure

测试结构

  • Unit tests in
    #[cfg(test)] mod tests
    within source files
  • Integration tests in
    tests/
    directory (one file per module or feature)
  • use super::*
    in test modules to access parent module items
  • Test function names describe the scenario:
    test_<function>_<scenario>_<expected>
  • Tests are independent — no reliance on execution order
  • 单元测试位于源文件内的
    #[cfg(test)] mod tests
  • 集成测试位于
    tests/
    目录下(每个模块或功能对应一个文件)
  • 测试模块中使用
    use super::*
    访问父模块项
  • 测试函数名称描述场景:
    test_<函数>_<场景>_<预期结果>
  • 测试相互独立 — 不依赖执行顺序

Async Tests

异步测试

  • #[tokio::test]
    used for async test functions
  • #[tokio::test(flavor = "multi_thread")]
    when testing multi-threaded behavior
  • No
    block_on
    inside async tests (use
    .await
    directly)
  • Test timeouts set for tests that could hang
  • Mock traits use native
    async fn
    instead of
    async-trait
    crate (stable since Rust 1.75)
  • 异步测试函数使用
    #[tokio::test]
  • 测试多线程行为时使用
    #[tokio::test(flavor = "multi_thread")]
  • 异步测试内无
    block_on
    (直接使用
    .await
  • 为可能挂起的测试设置超时
  • Mock Trait使用原生
    async fn
    而非
    async-trait
    crate(自Rust 1.75起稳定)

Assertions

断言

  • assert_eq!
    /
    assert_ne!
    used for value comparisons (better error messages than
    assert!
    )
  • Custom messages on assertions that aren't self-documenting
  • matches!
    macro used for enum variant checking
  • Error types checked with
    matches!
    or pattern matching, not string comparison
  • One assertion per test where practical (easier to diagnose failures)
  • if let
    assertions reviewed for edition 2024 temporary scope — temporaries in conditions drop earlier, may invalidate borrows
  • Tail expression returns reviewed for edition 2024 — temporaries in tail expressions drop before local variables
  • 值比较使用
    assert_eq!
    /
    assert_ne!
    (比
    assert!
    的错误消息更清晰)
  • 非自文档化的断言带有自定义消息
  • 枚举变体检查使用
    matches!
  • 使用
    matches!
    或模式匹配检查错误类型,而非字符串比较
  • 实际可行时,每个测试仅包含一个断言(便于诊断失败)
  • 针对2024版本的临时作用域,审查
    if let
    断言 — 条件中的临时值销毁更早,可能使借用无效
  • 针对2024版本,审查尾表达式返回值 — 尾表达式中的临时值在局部变量之前销毁

Mocking and Test Doubles

Mock与测试替身

  • Traits used as seams for dependency injection (not concrete types)
  • Mock implementations kept minimal — only what the test needs
  • No mocking of types you don't own (wrap external dependencies behind your own trait)
  • Test fixtures as helper functions, not global state
  • std::sync::LazyLock
    used for shared test fixtures instead of
    lazy_static!
    or
    once_cell
    (stable since Rust 1.80)
  • 使用Trait作为依赖注入的 seam(而非具体类型)
  • Mock实现保持最小化 — 仅包含测试所需的部分
  • 不Mock不属于你的类型(将外部依赖包装在自己的Trait后再Mock)
  • 测试fixture作为辅助函数,而非全局状态
  • 共享测试fixture使用
    std::sync::LazyLock
    而非
    lazy_static!
    once_cell
    (自Rust 1.80起稳定)

Error Path Testing

错误路径测试

  • Result::Err
    variants tested, not just happy paths
  • Specific error variants checked (not just "is error")
  • #[should_panic]
    used sparingly — prefer
    Result
    -returning tests
  • 测试
    Result::Err
    变体,而非仅测试正常路径
  • 检查具体的错误变体(而非仅检查"是否为错误")
  • 谨慎使用
    #[should_panic]
    — 优先使用返回
    Result
    的测试

Lint Suppression in Tests

测试中的Lint抑制

  • #[expect(lint)]
    used instead of
    #[allow(lint)]
    for test-specific suppressions (stable since Rust 1.81)
  • Justification comment on every
    #[expect]
    or
    #[allow]
    in test code
  • Stale
    #[allow]
    attributes migrated to
    #[expect]
    for self-cleaning behavior
  • 测试特定抑制使用
    #[expect(lint)]
    而非
    #[allow(lint)]
    (自Rust 1.81起稳定)
  • 测试代码中每个
    #[expect]
    #[allow]
    都带有理由注释
  • 将过时的
    #[allow]
    属性迁移为
    #[expect]
    以实现自清理

Test Naming

测试命名

  • Test names read like sentences describing behavior (not
    test_happy_path
    )
  • Related tests grouped in nested
    mod
    blocks for organization
  • Test names follow pattern:
    <function>_should_<behavior>_when_<condition>
  • 测试名称读起来像描述行为的句子(而非
    test_happy_path
  • 相关测试分组在嵌套
    mod
    块中以组织代码
  • 测试名称遵循模式:
    <函数>_should_<行为>_when_<条件>

Snapshot Testing

快照测试

  • cargo insta
    used for complex structural output (JSON, YAML, HTML, CLI output)
  • Snapshots are small and focused (not huge objects)
  • Redactions used for unstable fields (timestamps, UUIDs)
  • Snapshots committed to git in
    snapshots/
    directory
  • Simple values use
    assert_eq!
    , not snapshots
  • 复杂结构化输出(JSON、YAML、HTML、CLI输出)使用
    cargo insta
  • 快照小巧且聚焦(而非庞大对象)
  • 不稳定字段(时间戳、UUID)使用脱敏处理
  • 快照提交到git的
    snapshots/
    目录中
  • 简单值使用
    assert_eq!
    ,而非快照

Parametrized Testing

参数化测试

  • rstest
    used to avoid duplicated test functions for similar inputs
  • #[rstest]
    with
    #[case::name]
    attributes for descriptive parametrized tests
  • #[fixture]
    used for shared test setup when multiple tests need same construction
  • Parametrized tests still have descriptive case names (not just
    #[case(1)]
    )
  • Combined with async:
    #[rstest] #[tokio::test]
    for async parametrized tests
  • 使用
    rstest
    避免为相似输入编写重复测试函数
  • #[rstest]
    配合
    #[case::name]
    属性实现描述性参数化测试
  • 当多个测试需要相同构造时,使用
    #[fixture]
    实现共享测试设置
  • 参数化测试仍具有描述性的用例名称(而非仅
    #[case(1)]
  • 与异步结合:
    #[rstest] #[tokio::test]
    用于异步参数化测试

Doc Tests

文档测试

  • Public API functions have
    /// # Examples
    with runnable code
  • Doc tests serve as both documentation and correctness checks
  • Hidden setup lines prefixed with
    #
    to keep examples clean
  • cargo test --doc
    passes (nextest doesn't run doc tests)
  • 公共API函数带有
    /// # Examples
    和可运行代码
  • 文档测试同时作为文档和正确性检查
  • 隐藏的设置行以
    #
    为前缀,保持示例简洁
  • cargo test --doc
    执行通过(nextest不运行文档测试)

Severity Calibration

严重程度校准

Critical

Critical

  • Tests that pass but don't actually verify behavior (assertions on wrong values)
  • Shared mutable state between tests causing flaky results
  • Missing error path tests for security-critical code
  • 测试通过但未实际验证行为(断言错误的值)
  • 测试间共享可变状态导致结果不稳定
  • 安全关键代码缺少错误路径测试

Major

Major

  • #[should_panic]
    without
    expected
    message (catches any panic, including wrong ones)
  • unwrap()
    in test setup that hides the real failure location
  • Tests that depend on execution order
  • if let
    with inline temporary in assertion that breaks under edition 2024 temporary scoping
  • async-trait
    on mock traits when native
    async fn
    in traits is available and project targets edition 2024
  • #[should_panic]
    未指定
    expected
    消息(捕获任何panic,包括错误的panic)
  • 测试设置中的
    unwrap()
    隐藏了实际失败位置
  • 测试依赖执行顺序
  • 断言中的内联临时值使用
    if let
    ,在2024版本的临时作用域下会失效
  • 当项目目标为2024版本且原生Trait
    async fn
    可用时,Mock Trait仍使用
    async-trait

Minor

Minor

  • Missing assertion messages on complex comparisons
  • assert!(x == y)
    instead of
    assert_eq!(x, y)
    (worse error messages)
  • Test names that don't describe the scenario
  • Redundant setup code that could be extracted to a helper
  • #[allow]
    used where
    #[expect]
    would provide self-cleaning suppression
  • lazy_static!
    or
    once_cell
    used for test fixtures when
    LazyLock
    is available
  • 复杂比较缺少断言消息
  • 使用
    assert!(x == y)
    而非
    assert_eq!(x, y)
    (错误消息更差)
  • 测试名称未描述场景
  • 可提取到辅助函数的冗余设置代码
  • 可使用
    #[expect]
    实现自清理抑制的场景中使用了
    #[allow]
  • 测试fixture可使用
    LazyLock
    时仍使用
    lazy_static!
    once_cell

Informational

Informational

  • Suggestions to add property-based tests via
    proptest
    or
    quickcheck
  • Suggestions to add snapshot testing for complex output
  • Coverage improvement opportunities
  • 建议通过
    proptest
    quickcheck
    添加基于属性的测试
  • 建议为复杂输出添加快照测试
  • 覆盖率提升机会

Valid Patterns (Do NOT Flag)

有效模式(无需标记)

  • unwrap()
    /
    expect()
    in tests
    — Panicking on unexpected errors is the correct test behavior
  • use super::*
    in test modules
    — Standard pattern for accessing parent items
  • #[allow(dead_code)]
    on test helpers
    — Helper functions may not be used in every test
  • clone()
    in tests
    — Clarity over performance
  • Large test functions — Integration tests can be long; extracting helpers isn't always clearer
  • assert!
    for boolean checks
    — Fine when the expression is clearly boolean (
    .is_some()
    ,
    .is_empty()
    )
  • Multiple assertions testing one logical behavior — Sometimes one behavior needs multiple checks
  • unwrap()
    on
    Result
    -returning test functions
    — Propagating with
    ?
    is also fine but not required
  • async-trait
    on mock traits requiring
    dyn
    dispatch
    — Native
    async fn
    in traits doesn't support
    dyn Trait
    ;
    async-trait
    is still needed there
  • #[expect]
    with justification on test helpers
    — Self-cleaning lint suppression is correct in test code
  • LazyLock
    for expensive shared test fixtures
    — Thread-safe lazy init is appropriate for test globals
  • 测试中的
    unwrap()
    /
    expect()
    — 意外错误时panic是正确的测试行为
  • 测试模块中的
    use super::*
    — 访问父项的标准模式
  • 测试辅助函数上的
    #[allow(dead_code)]
    — 辅助函数可能并非在每个测试中都使用
  • 测试中的
    clone()
    — 清晰度优先于性能
  • 大型测试函数 — 集成测试可以很长;提取辅助函数并不总是更清晰
  • 布尔检查使用
    assert!
    — 当表达式明确为布尔值时(
    .is_some()
    .is_empty()
    )是可行的
  • 测试一个逻辑行为时使用多个断言 — 有时一个行为需要多个检查
  • 返回
    Result
    的测试函数中使用
    unwrap()
    — 使用
    ?
    传播错误也可行,但非必须
  • 需要
    dyn
    分发的Mock Trait使用
    async-trait
    — 原生Trait
    async fn
    不支持
    dyn Trait
    ;此时仍需要
    async-trait
  • 测试辅助函数上带有理由的
    #[expect]
    — 测试代码中使用自清理式lint抑制是正确的
  • 昂贵的共享测试fixture使用
    LazyLock
    — 线程安全的延迟初始化适用于测试全局变量

Before Submitting Findings

提交审查结果前

Load and follow
beagle-rust:review-verification-protocol
before reporting any issue.
<!-- cross-ref:start -->
在报告任何问题前,加载并遵循
beagle-rust:review-verification-protocol
<!-- cross-ref:start -->

See also (related skills — Code review family)

另请参阅(相关技能 — 代码审查系列)

If your issue relates to:
  • CodeRabbit-powered review (default) — check
    code-review
    if appropriate.
  • auto-apply CodeRabbit review comments — check
    autofix
    if appropriate.
  • Python + pytest review (type safety, async, fixtures) — check
    python-code-review
    if appropriate.
  • Rust source review — check
    rust-code-review
    if appropriate.
  • tokio async review — check
    tokio-async-code-review
    if appropriate.
  • Rust FFI review — check
    ffi-code-review
    if appropriate.
  • Deep Agents code review — check
    deepagents-code-review
    if appropriate.
  • SQLAlchemy 2.0 review — check
    sqlalchemy-code-review
    if appropriate.
<!-- cross-ref:end -->
如果你的问题涉及:
  • CodeRabbit驱动的审查(默认) — 若合适,请查看
    code-review
  • 自动应用CodeRabbit审查评论 — 若合适,请查看
    autofix
  • Python + pytest审查(类型安全、异步、fixtures) — 若合适,请查看
    python-code-review
  • Rust源代码审查 — 若合适,请查看
    rust-code-review
  • Tokio异步审查 — 若合适,请查看
    tokio-async-code-review
  • Rust FFI审查 — 若合适,请查看
    ffi-code-review
  • Deep Agents代码审查 — 若合适,请查看
    deepagents-code-review
  • SQLAlchemy 2.0审查 — 若合适,请查看
    sqlalchemy-code-review
<!-- cross-ref:end -->

Tokio async review

Tokio异步审查

Tokio Async Code Review

Tokio异步代码审查

Review Workflow

审查流程

  1. Check Cargo.toml — Note tokio feature flags (
    full
    ,
    rt-multi-thread
    ,
    macros
    ,
    sync
    , etc.). Missing features cause confusing compile errors.
  2. Check runtime setup — Is
    #[tokio::main]
    or manual runtime construction used? Multi-thread vs current-thread?
  3. Scan for blocking — Search for
    std::fs
    ,
    std::net
    ,
    std::thread::sleep
    , CPU-heavy loops in async functions.
  4. Check channel usage — Match channel type to communication pattern (mpsc, broadcast, oneshot, watch).
  5. Check sync primitives — Verify correct mutex type, proper guard lifetimes, no deadlock potential.
  1. 检查Cargo.toml — 记录tokio特性标志(
    full
    rt-multi-thread
    macros
    sync
    等)。缺少特性会导致令人困惑的编译错误。
  2. 检查运行时设置 — 使用
    #[tokio::main]
    还是手动构造运行时?多线程还是单线程?
  3. 扫描阻塞操作 — 在异步函数中搜索
    std::fs
    std::net
    std::thread::sleep
    、CPU密集型循环。
  4. 检查通道使用 — 通道类型与通信模式匹配(mpsc、broadcast、oneshot、watch)。
  5. 检查同步原语 — 验证互斥锁类型正确、守卫生命周期合理、无死锁风险。

Output Format

输出格式

Report findings as:
text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.
按以下格式报告问题:
text
[文件:行号] 问题标题
严重程度: Critical | Major | Minor | Informational
问题描述及其影响。

Quick Reference

快速参考

Issue TypeReference
Task spawning, JoinHandle, structured concurrencyreferences/task-management.md
Mutex, RwLock, Semaphore, Notify, Barrierreferences/sync-primitives.md
mpsc, broadcast, oneshot, watch channel patternsreferences/channels.md
Pin, cancellation, Future internals, select!, blocking bridgereferences/pinning-cancellation.md
问题类型参考文档
任务生成、JoinHandle、结构化并发references/task-management.md
Mutex、RwLock、Semaphore、Notify、Barrierreferences/sync-primitives.md
mpsc、broadcast、oneshot、watch通道模式references/channels.md
Pin、取消、Future内部实现、select!、阻塞桥接references/pinning-cancellation.md

Review Checklist

审查清单

Runtime Configuration

运行时配置

  • Tokio features in Cargo.toml match actual usage
  • Runtime flavor matches workload (
    multi_thread
    for I/O-bound,
    current_thread
    for simpler cases)
  • #[tokio::test]
    used for async tests (not manual runtime construction)
  • Worker thread count configured appropriately for production
  • Cargo.toml中的Tokio特性与实际使用匹配
  • 运行时类型与工作负载匹配(I/O密集型使用
    multi_thread
    ,简单场景使用
    current_thread
  • 异步测试使用
    #[tokio::test]
    (而非手动构造运行时)
  • 生产环境的工作线程数配置合理

Task Management

任务管理

  • spawn
    return values (
    JoinHandle
    ) are tracked, not silently dropped
  • spawn_blocking
    used for CPU-heavy or synchronous I/O operations
  • Tasks respect cancellation (via
    CancellationToken
    ,
    select!
    , or shutdown channels)
  • JoinError
    (task panic or cancellation) is handled, not just unwrapped
  • tokio::select!
    branches are cancellation-safe
  • Native
    async fn
    in traits used instead of
    async-trait
    crate where possible (stable since Rust 1.75)
  • RPIT lifetime capture reviewed in async contexts —
    -> impl Future
    now captures all in-scope lifetimes in edition 2024
  • spawn
    的返回值(
    JoinHandle
    )被跟踪,而非被静默丢弃
  • CPU密集型或同步I/O操作使用
    spawn_blocking
  • 任务遵守取消机制(通过
    CancellationToken
    select!
    或关闭通道)
  • JoinError
    (任务panic或取消)被处理,而非仅unwrap
  • tokio::select!
    分支是可取消安全的
  • 尽可能使用Trait中的原生
    async fn
    而非
    async-trait
    crate(自Rust 1.75起稳定)
  • 审查异步上下文中的RPIT生命周期捕获 — 2024版本中
    -> impl Future
    现在捕获所有作用域内的生命周期

Sync Primitives

同步原语

  • tokio::sync::Mutex
    used when lock is held across
    .await
    ;
    std::sync::Mutex
    for short non-async sections
  • No mutex guard held across await points (deadlock risk)
  • Semaphore
    used for limiting concurrent operations (not ad-hoc counters)
  • RwLock
    used when read-heavy workload (many readers, infrequent writes)
  • Notify
    used for simple signaling (not channel overhead)
  • std::sync::LazyLock
    used instead of
    once_cell::sync::Lazy
    or
    lazy_static!
    for runtime-initialized singletons (stable since Rust 1.80)
  • if let
    lock guard patterns reviewed for edition 2024 temporary scoping — temporaries drop earlier, may change borrow validity
  • 当锁跨
    .await
    持有使用
    tokio::sync::Mutex
    ;短非异步段使用
    std::sync::Mutex
  • 互斥锁守卫不跨await点持有(有死锁风险)
  • 使用
    Semaphore
    限制并发操作(而非临时计数器)
  • 读密集型工作负载使用
    RwLock
    (多读者、少写者)
  • 简单信号传递使用
    Notify
    (避免通道开销)
  • 运行时初始化的单例使用
    std::sync::LazyLock
    而非
    once_cell::sync::Lazy
    lazy_static!
    (自Rust 1.80起稳定)
  • 针对2024版本的临时作用域,审查
    if let
    锁守卫模式 — 临时值销毁更早,可能改变借用有效性

Channels

通道

  • Channel type matches pattern: mpsc for back-pressure, broadcast for fan-out, oneshot for request-response, watch for latest-value
  • Bounded channels have appropriate capacity (not too small = deadlock, not too large = memory)
  • SendError
    /
    RecvError
    handled (indicates other side dropped)
  • Broadcast
    Lagged
    errors handled (receiver fell behind)
  • Channel senders dropped when done to signal completion to receivers
  • 通道类型与模式匹配:mpsc用于背压、broadcast用于扇出、oneshot用于请求响应、watch用于最新值
  • 有界通道容量合理(过小会导致死锁,过大会占用内存)
  • SendError
    /
    RecvError
    被处理(表示另一端已断开)
  • Broadcast的
    Lagged
    错误被处理(接收方落后)
  • 完成后丢弃通道发送方,向接收方发出完成信号

Timer and Sleep

定时器与睡眠

  • tokio::time::sleep
    used instead of
    std::thread::sleep
  • tokio::time::timeout
    wraps operations that could hang
  • tokio::time::interval
    used correctly (
    .tick().await
    for periodic work)
  • 使用
    tokio::time::sleep
    而非
    std::thread::sleep
  • 可能挂起的操作使用
    tokio::time::timeout
    包裹
  • 周期性工作正确使用
    tokio::time::interval
    (使用
    .tick().await

Severity Calibration

严重程度校准

Critical

Critical

  • Blocking I/O (
    std::fs::read
    ,
    std::net::TcpStream
    ) in async context without
    spawn_blocking
  • Mutex guard held across
    .await
    point (deadlock potential)
  • std::thread::sleep
    in async function (blocks runtime thread)
  • Unbounded channel where back-pressure is needed (OOM risk)
  • 异步上下文中无
    spawn_blocking
    的阻塞I/O(
    std::fs::read
    std::net::TcpStream
  • 互斥锁守卫跨
    .await
    点持有(有死锁风险)
  • 异步函数中使用
    std::thread::sleep
    (阻塞运行时线程)
  • 需要背压的场景使用无界通道(有OOM风险)

Major

Major

  • JoinHandle
    silently dropped (lost errors, zombie tasks)
  • Missing
    select!
    cancellation safety consideration
  • Wrong mutex type (std vs tokio) for the use case
  • Missing timeout on network/external operations
  • JoinHandle
    被静默丢弃(丢失错误、僵尸任务)
  • select!
    未考虑取消安全
  • 使用错误的互斥锁类型(std vs tokio)
  • 网络/外部操作缺少超时

Minor

Minor

  • tokio::spawn
    for trivially small async blocks (overhead > benefit)
  • Overly large channel buffer without justification
  • Manual runtime construction where
    #[tokio::main]
    suffices
  • std::sync::Mutex
    where contention is high enough to benefit from tokio's async mutex
  • 对极小的异步块使用
    tokio::spawn
    (开销大于收益)
  • 通道缓冲区过大且无理由
  • 可使用
    #[tokio::main]
    的场景下手动构造运行时
  • 当竞争足够高可从Tokio异步互斥锁受益时仍使用
    std::sync::Mutex

Informational

Informational

  • Suggestions to use
    tokio-util
    utilities (e.g.,
    CancellationToken
    )
  • Tower middleware patterns for service composition
  • Structured concurrency with
    JoinSet
  • Migration from
    async-trait
    crate to native
    async fn
    in traits
  • Migration from
    once_cell
    /
    lazy_static
    to
    std::sync::LazyLock
  • Using
    #[expect(lint)]
    instead of
    #[allow(lint)]
    for self-cleaning suppression
  • 建议使用
    tokio-util
    工具(例如
    CancellationToken
  • 服务组合的Tower中间件模式
  • 使用
    JoinSet
    实现结构化并发
  • async-trait
    crate迁移到Trait中的原生
    async fn
  • once_cell
    /
    lazy_static
    迁移到
    std::sync::LazyLock
  • 使用
    #[expect(lint)]
    而非
    #[allow(lint)]
    实现自清理抑制

Valid Patterns (Do NOT Flag)

有效模式(无需标记)

  • std::sync::Mutex
    for short critical sections
    — tokio docs recommend this when no
    .await
    is inside the lock
  • tokio::spawn
    without explicit join
    — Valid for background tasks with proper shutdown signaling
  • Unbuffered channel capacity of 1 — Valid for synchronization barriers
  • #[tokio::main(flavor = "current_thread")]
    in simple binaries
    — Not every app needs multi-thread runtime
  • clone()
    on
    Arc<T>
    before
    spawn
    — Required for moving into tasks, not unnecessary cloning
  • Large broadcast channel capacity — Valid when lagged errors are expensive (event sourcing)
  • Native
    async fn
    in traits without
    async-trait
    — Stable since 1.75; the crate is still valid for
    dyn
    dispatch cases
  • + use<'a>
    on
    -> impl Future
    returns
    — Correct edition 2024 precise capture syntax to limit lifetime capture
  • #[expect(clippy::type_complexity)]
    on complex async types
    — Self-cleaning alternative to
    #[allow]
    , warns when suppression is no longer needed
  • 短临界区使用
    std::sync::Mutex
    — Tokio文档推荐在锁内无
    .await
    时使用
  • tokio::spawn
    不显式join
    — 带有正确关闭信号的后台任务是有效的
  • 容量为1的无缓冲通道 — 同步屏障的有效模式
  • 简单二进制文件中使用
    #[tokio::main(flavor = "current_thread")]
    — 并非每个应用都需要多线程运行时
  • spawn
    前对
    Arc<T>
    调用
    clone()
    — 移入任务所需,并非不必要的克隆
  • 大容量broadcast通道 — 当滞后错误代价高昂时有效(例如事件溯源)
  • Trait中使用原生
    async fn
    而非
    async-trait
    — 自1.75起稳定;
    dyn
    分发场景仍需使用该crate
  • -> impl Future
    返回值使用
    + use<'a>
    — 2024版本中限制生命周期捕获的精确语法
  • 复杂异步类型使用
    #[expect(clippy::type_complexity)]
    #[allow]
    的自清理替代方案,当抑制不再需要时发出警告

Before Submitting Findings

提交审查结果前

Load and follow
beagle-rust:review-verification-protocol
before reporting any issue.
<!-- cross-ref:start -->
在报告任何问题前,加载并遵循
beagle-rust:review-verification-protocol
<!-- cross-ref:start -->

See also (related skills — Code review family)

另请参阅(相关技能 — 代码审查系列)

If your issue relates to:
  • CodeRabbit-powered review (default) — check
    code-review
    if appropriate.
  • auto-apply CodeRabbit review comments — check
    autofix
    if appropriate.
  • Python + pytest review (type safety, async, fixtures) — check
    python-code-review
    if appropriate.
  • Rust source review — check
    rust-code-review
    if appropriate.
  • Rust test review — check
    rust-testing-code-review
    if appropriate.
  • Rust FFI review — check
    ffi-code-review
    if appropriate.
  • Deep Agents code review — check
    deepagents-code-review
    if appropriate.
  • SQLAlchemy 2.0 review — check
    sqlalchemy-code-review
    if appropriate.
<!-- cross-ref:end -->
如果你的问题涉及:
  • CodeRabbit驱动的审查(默认) — 若合适,请查看
    code-review
  • 自动应用CodeRabbit审查评论 — 若合适,请查看
    autofix
  • Python + pytest审查(类型安全、异步、fixtures) — 若合适,请查看
    python-code-review
  • Rust源代码审查 — 若合适,请查看
    rust-code-review
  • Rust测试代码审查 — 若合适,请查看
    rust-testing-code-review
  • Rust FFI审查 — 若合适,请查看
    ffi-code-review
  • Deep Agents代码审查 — 若合适,请查看
    deepagents-code-review
  • SQLAlchemy 2.0审查 — 若合适,请查看
    sqlalchemy-code-review
<!-- cross-ref:end -->

FFI review

FFI审查

FFI Code Review

FFI代码审查

Review Workflow

审查流程

  1. Check Cargo.toml -- Note Rust edition (2024 has breaking changes to extern blocks and unsafe attributes),
    build-dependencies
    (bindgen, cc, pkg-config),
    crate-type
    (
    cdylib
    ,
    staticlib
    ), and
    links
    key
  2. Check build.rs -- Verify link directives (
    cargo:rustc-link-lib
    ,
    cargo:rustc-link-search
    ), bindgen configuration, and C source compilation
  3. Check extern blocks -- Verify calling conventions, symbol declarations, and safety annotations
  4. Check type layout -- Every type crossing FFI must be
    #[repr(C)]
    or a primitive FFI type
  5. Check string and pointer handling -- CStr/CString usage, null checks, ownership transfers
  6. Check callbacks --
    extern "C" fn
    pointers, panic safety across FFI boundary
  7. Verify before reporting -- Load
    beagle-rust:review-verification-protocol
    before submitting findings
  1. 检查Cargo.toml — 记录Rust版本(2024版本对extern块和unsafe属性有破坏性变更)、
    build-dependencies
    (bindgen、cc、pkg-config)、
    crate-type
    cdylib
    staticlib
    )和
    links
  2. 检查build.rs — 验证链接指令(
    cargo:rustc-link-lib
    cargo:rustc-link-search
    )、bindgen配置和C源代码编译
  3. 检查extern块 — 验证调用约定、符号声明和安全注解
  4. 检查类型布局 — 跨FFI的每个类型必须为
    #[repr(C)]
    或原生FFI类型
  5. 检查字符串和指针处理 — CStr/CString使用、空指针检查、所有权转移
  6. 检查回调
    extern "C" fn
    指针、跨FFI边界的panic安全
  7. 报告前验证 — 在提交审查结果前,加载
    beagle-rust:review-verification-protocol

Output Format

输出格式

Report findings as:
text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.
按以下格式报告问题:
text
[文件:行号] 问题标题
严重程度: Critical | Major | Minor | Informational
问题描述及其影响。

Quick Reference

快速参考

Issue TypeReference
C-to-Rust type mapping, repr(C) layout, enums, opaque typesreferences/type-mapping.md
Safe wrappers, ownership transfer, callbacks, build.rs, testingreferences/safety-patterns.md
问题类型参考文档
C到Rust类型映射、repr(C)布局、枚举、不透明类型references/type-mapping.md
安全包装、所有权转移、回调、build.rs、测试references/safety-patterns.md

Review Checklist

审查清单

extern Blocks and Calling Conventions

extern块与调用约定

  • Foreign function declarations use
    extern "C"
    (explicit, not bare
    extern
    )
  • Edition 2024:
    extern "C" {}
    blocks written as
    unsafe extern "C" {}
  • Functions exposed to C use
    extern "C" fn
    (not default Rust calling convention)
  • Calling convention matches the foreign library (
    "C"
    ,
    "system"
    for Win32 API)
  • #[link(name = "...")]
    specifies the correct library name
  • #[link(name = "...", kind = "static")]
    used when statically linking
  • 外部函数声明使用
    extern "C"
    (显式,而非裸
    extern
  • 2024版本
    extern "C" {}
    块需写成
    unsafe extern "C" {}
  • 暴露给C的函数使用
    extern "C" fn
    (而非默认Rust调用约定)
  • 调用约定与外部库匹配(
    "C"
    、Win32 API使用
    "system"
  • #[link(name = "...")]
    指定正确的库名称
  • 静态链接时使用
    #[link(name = "...", kind = "static")]

Symbol Management

符号管理

  • Exported functions use
    #[no_mangle]
    to preserve symbol names
  • Edition 2024:
    #[no_mangle]
    written as
    #[unsafe(no_mangle)]
  • Edition 2024:
    #[export_name = "..."]
    written as
    #[unsafe(export_name = "...")]
  • #[link_name = "..."]
    used when Rust name differs from C symbol
  • Exported items are
    pub
    (only public
    #[no_mangle]
    symbols appear in library output)
  • 导出函数使用
    #[no_mangle]
    保留符号名称
  • 2024版本
    #[no_mangle]
    需写成
    #[unsafe(no_mangle)]
  • 2024版本
    #[export_name = "..."]
    需写成
    #[unsafe(export_name = "...")]
  • 当Rust名称与C符号不同时使用
    #[link_name = "..."]
  • 导出项为
    pub
    (仅公共
    #[no_mangle]
    符号会出现在库输出中)

Type Layout

类型布局

  • Every struct/union crossing FFI has
    #[repr(C)]
    -- Rust's default layout is undefined
  • Primitive types use
    std::ffi
    /
    std::os::raw
    equivalents (
    c_int
    ,
    c_char
    ,
    c_void
    )
  • No bare
    i32
    where C uses
    int
    -- use
    c_int
    (width varies by platform)
  • Quirky C types like
    __be32
    use byte arrays (
    [u8; 4]
    ), not Rust integers
  • Enums crossing FFI use
    #[repr(C)]
    or
    #[repr(u8)]
    /
    #[repr(u32)]
    with explicit discriminants
  • C-style bitflag enums use a newtype around an integer (or
    bitflags
    crate), not a Rust enum
  • #[non_exhaustive]
    on enums representing C enumerations that may gain new values
  • 跨FFI的每个结构体/联合体都带有
    #[repr(C)]
    — Rust默认布局未定义
  • 原生类型使用
    std::ffi
    /
    std::os::raw
    等效类型(
    c_int
    c_char
    c_void
  • C使用
    int
    时不使用裸
    i32
    — 使用
    c_int
    (宽度因平台而异)
  • 特殊C类型如
    __be32
    使用字节数组(
    [u8; 4]
    ),而非Rust整数
  • 跨FFI的枚举使用
    #[repr(C)]
    或带显式判别式的
    #[repr(u8)]
    /
    #[repr(u32)]
  • C风格位标志枚举使用整数的Newtype(或
    bitflags
    crate),而非Rust枚举
  • 代表C枚举且可能新增值的枚举使用
    #[non_exhaustive]

String Handling

字符串处理

  • C strings use
    CStr
    (borrowed) or
    CString
    (owned), never
    &str
    or
    String
  • CString::new()
    result is checked for interior null bytes (returns
    Err
    on
    \0
    )
  • CString
    outlives any
    *const c_char
    pointer derived from it via
    .as_ptr()
  • Incoming
    *const c_char
    validated with
    CStr::from_ptr()
    inside
    unsafe
  • No assumption that C strings are valid UTF-8 -- use
    to_str()
    which returns
    Result
  • OS paths use
    OsStr
    /
    OsString
    and
    CStr
    , not
    &str
  • C字符串使用
    CStr
    (借用)或
    CString
    (自有),绝不使用
    &str
    String
  • 检查
    CString::new()
    的结果是否包含内部空字节(遇到
    \0
    返回
    Err
  • CString
    的生命周期长于通过
    .as_ptr()
    派生的
    *const c_char
    指针
  • 传入的
    *const c_char
    unsafe
    内通过
    CStr::from_ptr()
    验证
  • 不假设C字符串为有效UTF-8 — 使用
    to_str()
    返回
    Result
  • OS路径使用
    OsStr
    /
    OsString
    CStr
    ,而非
    &str

Ownership and Allocation

所有权与分配

  • Clear ownership contract: who allocates, who frees
  • Rust-allocated memory freed by Rust (
    Box::from_raw
    ), C-allocated freed by C
  • Box::into_raw
    /
    Box::from_raw
    paired correctly for heap transfers
  • Vec::into_raw_parts
    used when passing arrays to C (pointer + length + capacity)
  • Destructor functions exposed for every opaque Rust type given to C
  • No
    Drop
    running on C-allocated memory (and vice versa)
  • 明确所有权契约:谁分配,谁释放
  • Rust分配的内存由Rust释放(
    Box::from_raw
    ),C分配的由C释放
  • Box::into_raw
    /
    Box::from_raw
    正确配对以实现堆内存转移
  • 向C传递数组时使用
    Vec::into_raw_parts
    (指针+长度+容量)
  • 为每个提供给C的不透明Rust类型暴露析构函数
  • C分配的内存不会运行Rust的
    Drop
    (反之亦然)

Callbacks

回调

  • Callback types are
    extern "C" fn(...)
    , not closures or
    fn(...)
  • Callbacks use
    std::panic::catch_unwind
    to prevent panics from unwinding across FFI
  • Callback context passed as
    *mut c_void
    with safe reconstruction at call site
  • Option<extern "C" fn(...)>
    used for nullable function pointers (niche optimization)
  • 回调类型为
    extern "C" fn(...)
    ,而非闭包或
    fn(...)
  • 回调使用
    std::panic::catch_unwind
    防止panic跨FFI边界展开
  • 回调上下文以
    *mut c_void
    传递,并在调用点安全重构
  • 可空函数指针使用
    Option<extern "C" fn(...)>
    ( niche优化)

Bindgen and Build Scripts

Bindgen与构建脚本

  • Bindgen output reviewed for correctness (auto-generated types may need adjustment)
  • -sys
    crate pattern used for raw bindings, separate crate for safe wrappers
  • build.rs
    uses
    cargo:rustc-link-lib
    and
    cargo:rustc-link-search
    correctly
  • links
    key in
    Cargo.toml
    prevents duplicate linking of the same native library
  • Platform-specific bindings generated per-build (not checked in for a single platform)
  • 审查Bindgen输出的正确性(自动生成的类型可能需要调整)
  • 使用
    -sys
    crate模式处理原始绑定,单独的crate处理安全包装
  • build.rs
    正确使用
    cargo:rustc-link-lib
    cargo:rustc-link-search
  • Cargo.toml中的
    links
    键防止重复链接同一原生库
  • 按构建生成特定平台的绑定(而非仅为单一平台提交绑定)

Safety Documentation

安全文档

  • Every
    unsafe
    block has a
    // SAFETY:
    comment explaining invariants
  • Every public FFI wrapper function documents safety requirements
  • Edition 2024:
    unsafe fn
    bodies use explicit
    unsafe {}
    blocks around unsafe ops
  • 每个
    unsafe
    块都带有
    // SAFETY:
    注释解释不变量
  • 每个公共FFI包装函数都记录安全要求
  • 2024版本
    unsafe fn
    主体在不安全操作周围使用显式
    unsafe {}

Severity Calibration

严重程度校准

Critical (Block Merge)

Critical(阻止合并)

  • Missing
    #[repr(C)]
    on types crossing FFI boundary (undefined memory layout)
  • Wrong string handling:
    &str
    /
    String
    where
    CStr
    /
    CString
    required
  • Ownership confusion: freeing C-allocated memory with Rust's allocator (or vice versa)
  • Panic unwinding across FFI boundary without
    catch_unwind
  • Using Rust enum for C bitflags (invalid discriminant = undefined behavior)
  • Passing closure where
    extern "C" fn
    pointer required
  • 跨FFI边界的类型缺少
    #[repr(C)]
    (内存布局未定义)
  • 字符串处理错误:需要
    CStr
    /
    CString
    时使用
    &str
    /
    String
  • 所有权混淆:用Rust分配器释放C分配的内存(反之亦然)
  • catch_unwind
    时panic跨FFI边界展开
  • 使用Rust枚举表示C位标志(无效判别式导致未定义行为)
  • 需要
    extern "C" fn
    指针时传递闭包

Major (Should Fix)

Major(应修复)

  • Missing safety documentation on
    unsafe
    blocks or public FFI functions
  • No null pointer check on incoming
    *const T
    /
    *mut T
    before dereferencing
  • CString
    dropped before its pointer is used by C (dangling pointer)
  • Missing
    #[link(name = "...")]
    causing link failures on some platforms
  • Edition 2024:
    extern
    block not marked
    unsafe extern
  • Edition 2024:
    #[no_mangle]
    not wrapped in
    #[unsafe(...)]
  • unsafe
    块或公共FFI函数缺少安全文档
  • 传入的
    *const T
    /
    *mut T
    解引用前未做空指针检查
  • CString
    在C使用其指针前被销毁(悬垂指针)
  • 缺少
    #[link(name = "...")]
    导致部分平台链接失败
  • 2024版本
    extern
    块未标记
    unsafe extern
  • 2024版本
    #[no_mangle]
    未包装在
    #[unsafe(...)]

Minor (Consider Fixing)

Minor(考虑修复)

  • Using
    i32
    instead of
    c_int
    for C
    int
    (correct on most platforms but not portable)
  • Missing
    #[non_exhaustive]
    on enums mapping to extensible C enumerations
  • Verbose manual bindings where bindgen would be more maintainable
  • Checked-in bindings without platform guards
  • C使用
    int
    时使用
    i32
    而非
    c_int
    (多数平台正确但不具可移植性)
  • 映射到可扩展C枚举的枚举缺少
    #[non_exhaustive]
  • 可使用bindgen的场景下使用冗长的手动绑定
  • 提交的绑定无平台守卫

Informational

Informational

  • Suggestions to split raw bindings into a
    -sys
    crate
  • Suggestions to add opaque wrapper types for distinct
    *mut c_void
    pointers
  • Suggestions to use
    Option<NonNull<T>>
    for nullable pointers
  • 建议将原始绑定拆分为
    -sys
    crate
  • 建议为不同的
    *mut c_void
    指针添加不透明包装类型
  • 建议使用
    Option<NonNull<T>>
    处理可空指针

Valid Patterns (Do NOT Flag)

有效模式(无需标记)

  • unsafe extern "C" {}
    in edition 2024
    -- correct form for foreign declarations
  • #[unsafe(no_mangle)]
    in edition 2024
    -- correct form for symbol export
  • Option<extern "C" fn(...)>
    for nullable callbacks
    -- niche optimization guaranteed
  • Option<NonNull<T>>
    for nullable pointers
    -- zero-cost nullable pointer pattern
  • *mut c_void
    for opaque C types
    -- standard when internal layout is irrelevant
  • Distinct empty structs wrapping
    c_void
    for type-safe opaque pointers
    -- prevents pointer confusion
  • CStr::from_bytes_with_nul_unchecked
    with compile-time literal
    -- safe when literal is known null-terminated
  • extern "C-unwind"
    for controlled unwinding
    -- valid per RFC 2945
  • include!(concat!(env!("OUT_DIR"), "/bindings.rs"))
    in bindgen crates
    -- standard pattern
  • Box::into_raw
    /
    Box::from_raw
    pairs for ownership transfer
    -- correct pattern when paired
  • 2024版本中的
    unsafe extern "C" {}
    — 外部声明的正确形式
  • 2024版本中的
    #[unsafe(no_mangle)]
    — 符号导出的正确形式
  • 可空回调使用
    Option<extern "C" fn(...)>
    — 保证niche优化
  • 可空指针使用
    Option<NonNull<T>>
    — 零成本可空指针模式
  • 不透明C类型使用
    *mut c_void
    — 内部布局无关时的标准做法
  • 包装
    c_void
    的不同空结构体用于类型安全的不透明指针
    — 防止指针混淆
  • 编译时常量使用
    CStr::from_bytes_with_nul_unchecked
    — 已知常量以空字符结尾时安全
  • 受控展开使用
    extern "C-unwind"
    — 符合RFC 2945
  • Bindgen crate中使用
    include!(concat!(env!("OUT_DIR"), "/bindings.rs"))
    — 标准模式
  • 所有权转移使用
    Box::into_raw
    /
    Box::from_raw
    配对
    — 配对时的正确模式

Before Submitting Findings

提交审查结果前

Load and follow
beagle-rust:review-verification-protocol
before reporting any issue.
<!-- cross-ref:start -->
在报告任何问题前,加载并遵循
beagle-rust:review-verification-protocol
<!-- cross-ref:start -->

See also (related skills — Code review family)

另请参阅(相关技能 — 代码审查系列)

If your issue relates to:
  • CodeRabbit-powered review (default) — check
    code-review
    if appropriate.
  • auto-apply CodeRabbit review comments — check
    autofix
    if appropriate.
  • Python + pytest review (type safety, async, fixtures) — check
    python-code-review
    if appropriate.
  • Rust source review — check
    rust-code-review
    if appropriate.
  • Rust test review — check
    rust-testing-code-review
    if appropriate.
  • tokio async review — check
    tokio-async-code-review
    if appropriate.
  • Deep Agents code review — check
    deepagents-code-review
    if appropriate.
  • SQLAlchemy 2.0 review — check
    sqlalchemy-code-review
    if appropriate.
<!-- cross-ref:end -->
如果你的问题涉及:
  • CodeRabbit驱动的审查(默认) — 若合适,请查看
    code-review
  • 自动应用CodeRabbit审查评论 — 若合适,请查看
    autofix
  • Python + pytest审查(类型安全、异步、fixtures) — 若合适,请查看
    python-code-review
  • Rust源代码审查 — 若合适,请查看
    rust-code-review
  • Rust测试代码审查 — 若合适,请查看
    rust-testing-code-review
  • Tokio异步审查 — 若合适,请查看
    tokio-async-code-review
  • Deep Agents代码审查 — 若合适,请查看
    deepagents-code-review
  • SQLAlchemy 2.0审查 — 若合适,请查看
    sqlalchemy-code-review
<!-- cross-ref:end -->