Rust in Action Skill
Apply the systems programming practices from Tim McNamara's "Rust in Action" to review existing code and write new Rust. This skill operates in two modes: Review Mode (analyze code for violations of Rust idioms and systems programming correctness) and Write Mode (produce safe, idiomatic, systems-capable Rust from scratch).
The key differentiator of this book: Rust is taught through real systems — a CPU simulator, key-value store, NTP client, raw TCP stack, and OS kernel. Practices focus on correctness at the hardware boundary, not just language syntax.
Reference Files
practices-catalog.md — Before/after examples for ownership, smart pointers, bit ops, I/O, networking, concurrency, error wrapping, and state machines
How to Use This Skill
Before responding, read practices-catalog.md for the topic at hand. For ownership/borrowing issues read the ownership section. For systems/binary data read the data section. For a full review, read all sections.
Mode 1: Code Review
When the user asks you to review Rust code, follow this process:
Step 1: Identify the Domain
Determine whether the code is application-level, systems-level (binary data, I/O, networking, memory), or concurrent. The review focus shifts accordingly.
Step 2: Analyze the Code
Critical rule: Only flag genuine issues. If a pattern is idiomatic Rust, acknowledge it as correct. Do not manufacture problems where none exist. When code is well-written, say so and offer only minor suggestions. See the "Idiomatic Patterns — Do NOT Flag as Issues" section for patterns that must never be flagged.
- Ownership & Borrowing (Ch 4): Unnecessary
.clone()? Value moved when a borrow would suffice? Use references where full ownership is not required.
- Smart Pointer Choice (Ch 6): Is the right pointer type used?
Box<T> for heap, Rc<T> for single-thread shared, Arc<T> for multi-thread shared, RefCell<T> for interior mutability (single-thread), Mutex<T> for interior mutability (multi-thread). Cow<T> when data is usually read but occasionally mutated.
- Error Handling (Ch 3, 8):
.unwrap() or .expect() where ? belongs? For library code, define a custom error type that wraps downstream errors via From impl. Never leak internal error types across the public API boundary.
- Binary Data & Endianness (Ch 5, 7): Are integer byte representations explicit? Use
to_le_bytes() / from_le_bytes() / to_be_bytes(). Validate with checksums when writing binary formats. Use serde + bincode for structured serialization.
- Memory (Ch 6): Is
unsafe minimized? Raw pointer use must be bounded by a safe abstraction. Stack vs heap allocation: prefer stack; use Box only when size is unknown at compile time or you need heap lifetime.
- File & I/O (Ch 7): Use
BufReader/BufWriter for large files. Handle ENOENT, EPERM, ENOSPC distinctly — don't collapse I/O errors to strings. Use std::fs::Path for type-safe path handling.
- Networking (Ch 8): TCP state is implicit in OS — model explicit state machines with enums. Use trait objects (
Box<dyn Trait>) only when heterogeneous runtime dispatch is needed. Prefer impl Trait for static dispatch.
- Concurrency (Ch 10): Closures passed to threads must be
'static or use move. Shared mutable state needs Arc<Mutex<T>>. Use channels for message passing over shared state. Thread pool patterns over spawning one thread per task.
- Time (Ch 9): Don't use
std::time::SystemTime for elapsed measurement — it can go backwards. Use std::time::Instant for durations. For network time, NTP requires epoch conversion (NTP epoch: 1900 vs Unix: 1970 — offset 70 years = 2_208_988_800 seconds).
- Idioms: Iterator adapters over manual loops.
for item in &collection not for i in 0..collection.len(). if let/while let for single-variant matching. Exhaustive match — no silent wildcard arms.
Step 3: Report Findings
For each issue, report:
- Chapter reference (e.g., "Ch 6: Smart Pointers")
- Location in the code
- What's wrong (the anti-pattern)
- How to fix it (the idiomatic / systems-correct approach)
- Priority: Critical (safety/UB/data corruption), Important (idiom/correctness), Suggestion (polish)
Step 4: Provide Fixed Code
Offer a corrected version with comments explaining each change.
Mode 2: Writing New Code
When the user asks you to write new Rust code, apply these core principles:
Use cargo, not rustc directly (Ch 2). cargo new, cargo build, cargo test, cargo doc. Add third-party crates via Cargo.toml — never manually link.
Prefer integer types that match the domain (Ch 2). Use u8 for bytes, u16/u32/u64 for protocol fields sized to spec, i64 for timestamps. Avoid default usize for domain values.
Use loop for retry/event loops; while for condition-driven; for for iteration (Ch 2). Never use loop { if cond { break } } where while cond {} is clearer.
Compound Types & Traits (Ch 3)
Model domain state with enums, not stringly-typed flags (Ch 3). Enums with data (enum Packet { Ack(u32), Data(Vec<u8>) }) replace boolean + optional pairs and make invalid states unrepresentable.
Implement new() as the canonical constructor (Ch 3). impl MyStruct { pub fn new(...) -> Self { ... } }. Use Default for zero-value construction.
Implement std::fmt::Display for user-facing output, Debug via derive (Ch 3). Derive Debug; hand-implement Display. Never use {:?} in user-facing messages.
Use pub(crate) to limit visibility to the crate; keep internals private (Ch 3). Public API surface should be minimal and intentional.
Document public items with /// rustdoc comments (Ch 3). Include examples in doc comments — cargo test runs them.
Ownership, Borrowing & Smart Pointers (Ch 4, 6)
Use references where full ownership is not required (Ch 4). Pass &T for read, &mut T for write. Only transfer ownership when the callee must own (e.g., storing in a struct).
Choose smart pointers by use case (Ch 6):
Box<T> — heap allocation, single owner, unknown size at compile time
Rc<T> — shared ownership, single-threaded
Arc<T> — shared ownership, multi-threaded
Cell<T> — interior mutability for Copy types, single-threaded
RefCell<T> — interior mutability for non-Copy, single-threaded, runtime borrow checks
Cow<'a, T> — clone-on-write, avoids allocation when data is only read
Arc<Mutex<T>> — shared mutable state across threads
Never use Rc across thread boundaries (Ch 6). The compiler enforces this — Rc is not Send. Use Arc instead.
Minimize unsafe blocks; wrap them in safe abstractions (Ch 6). Raw pointers (*const T, *mut T) must be bounded within a module or function that upholds safety invariants. Document the safety contract with // SAFETY: comments.
Data Representation (Ch 5)
Be explicit about endianness in binary protocols (Ch 5, 7). Use u32::to_le_bytes(), u32::from_be_bytes() etc. Never assume native endianness when writing to disk or network.
Use bit operations to inspect and build packed data (Ch 5). AND (&) to isolate bits, OR (|) to set bits, shift (<<, >>) to position. Use named constants for masks: const SIGN_BIT: u32 = 0x8000_0000.
Validate binary data with checksums (Ch 7). For key-value stores and file formats, store a CRC or hash alongside data. Verify on read before trusting.
Files & Storage (Ch 7)
Use BufReader/BufWriter for file I/O (Ch 7). Raw File::read() makes a syscall per call. BufReader batches reads into user-space buffer.
Use serde + bincode for binary serialization (Ch 7). Add #[derive(Serialize, Deserialize)]; let bincode::serialize/deserialize handle encoding. Use serde_json for human-readable formats.
Use std::path::Path and PathBuf for file paths (Ch 7). Never build paths with string concatenation. Use path.join(), path.extension(), path.file_name().
Networking (Ch 8)
Model protocol state explicitly with enums (Ch 8). A TCP connection has states (SYN_SENT, ESTABLISHED, CLOSE_WAIT, etc.). Encode them as enum variants — the compiler enforces valid transitions.
Wrap library errors in a domain error type (Ch 8). When a function calls multiple libraries (network + I/O + parse), define an enum that wraps each. Implement From<LibError> for DomainError so ? converts automatically.
Use trait objects only for heterogeneous runtime dispatch (Ch 8). Vec<Box<dyn Animal>> is correct when you have a mixed collection. For a single concrete type, impl Trait is zero-cost.
Concurrency (Ch 10)
Use move closures when passing to threads (Ch 10). thread::spawn(move || { ... }) transfers ownership of captured variables into the thread. This is required when the closure outlives the current stack frame.
Use Arc::clone() explicitly, not .clone() on a value (Ch 10). Arc::clone(&ptr) is idiomatic — it's cheap (increments a reference count). Avoid .clone() on the inner value.
Use channels for work distribution; Arc<Mutex<T>> for shared state (Ch 10). Channels (std::sync::mpsc) are simpler and safer. Use shared state only when channels don't fit (e.g., result collection).
Use thread pools over raw thread::spawn per task (Ch 10). Spawning one thread per request doesn't scale. Use rayon, tokio, or a manual pool with a bounded queue.
Time (Ch 9)
Use Instant for elapsed time, SystemTime for wall clock (Ch 9). SystemTime can go backwards (NTP adjustments, leap seconds). Instant is monotonic.
Apply the NTP epoch offset when working with network time (Ch 9). NTP timestamps count seconds from 1900-01-01; Unix timestamps count from 1970-01-01. Offset: 2_208_988_800u64 seconds.
Smart Pointer Selection Guide (Ch 6)
Is the data shared across threads?
├── Yes → Arc<T> (read-only) or Arc<Mutex<T>> (mutable)
└── No
├── Shared (multiple owners, single thread)?
│ └── Rc<T> (read-only) or Rc<RefCell<T>> (mutable)
└── Single owner
├── Size unknown at compile time / recursive type?
│ └── Box<T>
├── Usually read, occasionally cloned/modified?
│ └── Cow<'a, T>
└── Interior mutability needed?
├── Copy type → Cell<T>
└── Non-Copy → RefCell<T>
Code Structure Templates
const FLAGS_MASK: u8 = 0b0000_1111; // isolate lower 4 bits
fn extract_flags(byte: u8) -> u8 {
byte & FLAGS_MASK
}
</example>
<example id="2" title="Library Error Type (Ch 8)">
```rust
#[derive(Debug)]
pub enum AppError {
Io(std::io::Error),
Network(std::net::AddrParseError),
Parse(String),
}
impl std::fmt::Display for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AppError::Io(e) => write!(f, "I/O error: {e}"),
AppError::Network(e) => write!(f, "network error: {e}"),
AppError::Parse(msg) => write!(f, "parse error: {msg}"),
}
}
}
impl std::error::Error for AppError {}
impl From<std::io::Error> for AppError {
fn from(e: std::io::Error) -> Self { AppError::Io(e) }
}
impl From<std::net::AddrParseError> for AppError {
fn from(e: std::net::AddrParseError) -> Self { AppError::Network(e) }
}
impl ConnectionState {
fn connect(addr: std::net::SocketAddr) -> Result<Self, AppError> {
let stream = std::net::TcpStream::connect(addr)?;
Ok(ConnectionState::Connected { stream })
}
}
</example>
<example id="4" title="Thread Pool Pattern (Ch 10)">
```rust
use std::sync::{Arc, Mutex};
use std::sync::mpsc;
use std::thread;
type Job = Box<dyn FnOnce() + Send + 'static>;
struct ThreadPool {
sender: mpsc::Sender<Job>,
}
impl ThreadPool {
fn new(size: usize) -> Self {
let (sender, receiver) = mpsc::channel::<Job>();
let receiver = Arc::new(Mutex::new(receiver));
for _ in 0..size {
let rx = Arc::clone(&receiver);
thread::spawn(move || loop {
let job = rx.lock().expect("mutex poisoned").recv();
match job {
Ok(f) => f(),
Err(_) => break, // channel closed
}
});
}
ThreadPool { sender }
}
fn execute(&self, f: impl FnOnce() + Send + 'static) {
self.sender.send(Box::new(f)).expect("thread pool closed");
}
}
When reviewing code, recognize these patterns as correct and idiomatic. Do not manufacture issues from them:
Arc<Mutex<T>> — the standard pattern for shared mutable state across threads (Ch 6, 10). This is correct and idiomatic. Never call it redundant, a design error, or suggest removing/replacing it when it is the appropriate choice. When a Store or similar struct wraps shared mutable data accessed by multiple threads, Arc<Mutex<Vec<u8>>> is exactly right — acknowledge it as such.
BufReader<File> — explicitly recommended for batched I/O (Ch 7). Never call it overhead-adding or harmful.
AtomicU64 with Ordering::Relaxed — appropriate for counters where exact cross-thread ordering is not required, e.g. telemetry, stats (Ch 10). Not a bug.
&Path parameters — correct; prefer &Path over &str or String for file paths (Ch 7).
- Custom error enums with
Display + Error + From impls — the canonical library error pattern (Ch 3, 8). Praise it, don't critique it.
.expect("mutex poisoned") with a descriptive reason — correct idiom for panicking on a poisoned mutex (Ch 10).
Arc::clone(&ptr) idiom — correct; makes cheap refcount increment explicit (Ch 10).
move closures for threads — required and correct (Ch 10).
If code is already correct, say so. Only flag real issues. If the only things left to say are minor suggestions, label them as suggestions, not bugs or important issues.
Critical (Safety, Correctness, UB)
- Ch 4: Borrow, don't clone — never move when a reference suffices
- Ch 6: Choose the right smart pointer —
Rc is not thread-safe; don't share across threads
- Ch 6: Wrap
unsafe in safe abstractions — document safety contracts with // SAFETY:
- Ch 5/7: Explicit endianness — wrong byte order silently corrupts binary data
- Ch 9: Use
Instant for elapsed time — SystemTime can go backwards
Important (Idiom & Maintainability)
- Ch 3: Domain enums over stringly-typed state — invalid states should not compile
- Ch 8: Wrap downstream errors in a domain error type with
From impls
- Ch 8:
impl Trait over dyn Trait when types are homogeneous
- Ch 10:
move closures for threads — required when closure outlives the stack frame
- Ch 10:
Arc::clone() idiom — makes cheap pointer clone explicit
Suggestions (Systems Polish)
- Ch 2: Size integer types to the protocol spec —
u8 for bytes, u16 for ports
- Ch 5: Named bit-mask constants —
const SIGN_BIT: u32 = 0x8000_0000
- Ch 7:
BufReader/BufWriter for all file I/O — syscall batching
- Ch 7: Checksums on binary writes — detect corruption on read
- Ch 9: NTP epoch offset constant —
const NTP_UNIX_OFFSET: u64 = 2_208_988_800
Anti-Patterns to Always Flag
static mut — a data race waiting to happen in concurrent code; replace with Arc<Mutex<T>> or an atomic type (Ch 6, 10)
from_ne_bytes / to_ne_bytes in protocols — native endianness is host-dependent; always use from_le_bytes/from_be_bytes (Ch 5, 7)
.unwrap() in library or I/O code — panics on error; use ? with Result propagation (Ch 3, 8)
Box<Vec<T>> — Vec<T> already heap-allocates; wrapping it in Box adds a pointless double-indirection; return Vec<T> directly (Ch 6)
Rc<T> passed to thread::spawn — Rc is not Send; use Arc<T> for shared ownership across threads (Ch 6)
- Indexing slices without bounds checks —
bytes[0..4] panics on short input; use bytes.get(0..4).ok_or(...) (Ch 5, 7)
- Not returning
JoinHandle from thread-spawning functions — callers cannot join threads or detect panics; return thread::JoinHandle<()> (Ch 10)
When reviewing Rust code:
- Always identify all endianness issues —
from_ne_bytes/to_ne_bytes in network or file contexts is always wrong.
- Always flag
static mut — it is undefined behavior in concurrent contexts; replace with atomics or Arc<Mutex<T>>.
- Always flag
.unwrap() in non-test I/O or library code — use ? and Result.
- Flag
Box<Vec<T>> as redundant double-indirection.
- Flag
Rc<T> used with thread::spawn — it will not compile, but explain why and offer Arc<T>.
- Flag unchecked slice indexing — suggest
.get(range).ok_or(...).
- Flag thread-spawning functions that discard the
JoinHandle.
- Recognize and praise:
Arc<Mutex<T>>, BufReader, AtomicU64 with Ordering::Relaxed, &Path parameters, custom error enums, .expect("mutex poisoned"), Arc::clone(&ptr), move closures.
- Always provide corrected code with comments explaining each change.
1---2name: rust-in-action3version: "1.0"4license: MIT5tags: [rust, systems-programming]6description: >7 Write and review Rust code using systems programming concepts from "Rust in Action"8 by Tim McNamara. Covers language foundations, ownership and borrowing, smart pointers,9 data representation (bits, endianness, floats), memory (stack/heap/virtual), file I/O,10 networking (TCP/HTTP), concurrency (threads/closures), and OS-level programming.11 Use when writing systems-level Rust, working with binary data, raw pointers, file formats,12 network protocols, or low-level memory. Trigger on: "Rust", "systems programming",13 "smart pointers", "endianness", "bit manipulation", "TCP", "raw pointers", "serde",14 "borrow checker", "ownership", "concurrency", "kernel", ".rs files", "cargo".15metadata:16 source: https://skillmd.com/skills/booklib-ai/rust-in-action17---1819# Rust in Action Skill2021Apply the systems programming practices from Tim McNamara's "Rust in Action" to review existing code and write new Rust. This skill operates in two modes: **Review Mode** (analyze code for violations of Rust idioms and systems programming correctness) and **Write Mode** (produce safe, idiomatic, systems-capable Rust from scratch).2223The key differentiator of this book: Rust is taught through real systems — a CPU simulator, key-value store, NTP client, raw TCP stack, and OS kernel. Practices focus on correctness at the hardware boundary, not just language syntax.2425## Reference Files2627- `practices-catalog.md` — Before/after examples for ownership, smart pointers, bit ops, I/O, networking, concurrency, error wrapping, and state machines2829## How to Use This Skill3031**Before responding**, read `practices-catalog.md` for the topic at hand. For ownership/borrowing issues read the ownership section. For systems/binary data read the data section. For a full review, read all sections.3233---3435## Mode 1: Code Review3637When the user asks you to **review** Rust code, follow this process:3839### Step 1: Identify the Domain40Determine whether the code is application-level, systems-level (binary data, I/O, networking, memory), or concurrent. The review focus shifts accordingly.4142### Step 2: Analyze the Code4344**Critical rule**: Only flag genuine issues. If a pattern is idiomatic Rust, acknowledge it as correct. Do not manufacture problems where none exist. When code is well-written, say so and offer only minor suggestions. See the "Idiomatic Patterns — Do NOT Flag as Issues" section for patterns that must never be flagged.4546<core_principles>47Check these areas in order of severity:48491. **Ownership & Borrowing** (Ch 4): Unnecessary `.clone()`? Value moved when a borrow would suffice? Use references where full ownership is not required.502. **Smart Pointer Choice** (Ch 6): Is the right pointer type used? `Box<T>` for heap, `Rc<T>` for single-thread shared, `Arc<T>` for multi-thread shared, `RefCell<T>` for interior mutability (single-thread), `Mutex<T>` for interior mutability (multi-thread). `Cow<T>` when data is usually read but occasionally mutated.513. **Error Handling** (Ch 3, 8): `.unwrap()` or `.expect()` where `?` belongs? For library code, define a custom error type that wraps downstream errors via `From` impl. Never leak internal error types across the public API boundary.524. **Binary Data & Endianness** (Ch 5, 7): Are integer byte representations explicit? Use `to_le_bytes()` / `from_le_bytes()` / `to_be_bytes()`. Validate with checksums when writing binary formats. Use `serde` + `bincode` for structured serialization.535. **Memory** (Ch 6): Is `unsafe` minimized? Raw pointer use must be bounded by a safe abstraction. Stack vs heap allocation: prefer stack; use `Box` only when size is unknown at compile time or you need heap lifetime.546. **File & I/O** (Ch 7): Use `BufReader`/`BufWriter` for large files. Handle `ENOENT`, `EPERM`, `ENOSPC` distinctly — don't collapse I/O errors to strings. Use `std::fs::Path` for type-safe path handling.557. **Networking** (Ch 8): TCP state is implicit in OS — model explicit state machines with enums. Use trait objects (`Box<dyn Trait>`) only when heterogeneous runtime dispatch is needed. Prefer `impl Trait` for static dispatch.568. **Concurrency** (Ch 10): Closures passed to threads must be `'static` or use `move`. Shared mutable state needs `Arc<Mutex<T>>`. Use channels for message passing over shared state. Thread pool patterns over spawning one thread per task.579. **Time** (Ch 9): Don't use `std::time::SystemTime` for elapsed measurement — it can go backwards. Use `std::time::Instant` for durations. For network time, NTP requires epoch conversion (NTP epoch: 1900 vs Unix: 1970 — offset 70 years = 2_208_988_800 seconds).5810. **Idioms**: Iterator adapters over manual loops. `for item in &collection` not `for i in 0..collection.len()`. `if let`/`while let` for single-variant matching. Exhaustive `match` — no silent wildcard arms.59</core_principles>6061### Step 3: Report Findings62For each issue, report:63- **Chapter reference** (e.g., "Ch 6: Smart Pointers")64- **Location** in the code65- **What's wrong** (the anti-pattern)66- **How to fix it** (the idiomatic / systems-correct approach)67- **Priority**: Critical (safety/UB/data corruption), Important (idiom/correctness), Suggestion (polish)6869### Step 4: Provide Fixed Code70Offer a corrected version with comments explaining each change.7172---7374## Mode 2: Writing New Code7576When the user asks you to **write** new Rust code, apply these core principles:7778<core_principles>79### Language Foundations (Ch 2)80811. **Use cargo, not rustc directly** (Ch 2). `cargo new`, `cargo build`, `cargo test`, `cargo doc`. Add third-party crates via `Cargo.toml` — never manually link.82832. **Prefer integer types that match the domain** (Ch 2). Use `u8` for bytes, `u16`/`u32`/`u64` for protocol fields sized to spec, `i64` for timestamps. Avoid default `usize` for domain values.84853. **Use `loop` for retry/event loops; `while` for condition-driven; `for` for iteration** (Ch 2). Never use `loop { if cond { break } }` where `while cond {}` is clearer.8687### Compound Types & Traits (Ch 3)88894. **Model domain state with enums, not stringly-typed flags** (Ch 3). Enums with data (`enum Packet { Ack(u32), Data(Vec<u8>) }`) replace boolean + optional pairs and make invalid states unrepresentable.90915. **Implement `new()` as the canonical constructor** (Ch 3). `impl MyStruct { pub fn new(...) -> Self { ... } }`. Use `Default` for zero-value construction.92936. **Implement `std::fmt::Display` for user-facing output, `Debug` via derive** (Ch 3). Derive `Debug`; hand-implement `Display`. Never use `{:?}` in user-facing messages.94957. **Use `pub(crate)` to limit visibility to the crate; keep internals private** (Ch 3). Public API surface should be minimal and intentional.96978. **Document public items with `///` rustdoc comments** (Ch 3). Include examples in doc comments — `cargo test` runs them.9899### Ownership, Borrowing & Smart Pointers (Ch 4, 6)1001019. **Use references where full ownership is not required** (Ch 4). Pass `&T` for read, `&mut T` for write. Only transfer ownership when the callee must own (e.g., storing in a struct).10210310. **Choose smart pointers by use case** (Ch 6):104 - `Box<T>` — heap allocation, single owner, unknown size at compile time105 - `Rc<T>` — shared ownership, single-threaded106 - `Arc<T>` — shared ownership, multi-threaded107 - `Cell<T>` — interior mutability for `Copy` types, single-threaded108 - `RefCell<T>` — interior mutability for non-`Copy`, single-threaded, runtime borrow checks109 - `Cow<'a, T>` — clone-on-write, avoids allocation when data is only read110 - `Arc<Mutex<T>>` — shared mutable state across threads11111211. **Never use `Rc` across thread boundaries** (Ch 6). The compiler enforces this — `Rc` is not `Send`. Use `Arc` instead.11311412. **Minimize `unsafe` blocks; wrap them in safe abstractions** (Ch 6). Raw pointers (`*const T`, `*mut T`) must be bounded within a module or function that upholds safety invariants. Document the safety contract with `// SAFETY:` comments.115116### Data Representation (Ch 5)11711813. **Be explicit about endianness in binary protocols** (Ch 5, 7). Use `u32::to_le_bytes()`, `u32::from_be_bytes()` etc. Never assume native endianness when writing to disk or network.11912014. **Use bit operations to inspect and build packed data** (Ch 5). AND (`&`) to isolate bits, OR (`|`) to set bits, shift (`<<`, `>>`) to position. Use named constants for masks: `const SIGN_BIT: u32 = 0x8000_0000`.12112215. **Validate binary data with checksums** (Ch 7). For key-value stores and file formats, store a CRC or hash alongside data. Verify on read before trusting.123124### Files & Storage (Ch 7)12512616. **Use `BufReader`/`BufWriter` for file I/O** (Ch 7). Raw `File::read()` makes a syscall per call. `BufReader` batches reads into user-space buffer.12712817. **Use `serde` + `bincode` for binary serialization** (Ch 7). Add `#[derive(Serialize, Deserialize)]`; let `bincode::serialize`/`deserialize` handle encoding. Use `serde_json` for human-readable formats.12913018. **Use `std::path::Path` and `PathBuf` for file paths** (Ch 7). Never build paths with string concatenation. Use `path.join()`, `path.extension()`, `path.file_name()`.131132### Networking (Ch 8)13313419. **Model protocol state explicitly with enums** (Ch 8). A TCP connection has states (SYN_SENT, ESTABLISHED, CLOSE_WAIT, etc.). Encode them as enum variants — the compiler enforces valid transitions.13513620. **Wrap library errors in a domain error type** (Ch 8). When a function calls multiple libraries (network + I/O + parse), define an enum that wraps each. Implement `From<LibError> for DomainError` so `?` converts automatically.13713821. **Use trait objects only for heterogeneous runtime dispatch** (Ch 8). `Vec<Box<dyn Animal>>` is correct when you have a mixed collection. For a single concrete type, `impl Trait` is zero-cost.139140### Concurrency (Ch 10)14114222. **Use `move` closures when passing to threads** (Ch 10). `thread::spawn(move || { ... })` transfers ownership of captured variables into the thread. This is required when the closure outlives the current stack frame.14314423. **Use `Arc::clone()` explicitly, not `.clone()` on a value** (Ch 10). `Arc::clone(&ptr)` is idiomatic — it's cheap (increments a reference count). Avoid `.clone()` on the inner value.14514624. **Use channels for work distribution; `Arc<Mutex<T>>` for shared state** (Ch 10). Channels (`std::sync::mpsc`) are simpler and safer. Use shared state only when channels don't fit (e.g., result collection).14714825. **Use thread pools over raw `thread::spawn` per task** (Ch 10). Spawning one thread per request doesn't scale. Use `rayon`, `tokio`, or a manual pool with a bounded queue.149150### Time (Ch 9)15115226. **Use `Instant` for elapsed time, `SystemTime` for wall clock** (Ch 9). `SystemTime` can go backwards (NTP adjustments, leap seconds). `Instant` is monotonic.15315427. **Apply the NTP epoch offset when working with network time** (Ch 9). NTP timestamps count seconds from 1900-01-01; Unix timestamps count from 1970-01-01. Offset: `2_208_988_800u64` seconds.155</core_principles>156157---158159## Smart Pointer Selection Guide (Ch 6)160161```162Is the data shared across threads?163├── Yes → Arc<T> (read-only) or Arc<Mutex<T>> (mutable)164└── No165 ├── Shared (multiple owners, single thread)?166 │ └── Rc<T> (read-only) or Rc<RefCell<T>> (mutable)167 └── Single owner168 ├── Size unknown at compile time / recursive type?169 │ └── Box<T>170 ├── Usually read, occasionally cloned/modified?171 │ └── Cow<'a, T>172 └── Interior mutability needed?173 ├── Copy type → Cell<T>174 └── Non-Copy → RefCell<T>175```176177---178179## Code Structure Templates180181<examples>182<example id="1" title="Binary Protocol Field (Ch 5, 7)">183```rust184/// Parse a 4-byte big-endian u32 from a byte buffer at offset.185fn read_u32_be(buf: &[u8], offset: usize) -> Result<u32, ParseError> {186 buf.get(offset..offset + 4)187 .ok_or(ParseError::UnexpectedEof)188 .map(|b| u32::from_be_bytes(b.try_into().unwrap()))189}190191const FLAGS_MASK: u8 = 0b0000_1111; // isolate lower 4 bits192fn extract_flags(byte: u8) -> u8 {193 byte & FLAGS_MASK194}195```196</example>197198<example id="2" title="Library Error Type (Ch 8)">199```rust200#[derive(Debug)]201pub enum AppError {202 Io(std::io::Error),203 Network(std::net::AddrParseError),204 Parse(String),205}206207impl std::fmt::Display for AppError {208 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {209 match self {210 AppError::Io(e) => write!(f, "I/O error: {e}"),211 AppError::Network(e) => write!(f, "network error: {e}"),212 AppError::Parse(msg) => write!(f, "parse error: {msg}"),213 }214 }215}216217impl std::error::Error for AppError {}218impl From<std::io::Error> for AppError {219 fn from(e: std::io::Error) -> Self { AppError::Io(e) }220}221impl From<std::net::AddrParseError> for AppError {222 fn from(e: std::net::AddrParseError) -> Self { AppError::Network(e) }223}224```225</example>226227<example id="3" title="State Machine with Enum (Ch 8)">228```rust229#[derive(Debug, Clone, PartialEq)]230enum ConnectionState {231 Idle,232 Connecting { addr: std::net::SocketAddr },233 Connected { stream: std::net::TcpStream },234 Closed,235}236237impl ConnectionState {238 fn connect(addr: std::net::SocketAddr) -> Result<Self, AppError> {239 let stream = std::net::TcpStream::connect(addr)?;240 Ok(ConnectionState::Connected { stream })241 }242}243```244</example>245246<example id="4" title="Thread Pool Pattern (Ch 10)">247```rust248use std::sync::{Arc, Mutex};249use std::sync::mpsc;250use std::thread;251252type Job = Box<dyn FnOnce() + Send + 'static>;253254struct ThreadPool {255 sender: mpsc::Sender<Job>,256}257258impl ThreadPool {259 fn new(size: usize) -> Self {260 let (sender, receiver) = mpsc::channel::<Job>();261 let receiver = Arc::new(Mutex::new(receiver));262263 for _ in 0..size {264 let rx = Arc::clone(&receiver);265 thread::spawn(move || loop {266 let job = rx.lock().expect("mutex poisoned").recv();267 match job {268 Ok(f) => f(),269 Err(_) => break, // channel closed270 }271 });272 }273 ThreadPool { sender }274 }275276 fn execute(&self, f: impl FnOnce() + Send + 'static) {277 self.sender.send(Box::new(f)).expect("thread pool closed");278 }279}280```281</example>282</examples>283284---285286<strengths_to_praise>287## Idiomatic Patterns — Do NOT Flag as Issues288289When reviewing code, recognize these patterns as **correct and idiomatic**. Do not manufacture issues from them:290291- **`Arc<Mutex<T>>`** — the standard pattern for shared mutable state across threads (Ch 6, 10). This is correct and idiomatic. Never call it redundant, a design error, or suggest removing/replacing it when it is the appropriate choice. When a `Store` or similar struct wraps shared mutable data accessed by multiple threads, `Arc<Mutex<Vec<u8>>>` is exactly right — acknowledge it as such.292- **`BufReader<File>`** — explicitly recommended for batched I/O (Ch 7). Never call it overhead-adding or harmful.293- **`AtomicU64` with `Ordering::Relaxed`** — appropriate for counters where exact cross-thread ordering is not required, e.g. telemetry, stats (Ch 10). Not a bug.294- **`&Path` parameters** — correct; prefer `&Path` over `&str` or `String` for file paths (Ch 7).295- **Custom error enums with `Display` + `Error` + `From` impls** — the canonical library error pattern (Ch 3, 8). Praise it, don't critique it.296- **`.expect("mutex poisoned")` with a descriptive reason** — correct idiom for panicking on a poisoned mutex (Ch 10).297- **`Arc::clone(&ptr)` idiom** — correct; makes cheap refcount increment explicit (Ch 10).298- **`move` closures for threads** — required and correct (Ch 10).299300If code is already correct, say so. Only flag real issues. If the only things left to say are minor suggestions, label them as suggestions, not bugs or important issues.301</strengths_to_praise>302303---304305<anti_patterns>306## Priority of Practices by Impact307308### Critical (Safety, Correctness, UB)309- Ch 4: Borrow, don't clone — never move when a reference suffices310- Ch 6: Choose the right smart pointer — `Rc` is not thread-safe; don't share across threads311- Ch 6: Wrap `unsafe` in safe abstractions — document safety contracts with `// SAFETY:`312- Ch 5/7: Explicit endianness — wrong byte order silently corrupts binary data313- Ch 9: Use `Instant` for elapsed time — `SystemTime` can go backwards314315### Important (Idiom & Maintainability)316- Ch 3: Domain enums over stringly-typed state — invalid states should not compile317- Ch 8: Wrap downstream errors in a domain error type with `From` impls318- Ch 8: `impl Trait` over `dyn Trait` when types are homogeneous319- Ch 10: `move` closures for threads — required when closure outlives the stack frame320- Ch 10: `Arc::clone()` idiom — makes cheap pointer clone explicit321322### Suggestions (Systems Polish)323- Ch 2: Size integer types to the protocol spec — `u8` for bytes, `u16` for ports324- Ch 5: Named bit-mask constants — `const SIGN_BIT: u32 = 0x8000_0000`325- Ch 7: `BufReader`/`BufWriter` for all file I/O — syscall batching326- Ch 7: Checksums on binary writes — detect corruption on read327- Ch 9: NTP epoch offset constant — `const NTP_UNIX_OFFSET: u64 = 2_208_988_800`328329### Anti-Patterns to Always Flag330- **`static mut`** — a data race waiting to happen in concurrent code; replace with `Arc<Mutex<T>>` or an atomic type (Ch 6, 10)331- **`from_ne_bytes` / `to_ne_bytes` in protocols** — native endianness is host-dependent; always use `from_le_bytes`/`from_be_bytes` (Ch 5, 7)332- **`.unwrap()` in library or I/O code** — panics on error; use `?` with `Result` propagation (Ch 3, 8)333- **`Box<Vec<T>>`** — `Vec<T>` already heap-allocates; wrapping it in `Box` adds a pointless double-indirection; return `Vec<T>` directly (Ch 6)334- **`Rc<T>` passed to `thread::spawn`** — `Rc` is not `Send`; use `Arc<T>` for shared ownership across threads (Ch 6)335- **Indexing slices without bounds checks** — `bytes[0..4]` panics on short input; use `bytes.get(0..4).ok_or(...)` (Ch 5, 7)336- **Not returning `JoinHandle` from thread-spawning functions** — callers cannot join threads or detect panics; return `thread::JoinHandle<()>` (Ch 10)337</anti_patterns>338339<guidelines>340## Review Guidelines Summary341342When reviewing Rust code:3431. Always identify all endianness issues — `from_ne_bytes`/`to_ne_bytes` in network or file contexts is always wrong.3442. Always flag `static mut` — it is undefined behavior in concurrent contexts; replace with atomics or `Arc<Mutex<T>>`.3453. Always flag `.unwrap()` in non-test I/O or library code — use `?` and `Result`.3464. Flag `Box<Vec<T>>` as redundant double-indirection.3475. Flag `Rc<T>` used with `thread::spawn` — it will not compile, but explain why and offer `Arc<T>`.3486. Flag unchecked slice indexing — suggest `.get(range).ok_or(...)`.3497. Flag thread-spawning functions that discard the `JoinHandle`.3508. Recognize and praise: `Arc<Mutex<T>>`, `BufReader`, `AtomicU64` with `Ordering::Relaxed`, `&Path` parameters, custom error enums, `.expect("mutex poisoned")`, `Arc::clone(&ptr)`, `move` closures.3519. Always provide corrected code with comments explaining each change.352</guidelines>