/rewrite-rs-skills:unsafe-rustfrom rewrite-rs-skills
Justifies, documents, and verifies unsafe Rust code — safety invariants on every unsafe block, sound safe wrappers, undefined behaviour hazards, and Miri verification. Use when writing or reviewing unsafe code, FFI boundaries, raw pointers, transmute, or safe wrappers around unsafe primitives.
Ships in rewrite-rs-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
unsafe is a promise, not a permission: the code inside may break the rules,
but the code around it must keep them. unsafe means undefined behaviour, not
"dangerous" — UB is the compiler being permitted to assume the situation
cannot arise, which is why it surfaces as a later, unrelated miscompile. The
depth is in SAFETY-REVIEW.md under UB is not a bad outcome at runtime.
This skill governs soundness — whether a safe caller can trigger undefined
behaviour — and it never treats "the tests pass" as evidence of soundness.
unsafe does not turn off the borrow checkerIt permits exactly five extra operations: dereferencing a raw pointer, calling
an unsafe fn, implementing an unsafe trait, accessing a union field, and
mutating a static mut. Everything else — lifetimes, ownership, types — still
applies inside the block. unsafe is a narrow escape hatch — reaching for it
to resolve a borrow error is always wrong. That case is /ownership-not-clone.
unsafe is justified for exactly three reasons. Each has a question that must
be answered before the block is written — and the reason written down, in the
// SAFETY: comment or the PR description, not remembered by whoever wrote it.
/rust-ffi.
Use the edition 2024 marks on the boundary — those attributes always were
unsafe assertions; they are in SAFETY-REVIEW.md under Per FFI call./rust-performance
first, and the answer there is usually that the allocation was the problem.A block that does not sit under one of these three has an author reaching for
unsafe to make an error go away, and the error was right.
unsafe block carries a // SAFETY: commentThe comment states the invariant the caller upholds, not what the code does:
// SAFETY: `ptr` came from `Vec::as_mut_ptr` on a vec of at least `len`
// elements that is still alive for this scope, and no other reference to it
// exists here.
let slice = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
And every pub unsafe fn carries a # Safety doc section stating what the
caller must guarantee. clippy::undocumented_unsafe_blocks and
clippy::missing_safety_doc are the mechanical check for the two rules:
propose them for the repo lint config, never override a level the repo already
set.
A safe API is sound when no safe caller can trigger undefined behaviour, for
any input, including malicious ones. Unsound code is never acceptable: there is
no "unsound but only in a case that cannot happen here". Soundness belongs
to the API, so a safe function that lets safe caller code reach UB is a bug
whoever calls it today; fix it, or mark it unsafe fn. The encapsulation rule: keep the unsafe block as small as it can
be, and put the safe/unsafe boundary where the invariant is actually
enforceable — the check belongs in the safe code that guards the block, not in
the block itself. Inside the block, assume the code you call misbehaves — the
depth is in SAFETY-REVIEW.md.
The unit of soundness is the module. Fields and helpers private to a module
cannot be touched by outside code, so the module is where an invariant can be
defended: choose the narrowest module that is still able to guarantee the
invariant, put the unsafe there, and expose only a safe interface. String is the model — a Vec<u8> whose
private field and safe methods keep the bytes valid UTF-8, so safe callers
cannot break the invariant the unchecked internals rely on. When the
invariant is large or the dependencies many, isolate the code in its own small
crate with few dependencies, so the audit surface is a short list of files.
One point each; the review depth is in SAFETY-REVIEW.md.
&mut coexisting with any other live reference to the same
place.MaybeUninit<T>,
never mem::zeroed(): zero is a valid u32 and an invalid &T, bool, or
enum — and the invalidity is instant UB, not a bad value you will notice.bool that is not 0 or 1, a char outside the scalar
ranges, a null reference.transmute: between types with different layouts, or without
#[repr(C)]/#[repr(transparent)] pinning the layout. Two uses are off
the table outright: casting an integer to an enum through transmute (a
value with no variant is instant UB; use a TryFrom or a match), and
stretching a lifetime with transmute to make a borrow check pass (the
checker was right; restructure the ownership).bytemuck for plain-old-data casts, zerocopy for zero-copy parsing,
arrayvec/smallvec for stack-backed collections, an existing binding crate
for an existing C library. Auditing unsafe you did not write is cheaper than
justifying it — the audit is the published, reviewed one.
The same reasoning rules out unsafe impl Send or Sync used to silence a
bound the compiler reported. If a type holding a raw pointer or an Rc is
rejected by a Send requirement, the type is the problem; a hand-written
impl is for a type whose fields really are safe to move across threads, with
the argument in a comment (SAFETY-REVIEW.md, per hand-written impl).
Whether the wrapper should be pub, and what its unsafe fn signature commits
the crate to, is /rust-api-design. Pin and manual Future impls interact
with /async-rust. Error handling across the boundary is /rust-errors.
Construct-level mapping from C or C++ into Rust is /port-from-c and
/port-from-cpp — this skill covers the unsafe discipline, not the mapping.
New unsafe abstractions get more testing than ordinary code, because the
compiler is not helping. Write tests that act as adversarial callers: pass
boundary values and zero-length input, a closure that panics halfway, a trait
impl that lies (a Deref that changes its answer, a Clone that panics),
and drop order that surprises. Run them under Miri below.
cargo miri test # requires the miri component on nightly
cargo clippy --all-targets # add -- -D warnings only if the repo has no lint config
cargo test
If cargo miri is unavailable, say so explicitly in the report rather than
silently skipping it, and do not install a nightly toolchain into the user
environment as a side effect. State the Miri limitations plainly so the result
is not over-read: it does not execute FFI calls into real C code, it only
checks the paths the tests actually exercise, and it is slow enough that
targeting the relevant test — cargo miri test <filter> — is usually the
practical move. For the FFI side Miri cannot reach, the routes are
-Zmiri-strict-provenance for pointer provenance and the address sanitizer for
what a real C library does with the memory.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
28 skills in this plugin
/async-rustWrite correct async Rust — runtime choice, Send and Sync bounds, cancellation safety, blocking work inside async contexts, and shared state across tasks. Use when writing or reviewing async code, when a future is held across an await point, when the user hits a Send bound error on a spawned task, when a runtime stalls or deadlocks, or when the user asks about tokio, select!, or spawn_blocking./idiomatic-rustWrite Rust that reads like Rust — iterator pipelines over index loops, From/Into over ad-hoc converters, derives over hand-written impls, newtypes over bare primitives. Use when writing new Rust, when reviewing Rust that reads like a translation from another language, when reaching for a classic design pattern (strategy, command, visitor) or a try/finally cleanup in Rust, when naming a constructor, accessor, iterator, or error type, or when the user asks how to make Rust code more idiomatic or less repetitive./ownership-not-cloneUse ownership and borrowing instead of reaching for clone, Rc, RefCell, or Arc<Mutex<_>> to silence the borrow checker. Every clone must be explainable. Use when code clones to make an error go away, when a borrow-checker fight is being resolved by copying data, when reviewing Rust dense with .clone() or Rc<RefCell<_>>, or when the user asks whether a clone is necessary./port-from-cPort C into Rust — recovering the ownership, lifetime, nullability, and length that C never recorded, mapping pointers to references and slices, tag-plus-union to enums, return codes and errno to Result, and linking Rust into the existing build with bindgen and cbindgen. Use when porting, rewriting, or migrating C, a C library, firmware, or a C application into Rust, when replacing C modules one at a time behind the existing build, or when the user asks how a C construct such as malloc, a char pointer, a union, or a preprocessor macro translates to Rust./port-from-cppPort C++ into Rust — RAII and smart pointers onto ownership, templates onto generics and traits, exceptions onto Result, the STL onto Rust collections, and the traps (move semantics, implicit conversions, undefined behaviour, iterator invalidation). Use when porting, rewriting, or migrating C++, a C++ library, or a C++ application into Rust, when replacing a C++ module with Rust behind the existing build, or when the user asks how a C++ construct such as unique_ptr, shared_ptr, a template, or an STL container translates to Rust./port-from-goPort Go into Rust — goroutines and channels onto tasks and async, interfaces onto traits, error values onto Result, and the value-semantics traps (zero values, integer wraparound, slice aliasing, nil). Use when porting, rewriting, or migrating Go, Golang, a Go service, or a Go CLI into Rust, when replacing a Go component with a Rust one behind the same interface, or when the user asks how a Go construct translates to Rust.npx claudepluginhub rewrite-rs/skills --plugin rewrite-rs-skillsOther plugins' skills for the same job