rust-performance

A set of rules for writing faster and safer Rust code, including guidance on memory use, concurrency, benchmarking, and limited use of unsafe code.

In plain words
What is it for?
It guides Rust performance improvements, concurrent and parallel code, memory layout decisions, benchmarking, and type-based memory-safety practices.
Why use it?
It gives consistent checks for performance and safety decisions while helping avoid unnecessary complexity or premature optimization.

Cursor rule for Cursor

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/wangqiqi/cursor-ai-rules/rust-performance
Clone the repo
git clone --depth 1 https://github.com/wangqiqi/cursor-ai-rules

Made for: Cursor.

Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 2,296 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.02296
Opus 5 $0.00000 $0.01148
Sonnet 5 $0.00000 $0.00459
Haiku 4.5 $0.00000 $0.00230

Measured 2d ago against content hash c8276fa07000, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

rust-performance scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.cursor/rules/tech/rust-performance.mdc · 383 lines

How it starts

The opening of the file, as written. The whole thing — 383 lines — stays where its author put it; the contents beside it link to each section on GitHub.

⚡ Rust 性能优化和最佳实践

⚠️ 执行原则

MUST 遵循以下Rust性能优化准则:

  • MUST 利用零成本抽象
  • NEVER 不必要地使用unsafe代码
  • ALWAYS 进行性能基准测试
  • DO NOT 过早优化牺牲可读性
  • MUST 正确使用并发和并行
  • ALWAYS 考虑内存布局和缓存效率

并发性能优化

    let handles: Vec<_> = (0..4).map(|_| {
        s.spawn(|_| {
            let mut results = Vec::new();
            while let Ok(item) = receiver.recv() {
                results.push(process_item(item));
            }
            results
        })
    }).collect();

    // 收集结果
    let mut final_results = Vec::new();
    for handle in handles {
        final_results.extend(handle.join().unwrap());
    }

    final_results
}).unwrap()

}

fn process_item(item: i32) -> i32 { item * 2 }


## 🔒 安全实践

### 内存安全保证
```rust
// ✅ 推荐:使用类型系统防止常见错误
#[derive(Debug, Clone)]
pub struct NonEmptyString(String);

impl NonEmptyString {
    pub fn new(s: String) -> Option<Self> {
        if s.is_empty() {
            None
        } else {
            Some(Self(s))
        }
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for NonEmptyString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ✅ 推荐:范围类型防止越界
#[derive(Debug, Clone, Copy)]
pub struct RangeInclusive<T> {
    start: T,
    end: T,
}

impl<T: PartialOrd + Copy> RangeInclusive<T> {
    pub fn new(start: T, end: T) -> Option<Self> {
        if start <= end {
            Some(Self { start, end })
        } else {
            None
        }
    }

    pub fn contains(&self, value: T) -> bool {
        self.start <= value && value <= self.end
    }
}

// ✅ 推荐:PhantomData处理泛型生命周期
use std::marker::PhantomData;

struct DatabaseConnection<'a> {
    _marker: PhantomData<&'a ()>,
    // 实际连接数据...
}

impl<'a> DatabaseConnection<'a> {
    fn new() -> Self {
        Self {
            _marker: PhantomData,
        }
    }
}

FFI安全

use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int};

Read the full file on GitHub · 383 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 383 lines · 0 tokens per session scan A c8276fa07000

Subscribe to this mod's changes

rust-performance is a cursor rule published in the GitHub repository wangqiqi/cursor-ai-rules (15 stars, last pushed 3mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 2,296 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.