Rust Performance & Safety Patterns
БесплатноБез исполняемых скриптовНе проверенZero-copy deserialization, async I/O patterns, lifetime management, memory-efficient parsing, and safe handling of unsafe code for SSTable parsing. Use when…
Об этом скилле
Rust Performance & Safety Patterns
This skill provides guidance on Rust patterns for high-performance, memory-efficient SSTable parsing.
When to Use This Skill
- Implementing zero-copy deserialization
- Managing lifetimes for borrowed data
- Async I/O patterns with tokio
- Memory optimization (<128MB target)
- Safe handling of unsafe code
- Borrow checker issues
- Performance bottlenecks
Documentation Resources
For latest crate documentation, use Context7 MCP:
bytes crate (/tokio-rs/bytes)
Zero-copy buffer types, Bytes/BytesMut API
Ask: "Fetch bytes crate documentation using Context7"
tokio (/tokio-rs/tokio)
Async runtime, I/O patterns, task management
Ask: "Fetch tokio documentation using Context7"
serde (/serde-rs/serde)
Serialization framework patterns
Ask: "Fetch serde documentation using Context7"
Zero-Copy Patterns
Core Principle
Avoid copying data unnecessarily. Use Bytes for shared buffer references.
See zero-copy-patterns.md for detailed patterns from existing codebase.
Buffer Sharing with Bytes
use bytes::Bytes;
// Share buffer without copying
fn parse_partition(buffer: Bytes, offset: usize, len: usize) -> Result<Partition> {
// Slice creates new Bytes pointing to same underlying buffer
let partition_data = buffer.slice(offset..offset + len);
// Pass slices to child parsers
let header = parse_header(partition_data.slice(0..10))?;
let rows = parse_rows(partition_data.slice(10..))?;
Ok(Partition { header, rows })
}
Avoiding Unnecessary Clones
// ❌ BAD: Copies data
fn parse_text(data: &[u8]) -> Result<String> {
let bytes = data.to_vec(); // COPY 1
String::from_utf8(bytes) // COPY 2 (if validation needed)
}
// ✅ GOOD: Minimal copying
fn parse_text(data: Bytes) -> Result<String> {
// Only copy if UTF-8 validation requires it
let s = std::str::from_utf8(&data)?;
Ok(s.to_string()) // Single copy only when needed
}
// ✅ BETTER: Keep as Bytes if possible
fn parse_blob(data: Bytes) -> Result<Bytes> {
// No copy at all
Ok(data)
}
Lifetime Management
Borrowing vs Owning
// Struct with borrowed data (careful with lifetimes)
struct Row<'a> {
key: &'a [u8],
values: Vec<&'a [u8]>,
}
// Struct with owned data (simpler, but copies)
struct RowOwned {
key: Bytes, // Shared ownership, no copy
values: Vec<Bytes>,
}
Lifetime Elision
// Explicit lifetimes
fn parse_row<'a>(data: &'a [u8]) -> Result<Row<'a>> { ... }
// Elided (compiler infers)
fn parse_row(data: &[u8]) -> Result<Row> { ... }
Common Lifetime Patterns
// Pattern 1: Return borrowed data
fn find_cell<'a>(row: &'a Row, column: &str) -> Option<&'a [u8]> {
row.cells.get(column).map(|c| c.value.as_ref())
}
// Pattern 2: Return owned data (use Bytes for zero-copy)
fn find_cell_owned(row: &Row, column: &str) -> Option<Bytes> {
row.cells.get(column).map(|c| c.value.clone()) // Bytes::clone is cheap
}
Async Patterns
Async File I/O
use tokio::fs::File;
use tokio::io::AsyncReadExt;
async fn read_sstable(path: &Path) -> Result<Bytes> {
let mut file = File::open(path).await?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer).await?;
Ok(Bytes::from(buffer))
}
Async Decompression
use tokio::task;
async fn decompress_chunk(compressed: Bytes) -> Result<Bytes> {
// CPU-intensive work in blocking task
task::spawn_blocking(move || {
let decompressed = lz4::block::decompress(&compressed, None)?;
Ok(Bytes::from(decompressed))
}).await?
}
Async Iteration
use futures::stream::{Stream, StreamExt};
async fn parse_rows<S>(row_stream: S) -> Result<Vec<Row>>
where
S: Stream<Item = Result<Bytes>>,
{
let mut rows = Vec::new();
tokio::pin!(row_stream);
while let Some(row_data) = row_stream.next().await {
let row = parse_row(row_data?)?;
rows.push(row);
}
Ok(rows)
}
Memory Management
PRD Target: <128MB
Track memory usage for large SSTables:
// Don't hold entire SSTable in memory
struct SstableReader {
file: File,
index: Vec<IndexEntry>, // Keep index in memory
cache: LruCache<u64, Bytes>, // Cache hot blocks
}
// Read only what's needed
async fn read_partition(&mut self, offset: u64) -> Result<Partition> {
// Check cache first
if let Some(block) = self.cache.get(&offset) {
return parse_partition(block.clone(), 0, block.len());
}
// Read minimal block
let block = self.read_block(offset).await?;
self.cache.put(offset, block.clone());
parse_partition(block, 0, block.len())
}
Streaming Instead of Buffering
// ❌ BAD: Buffer everything
async fn process_sstable(path: &Path) -> Result<Vec<Row>> {
let data = tokio::fs::read(path).await?; // Load entire file
parse
Установить Rust Performance & Safety Patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл Rust Performance & Safety Patterns?
Zero-copy deserialization, async I/O patterns, lifetime management, memory-efficient parsing, and safe handling of unsafe code for SSTable parsing. Use when working with performance optimization, memory efficiency, async/await, borrowing/lifetimes, zero-copy patterns, or memory usage under 128MB target.
Как установить скилл Rust Performance & Safety Patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Rust Performance & Safety Patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic