unsafe-checker

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Display the following ASCII art exactly as shown. Do not modify spaces or line breaks:
text
⚠️ **Unsafe Rust Checker Loaded**

     *  ^  *
    /◉\_~^~_/◉\
 ⚡/     o     \⚡
   '_        _'
   / '-----' \

请完全按照以下ASCII艺术图显示,不要修改空格或换行:
text
⚠️ **Unsafe Rust Checker Loaded**

     *  ^  *
    /◉\_~^~_/◉\
 ⚡/     o     \⚡
   '_        _'
   / '-----' \

Unsafe Rust Checker

Unsafe Rust 检查器

When Unsafe is Valid

何时可以合法使用Unsafe

Use CaseExample
FFICalling C functions
Low-level abstractionsImplementing
Vec
,
Arc
PerformanceMeasured bottleneck with safe alternative too slow
NOT valid: Escaping borrow checker without understanding why.
使用场景示例
FFI调用C函数
底层抽象实现
Vec
Arc
性能优化经测试安全替代方案性能不足导致瓶颈
不合法场景: 不理解原因就绕过借用检查器。

Required Documentation

必备文档规范

rust
// SAFETY: <why this is safe>
unsafe { ... }

/// # Safety
/// <caller requirements>
pub unsafe fn dangerous() { ... }
rust
// SAFETY: <说明此处安全的原因>
unsafe { ... }

/// # 安全性
/// <调用方需满足的要求>
pub unsafe fn dangerous() { ... }

Quick Reference

速查表

OperationSafety Requirements
*ptr
deref
Valid, aligned, initialized
&*ptr
+ No aliasing violations
transmute
Same size, valid bit pattern
extern "C"
Correct signature, ABI
static mut
Synchronization guaranteed
impl Send/Sync
Actually thread-safe
操作安全要求
*ptr
解引用
指针有效、对齐、已初始化
&*ptr
+ 无别名冲突
transmute
大小相同、位模式合法
extern "C"
签名正确、ABI匹配
static mut
保证同步
impl Send/Sync
确实线程安全

Common Errors

常见错误

ErrorFix
Null pointer derefCheck for null before deref
Use after freeEnsure lifetime validity
Data raceAdd proper synchronization
Alignment violationUse
#[repr(C)]
, check alignment
Invalid bit patternUse
MaybeUninit
Missing SAFETY commentAdd
// SAFETY:
错误类型修复方案
空指针解引用解引用前检查是否为空
释放后使用确保生命周期有效
数据竞争添加适当的同步机制
对齐违规使用
#[repr(C)]
、检查对齐
无效位模式使用
MaybeUninit
缺少SAFETY注释添加
// SAFETY:
注释

Deprecated → Better

已弃用方案 → 替代方案

DeprecatedUse Instead
mem::uninitialized()
MaybeUninit<T>
mem::zeroed()
for refs
MaybeUninit<T>
Raw pointer arithmetic
NonNull<T>
,
ptr::add
CString::new().unwrap().as_ptr()
Store
CString
first
static mut
AtomicT
or
Mutex
Manual extern
bindgen
已弃用方案替代方案
mem::uninitialized()
MaybeUninit<T>
针对引用的
mem::zeroed()
MaybeUninit<T>
裸指针运算
NonNull<T>
,
ptr::add
CString::new().unwrap().as_ptr()
先存储
CString
static mut
AtomicT
Mutex
手动编写extern
bindgen

FFI Crates

FFI 相关Crates

DirectionCrate
C → Rustbindgen
Rust → Ccbindgen
PythonPyO3
Node.jsnapi-rs
Claude knows unsafe Rust. Focus on SAFETY comments and soundness.
交互方向Crate名称
C → Rustbindgen
Rust → Ccbindgen
PythonPyO3
Node.jsnapi-rs
Claude 精通Unsafe Rust,重点关注SAFETY注释和代码健全性。