Patterns for unsafe Rust: minimize and encapsulate unsafe, document SAFETY invariants, use MaybeUninit and Pin correctly, and test with Miri.
.cursor/rules/rust-memory-safety-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Patterns for unsafe Rust: minimize and encapsulate unsafe, document SAFETY invariants, use MaybeUninit and Pin correctly, and test with Miri."
globs: "**/*"
alwaysApply: false
---
Apply these rules whenever code uses or touches `unsafe` Rust.
## Minimize unsafe
- Write safe Rust first. Use `unsafe` only for FFI, hardware/OS interfaces or a measured performance need that safe code cannot meet.
- Add `#![forbid(unsafe_code)]` to crates that do not need unsafe, so it cannot be introduced by accident.
- Keep each `unsafe` block as small as possible and wrap it in a safe function or type whose public API cannot be used to cause undefined behaviour.
## Document invariants
- Put a `// SAFETY:` comment on every `unsafe` block explaining why each requirement of the unsafe operation holds. Enable Clippy's `undocumented_unsafe_blocks` lint.
- Every `unsafe fn` needs a `# Safety` doc section listing what callers must guarantee. Inside `unsafe fn`, still wrap unsafe operations in explicit `unsafe {}` blocks (the `unsafe_op_in_unsafe_fn` lint warns by default in the 2024 edition).
## Validate at the boundary
- Check pointer non-null, alignment, length and lifetime before turning raw pointers into references or slices. Validate data from FFI (lengths, UTF-8, enum discriminants) before trusting it.
## Uninitialized memory
- Use `MaybeUninit<T>`; never `mem::uninitialized()` or `mem::zeroed()` for types where all-zero is not a valid value. Only call `assume_init` after every byte that matters has been written.
## Drop
- Implement `Drop` only for types that own a resource. In types that manage raw allocations, make sure `Drop` frees exactly once, and consider what happens if a destructor panics.
## Pin
- Use `Pin` for values that must not move after creation, such as self-referential structs and hand-written futures. Prefer `std::pin::pin!` or `Box::pin`, and use the `pin-project` (or `pin-project-lite`) crate for field projections instead of hand-written unsafe projections.
## Testing
- Run tests that exercise unsafe code under Miri (`cargo +nightly miri test`), which detects many kinds of undefined behaviour such as out-of-bounds access, use-after-free and invalid aliasing. Miri runs on nightly and cannot run FFI calls, so isolate pure-Rust unsafe code to test it.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A crate reads a C struct through FFI and builds a &[u8] from a pointer and length without checks; some unsafe blocks have no explanation.
Apply the Rust Memory Safety Patterns rule to src/ffi.rs and suggest how to test it.
A safe wrapper function that checks null and length before slice::from_raw_parts, // SAFETY: comments on each unsafe block, a # Safety section on any remaining unsafe fn, MaybeUninit for out-parameters, and a plan to run the pure-Rust parts under cargo +nightly miri test.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/rust-memory-safety-patterns.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Rust Memory Safety Patterns project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules whenever code uses or touches `unsafe` Rust.
## Minimize unsafe
- Write safe Rust first. Use `unsafe` only for FFI, hardware/OS interfaces or a measured performance need that safe code cannot meet.
- Add `#![forbid(unsafe_code)]` to crates that do not need unsafe, so it cannot be introduced by accident.
- Keep each `unsafe` block as small as possible and wrap it in a safe function or type whose public API cannot be used to cause undefined behaviour.
## Document invariants
- Put a `// SAFETY:` comment on every `unsafe` block explaining why each requirement of the unsafe operation holds. Enable Clippy's `undocumented_unsafe_blocks` lint.
- Every `unsafe fn` needs a `# Safety` doc section listing what callers must guarantee. Inside `unsafe fn`, still wrap unsafe operations in explicit `unsafe {}` blocks (the `unsafe_op_in_unsafe_fn` lint warns by default in the 2024 edition).
## Validate at the boundary
- Check pointer non-null, alignment, length and lifetime before turning raw pointers into references or slices. Validate data from FFI (lengths, UTF-8, enum discriminants) before trusting it.
## Uninitialized memory
- Use `MaybeUninit<T>`; never `mem::uninitialized()` or `mem::zeroed()` for types where all-zero is not a valid value. Only call `assume_init` after every byte that matters has been written.
## Drop
- Implement `Drop` only for types that own a resource. In types that manage raw allocations, make sure `Drop` frees exactly once, and consider what happens if a destructor panics.
## Pin
- Use `Pin` for values that must not move after creation, such as self-referential structs and hand-written futures. Prefer `std::pin::pin!` or `Box::pin`, and use the `pin-project` (or `pin-project-lite`) crate for field projections instead of hand-written unsafe projections.
## Testing
- Run tests that exercise unsafe code under Miri (`cargo +nightly miri test`), which detects many kinds of undefined behaviour such as out-of-bounds access, use-after-free and invalid aliasing. Miri runs on nightly and cannot run FFI calls, so isolate pure-Rust unsafe code to test it.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.