@sinkaroid/rust-shapeshift 1.0.4 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +61 -5
  2. package/package.json +6 -6
  3. package/skills/rust-shapeshift/SKILL.md +24 -4
  4. package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +1 -1
  5. package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +1 -1
  6. package/skills/rust-shapeshift/resources/collection_reuse_and_capacity_retention.md +135 -0
  7. package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +1 -1
  8. package/skills/rust-shapeshift/resources/deadlock_elimination_and_locks_across_await.md +149 -0
  9. package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +1 -1
  10. package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +3 -3
  11. package/skills/rust-shapeshift/resources/enum_variant_boxing_and_stack_squashing.md +136 -0
  12. package/skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md +1 -1
  13. package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +1 -1
  14. package/skills/rust-shapeshift/resources/hot_path_string_and_zero_cost_helpers.md +3 -3
  15. package/skills/rust-shapeshift/resources/lock_free_ring_buffers_and_disruptor.md +185 -0
  16. package/skills/rust-shapeshift/resources/memory_mapped_files_and_zero_copy_paging.md +151 -0
  17. package/skills/rust-shapeshift/resources/numeric_safety_and_saturating_arithmetic.md +124 -0
  18. package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +1 -1
  19. package/skills/rust-shapeshift/resources/production_memory_leak_diagnostics_and_ebpf.md +120 -0
  20. package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +1 -1
  21. package/skills/rust-shapeshift/resources/redis_connection_and_caching_pitfalls.md +1 -1
  22. package/skills/rust-shapeshift/resources/reqwest_client_and_connection_pooling.md +1 -1
  23. package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +1 -1
  24. package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +2 -2
  25. package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +1 -1
  26. package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +1 -1
  27. package/skills/rust-shapeshift/resources/zero_copy_zero_alloc_serialization_rkyv.md +135 -0
  28. package/skills/rust-shapeshift/resources/zero_cost_iterators_and_pipeline_inlining.md +121 -0
  29. package/skills/rust-shapeshift/resources/zero_cost_state_machines_and_enum_dispatch.md +162 -0
  30. package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +1 -1
@@ -0,0 +1,136 @@
1
+ # Enum Variant Boxing & Stack Squashing
2
+
3
+ In Rust systems architecture, an `enum`'s in-memory layout is determined by its largest variant:
4
+ $$\text{size\_of::<Enum>()} = \max(\text{size\_of::<Variant}_i\text{>()}) + \text{discriminant} + \text{alignment padding}$$
5
+
6
+ When a single oversized variant is added to a protocol, domain event, or state machine, **every single instance of that enum—even zero-sized unit variants—allocates that maximum size on the stack**.
7
+
8
+ In high-concurrency Tokio applications with 50,000+ active connections or recursive async task trees, oversized enums bloat the compiler-generated `Future` state machines, multiplying idle RAM consumption into tens of megabytes.
9
+
10
+ This reference guide documents how to squash enum footprints using variant boxing, compile-time size guards, and zero-cost pattern matching.
11
+
12
+ ---
13
+
14
+ ## 1. The Async Task Multiplication Trap
15
+
16
+ Consider a typical message event enum in a gateway or websocket server:
17
+
18
+ ```rust
19
+ use std::mem::size_of;
20
+
21
+ pub struct PingPayload; // 0 bytes
22
+
23
+ pub struct MessagePayload {
24
+ pub raw_buffer: [u8; 1024], // 1024 bytes!
25
+ pub header_len: usize,
26
+ }
27
+
28
+ // NAIVE: Size of Event is 1024 + 8 + 8 (discriminant + padding) = 1040 bytes!
29
+ pub enum NaiveEvent {
30
+ Ping(PingPayload),
31
+ Heartbeat,
32
+ Data(MessagePayload),
33
+ }
34
+
35
+ assert_eq!(size_of::<NaiveEvent>(), 1040);
36
+ ```
37
+
38
+ ### The Async Consequence
39
+ In Tokio, when an async task holds `NaiveEvent` across an `.await` boundary:
40
+ ```rust
41
+ async fn process_event(event: NaiveEvent) {
42
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
43
+ match event { /* ... */ }
44
+ }
45
+ ```
46
+ The compiler captures `NaiveEvent` inside the generator state machine:
47
+ - 50,000 idle tasks $\times$ 1,040 bytes $\approx$ **52 MB of RAM** consumed by empty padding while waiting on I/O.
48
+ - Even if 99.9% of messages are small `Heartbeat` or `Ping` packets, memory is allocated as if every message is a full 1KB payload.
49
+
50
+ ---
51
+
52
+ ## 2. The Solution: Boxing Oversized Variants
53
+
54
+ By wrapping variants exceeding 128 bytes in a `Box<T>`, the variant's stack footprint collapses into a single 8-byte heap pointer:
55
+
56
+ ```rust
57
+ use std::mem::size_of;
58
+
59
+ pub struct MessagePayload {
60
+ pub raw_buffer: [u8; 1024],
61
+ pub header_len: usize,
62
+ }
63
+
64
+ // SQUASHED: Maximum variant size is now 8 bytes (Box pointer)
65
+ pub enum SquashedEvent {
66
+ Ping,
67
+ Heartbeat,
68
+ Data(Box<MessagePayload>), // 8-byte pointer on 64-bit targets
69
+ }
70
+
71
+ // Size is 8 (pointer) + 8 (discriminant tag + padding) = 16 bytes!
72
+ const _: () = assert!(size_of::<SquashedEvent>() == 16);
73
+ ```
74
+
75
+ ### Memory Savings Comparison
76
+ | Metric | Naive Enum | Squashed (Boxed) Enum | Savings |
77
+ |---|---|---|---|
78
+ | **Single Enum Size** | 1,040 bytes | 16 bytes | **98.4% reduction** |
79
+ | **50,000 Tasks (Heartbeat)** | 52.0 MB | 0.8 MB | **51.2 MB reclaimed** |
80
+ | **L1 Data Cache (32KB)** | Holds ~30 events | Holds ~2,000 events | **66x cache density** |
81
+
82
+ Heap allocation is now triggered **only when the rare large variant is instantiated**, leaving the high-frequency ping/heartbeat paths 100% zero-allocation.
83
+
84
+ ---
85
+
86
+ ## 3. Pattern Matching and Moving Out of Box
87
+
88
+ Rust allows matching directly on boxed payloads without double-referencing:
89
+
90
+ ```rust
91
+ pub fn handle_event(event: SquashedEvent) {
92
+ match event {
93
+ SquashedEvent::Ping => {
94
+ // 0 heap, 0 pointer dereference
95
+ }
96
+ SquashedEvent::Heartbeat => {
97
+ // 0 heap, 0 pointer dereference
98
+ }
99
+ SquashedEvent::Data(boxed_payload) => {
100
+ // boxed_payload is Box<MessagePayload>
101
+ // Unbox value if needed, or process via deref
102
+ let payload: MessagePayload = *boxed_payload;
103
+ println!("Processed header len: {}", payload.header_len);
104
+ }
105
+ }
106
+ }
107
+ ```
108
+
109
+ ---
110
+
111
+ ## 4. Compile-Time Guard with Static Assertions
112
+
113
+ To prevent teammates or AI agents from accidentally adding unboxed bulky structs into the enum in the future, enforce a static size assertion:
114
+
115
+ ```rust
116
+ pub enum ServiceCommand {
117
+ ReloadConfig,
118
+ DrainConnections,
119
+ UpdateSession(Box<SessionUpdate>),
120
+ }
121
+
122
+ // Fails compilation if any future refactor pushes the enum above 24 bytes!
123
+ const _: () = assert!(
124
+ std::mem::size_of::<ServiceCommand>() <= 24,
125
+ "ServiceCommand exceeds 24-byte memory budget! Box large variants."
126
+ );
127
+ ```
128
+
129
+ ---
130
+
131
+ ## 5. Architectural Checklist for Enums
132
+
133
+ 1. Run `cargo clippy -- -W clippy::large_enum_variant` to find unboxed variants.
134
+ 2. If the size difference between the smallest and largest variant exceeds **128 bytes**, box the largest variant.
135
+ 3. For recursive data structures (trees, ASTs, JSON representations), always box child enum nodes.
136
+ 4. Enforce `const _: () = assert!(size_of::<MyEnum>() <= BUDGET);` for core protocol types.
@@ -6,7 +6,7 @@ A frequent failure mode in Rust backend engineering is choosing a web framework
6
6
 
7
7
  Reaching for Tokio and Axum for an ephemeral monitoring sidecar wastes 20MB–40MB of memory on unused thread pools. Conversely, hand-rolling HTTP/1.1 parsers with `std::net` for a complex SaaS application wastes months reinventing routing, OpenAPI schemas, and multipart streams.
8
8
 
9
- This playbook provides an objective, production-tested **Selection Matrix** comparing **Zero-Dependency Manual (`std::net`)**, **Axum**, **Actix Web**, **Salvo**, **Poem**, **Rocket**, and **Loco**.
9
+ This reference guide provides an objective, production-tested **Selection Matrix** comparing **Zero-Dependency Manual (`std::net`)**, **Axum**, **Actix Web**, **Salvo**, **Poem**, **Rocket**, and **Loco**.
10
10
 
11
11
  ---
12
12
 
@@ -4,7 +4,7 @@ In GraphQL APIs, memory efficiency cannot be guaranteed by standard HTTP body li
4
4
 
5
5
  Without strict schema-level containment, a single recursive GraphQL query can allocate hundreds of thousands of intermediate async futures, blowing process RSS past gigabytes in milliseconds.
6
6
 
7
- This playbook documents how to build a high-throughput, memory-contained GraphQL server using **`async-graphql`** and **`async-graphql-axum`**.
7
+ This reference guide documents how to build a high-throughput, memory-contained GraphQL server using **`async-graphql`** and **`async-graphql-axum`**.
8
8
 
9
9
  ---
10
10
 
@@ -6,7 +6,7 @@ In dynamic languages (JavaScript / Python), developers habitually call regex rep
6
6
 
7
7
  ## 1. Zero-Regex Whitespace Squeezing (Single-Pass Iterator)
8
8
 
9
- In `jandapress/src/scraper/pururin.rs`, collapsing newlines and multiple spaces into a single space is executed on every parsed tag.
9
+ In high-volume HTML scraping, collapsing newlines and multiple spaces into a single space is executed on every parsed tag.
10
10
 
11
11
  Instead of running a regex engine, this single-pass character iterator performs zero regex compilation and minimal allocations:
12
12
 
@@ -35,7 +35,7 @@ pub fn squeeze_whitespace(value: &str) -> String {
35
35
 
36
36
  ## 2. Integer Arithmetic Over Heavy Date/Time Crates
37
37
 
38
- In `lustpress/src/util.rs`, converting video duration in seconds into `"{m}min, {s}sec"` format is called on hundreds of items per search request.
38
+ In media metadata processing, converting duration in seconds into `"{m}min, {s}sec"` format is called on hundreds of items per search request.
39
39
 
40
40
  Instead of creating DateTime objects or calling heavy formatting libraries, use native CPU integer division and modulo:
41
41
 
@@ -69,7 +69,7 @@ pub fn encode_query(val: &str) -> String {
69
69
 
70
70
  ## 4. Static Regex Compilation with `LazyLock<Regex>`
71
71
 
72
- When regular expressions are strictly required (such as mathematical challenge extraction in `lustpress/src/fetch.rs`), **NEVER** construct `Regex::new(...)` inside function bodies.
72
+ When regular expressions are strictly required (such as mathematical challenge token extraction), **NEVER** construct `Regex::new(...)` inside function bodies.
73
73
 
74
74
  Always compile regex patterns once into static memory:
75
75
 
@@ -0,0 +1,185 @@
1
+ # Lock-Free Circular Ring Buffers and Disruptor Pattern
2
+
3
+ In concurrent pipelines transferring millions of events, telemetry metrics, or network packets per second, standard synchronization channels (`tokio::sync::mpsc`, `crossbeam_channel`, or `std::sync::mpsc`) introduce noticeable performance bottlenecks:
4
+ 1. **Dynamic Node Allocations**: Many channel implementations allocate heap memory for queue segments or nodes during sustained bursts.
5
+ 2. **Lock & Atomic Bus Contention**: Producers and consumers competing on shared atomic cursors cause cache-line bouncing across multi-core CPU architectures.
6
+ 3. **Latency Jitter**: Memory allocators and thread wakeups create unpredictable p99/p99.99 latency spikes.
7
+
8
+ The **Disruptor Pattern** and **Fixed-Capacity Lock-Free Ring Buffers** eliminate dynamic allocations entirely by pre-allocating a contiguous circular buffer at startup and using hardware cache-aligned atomic sequence barriers.
9
+
10
+ ---
11
+
12
+ ## 1. Single-Producer Single-Consumer (SPSC) Ring Buffer with `rtrb`
13
+
14
+ For ultra-low-latency pipelines where a single dedicated reader thread receives messages from a single worker, an SPSC lock-free ring buffer provides sub-nanosecond operations with zero locks.
15
+
16
+ Add `rtrb` to `Cargo.toml`:
17
+ ```toml
18
+ [dependencies]
19
+ rtrb = "0.3"
20
+ ```
21
+
22
+ ### High-Throughput SPSC Pipeline
23
+
24
+ ```rust
25
+ use rtrb::{RingBuffer, Producer, Consumer};
26
+ use std::thread;
27
+
28
+ pub struct TelemetryEvent {
29
+ pub timestamp_ns: u64,
30
+ pub event_id: u32,
31
+ pub metric_value: f64,
32
+ }
33
+
34
+ pub fn create_spsc_telemetry_pipeline(capacity: usize) -> (Producer<TelemetryEvent>, Consumer<TelemetryEvent>) {
35
+ // Allocates fixed memory chunk once at startup. Zero allocations during runtime.
36
+ RingBuffer::new(capacity)
37
+ }
38
+
39
+ pub fn run_pipeline_demo() {
40
+ let (mut producer, mut consumer) = create_spsc_telemetry_pipeline(65_536);
41
+
42
+ // Producer Thread
43
+ let producer_handle = thread::spawn(move || {
44
+ for i in 0..1_000_000 {
45
+ let event = TelemetryEvent {
46
+ timestamp_ns: i,
47
+ event_id: (i % 256) as u32,
48
+ metric_value: 42.0,
49
+ };
50
+
51
+ // Non-blocking push. If buffer is full, backpressure strategy takes over.
52
+ while let Err(e) = producer.push(event) {
53
+ // Cooperative yield or micro-spin
54
+ std::hint::spin_loop();
55
+ }
56
+ }
57
+ });
58
+
59
+ // Consumer Thread
60
+ let consumer_handle = thread::spawn(move || {
61
+ let mut received = 0;
62
+ while received < 1_000_000 {
63
+ if let Ok(event) = consumer.pop() {
64
+ received += 1;
65
+ let _val = event.metric_value;
66
+ } else {
67
+ std::hint::spin_loop();
68
+ }
69
+ }
70
+ });
71
+
72
+ producer_handle.join().unwrap();
73
+ consumer_handle.join().unwrap();
74
+ }
75
+ ```
76
+
77
+ ---
78
+
79
+ ## 2. Multi-Producer Multi-Consumer (MPMC) with `crossbeam::queue::ArrayQueue`
80
+
81
+ When multiple Tokio worker threads or OS threads must push to a shared bounded queue without heap allocations or unbounded memory growth, use `ArrayQueue`.
82
+
83
+ Add `crossbeam-queue` to `Cargo.toml`:
84
+ ```toml
85
+ [dependencies]
86
+ crossbeam-queue = "0.3"
87
+ ```
88
+
89
+ ```rust
90
+ use crossbeam_queue::ArrayQueue;
91
+ use std::sync::Arc;
92
+
93
+ pub struct BoundedEventBroker<T> {
94
+ queue: Arc<ArrayQueue<T>>,
95
+ }
96
+
97
+ impl<T> BoundedEventBroker<T> {
98
+ pub fn new(capacity: usize) -> Self {
99
+ Self {
100
+ // Strictly bounded fixed-size heap allocation
101
+ queue: Arc::new(ArrayQueue::new(capacity)),
102
+ }
103
+ }
104
+
105
+ /// Pushes event without allocating. Returns Err(event) if at capacity (sheds load).
106
+ #[inline(always)]
107
+ pub fn try_publish(&self, item: T) -> Result<(), T> {
108
+ self.queue.push(item)
109
+ }
110
+
111
+ /// Pulls event with zero lock contention
112
+ #[inline(always)]
113
+ pub fn try_consume(&self) -> Option<T> {
114
+ self.queue.pop()
115
+ }
116
+
117
+ pub fn len(&self) -> usize {
118
+ self.queue.len()
119
+ }
120
+
121
+ pub fn is_full(&self) -> bool {
122
+ self.queue.is_full()
123
+ }
124
+ }
125
+ ```
126
+
127
+ ---
128
+
129
+ ## 3. Cache Line Alignment for Atomic Cursors (False Sharing Prevention)
130
+
131
+ When building custom ring buffers, producers and consumers maintain atomic sequence numbers (head and tail pointers). If the head and tail atomics share the same 64-byte CPU cache line, multi-core writes cause severe CPU cache invalidation loops:
132
+
133
+ ```rust
134
+ use std::sync::atomic::{AtomicU64, Ordering};
135
+
136
+ // CAUTION: False sharing hazard!
137
+ // head and tail reside on the same cache line. Every producer write invalidates consumer cache.
138
+ pub struct BadCursor {
139
+ pub head: AtomicU64, // Offset 0..8
140
+ pub tail: AtomicU64, // Offset 8..16
141
+ }
142
+
143
+ // CORRECT: Cache line alignment isolates each cursor to its own 64-byte line
144
+ #[repr(align(64))]
145
+ pub struct CacheAlignedCursor {
146
+ pub cursor: AtomicU64,
147
+ }
148
+
149
+ pub struct TrueDisruptorRing {
150
+ pub head: CacheAlignedCursor, // Occupies dedicated 64B cache line
151
+ pub tail: CacheAlignedCursor, // Occupies dedicated 64B cache line
152
+ pub mask: usize, // Power-of-two bitmask (capacity - 1)
153
+ }
154
+
155
+ impl TrueDisruptorRing {
156
+ pub fn new(power_of_two_capacity: usize) -> Self {
157
+ assert!(power_of_two_capacity.is_power_of_two(), "Capacity must be power of two");
158
+ Self {
159
+ head: CacheAlignedCursor { cursor: AtomicU64::new(0) },
160
+ tail: CacheAlignedCursor { cursor: AtomicU64::new(0) },
161
+ mask: power_of_two_capacity - 1,
162
+ }
163
+ }
164
+
165
+ #[inline(always)]
166
+ pub fn compute_slot_index(&self, sequence: u64) -> usize {
167
+ // Fast bitwise AND replaces expensive modulo operator (sequence % capacity)
168
+ (sequence as usize) & self.mask
169
+ }
170
+ }
171
+ ```
172
+
173
+ ---
174
+
175
+ ## 4. Architectural Rules for Ring Buffer Systems
176
+
177
+ 1. **Power-of-Two Capacity**:
178
+ - Always choose capacities that are powers of two ($2^{16} = 65,536$, $2^{20} = 1,048,576$). This replaces the expensive CPU division/modulo instruction (`% capacity`) with a single-cycle bitwise AND (`& mask`).
179
+ 2. **Explicit Backpressure Policy**:
180
+ - When the ring is full, make an explicit architectural decision:
181
+ - **Drop Oldest** (for live telemetry and market data feeds).
182
+ - **Fast-Fail / Shed Load** (return HTTP 503 / queue full).
183
+ - **Exponential Backoff** (`std::hint::spin_loop` ➔ `thread::yield_now` ➔ async sleep).
184
+ 3. **Batch Draining**:
185
+ - Consumers should drain items in batches (e.g. 64–256 items at a time) to amortize atomic synchronization overhead and optimize CPU L1 cache throughput.
@@ -0,0 +1,151 @@
1
+ # Memory-Mapped Files and Zero-Copy Paging Architecture
2
+
3
+ When applications process large binary datasets, disk caches, persistent logs, or static web assets, using standard filesystem APIs like `tokio::fs::read` or `std::fs::File::read_to_end` forces the OS to copy entire files into userspace heap buffers (`Vec<u8>`). This spikes process Resident Set Size (RSS), strains the allocator, and risks triggering Linux OOMKilled (Exit Code 137).
4
+
5
+ Memory-mapped file I/O delegates paging to the Linux Virtual Memory Subsystem and Page Cache, achieving **sub-megabyte memory footprints** even when processing multi-gigabyte files.
6
+
7
+ ---
8
+
9
+ ## 1. How Memory Mapping Prevents RSS Bloat
10
+
11
+ Standard read vs. memory-mapped I/O:
12
+
13
+ | Metric / Behavior | Standard `File::read_to_end` | Memory Mapping (`memmap2`) |
14
+ |---|---|---|
15
+ | **Userspace Heap Allocation** | Full file size allocated in heap `Vec<u8>` | **0 bytes** allocated on heap |
16
+ | **OS Page Cache Duplication** | 2x (Kernel page cache + userspace buffer) | **1x** (Userspace directly maps page cache) |
17
+ | **Memory Eviction Under Pressure** | None (OS cannot free userspace heap) | **Automatic** (Kernel drops clean pages) |
18
+ | **Paging Granularity** | Eager bulk copy | **On-demand** (4KB page faults as touched) |
19
+ | **OOM Risk** | High for files > available RAM | **Zero** (Pages flushed/evicted dynamically) |
20
+
21
+ ---
22
+
23
+ ## 2. Zero-Copy File Inspection with `memmap2`
24
+
25
+ Add `memmap2` to `Cargo.toml`:
26
+ ```toml
27
+ [dependencies]
28
+ memmap2 = "0.9"
29
+ ```
30
+
31
+ ### Read-Only Zero-Copy Memory Map with Kernel Advice
32
+
33
+ ```rust
34
+ use memmap2::{Mmap, MmapOptions, Advice};
35
+ use std::fs::File;
36
+ use std::path::Path;
37
+ use std::io::{Result, Error, ErrorKind};
38
+
39
+ pub struct PagedFileStorage {
40
+ file: File,
41
+ mmap: Mmap,
42
+ }
43
+
44
+ impl PagedFileStorage {
45
+ pub fn open(path: impl AsRef<Path>) -> Result<Self> {
46
+ let file = File::open(path)?;
47
+ let metadata = file.metadata()?;
48
+
49
+ if metadata.len() == 0 {
50
+ return Err(Error::new(ErrorKind::InvalidData, "Cannot mmap zero-length file"));
51
+ }
52
+
53
+ // Safety: File is opened read-only and no concurrent writes are made
54
+ // by this process. Underlying file descriptor must not be truncated externally.
55
+ let mmap = unsafe { MmapOptions::new().map(&file)? };
56
+
57
+ // Kernel hint: Sequential reading optimization
58
+ #[cfg(target_os = "linux")]
59
+ let _ = mmap.advise(Advice::Sequential);
60
+
61
+ Ok(Self { file, mmap })
62
+ }
63
+
64
+ /// Read a subslice with zero heap allocation
65
+ #[inline(always)]
66
+ pub fn read_slice(&self, offset: usize, length: usize) -> Option<&[u8]> {
67
+ self.mmap.get(offset..offset + length)
68
+ }
69
+
70
+ /// Advise kernel that a memory range is no longer needed in physical RAM
71
+ pub fn release_range_from_ram(&self, offset: usize, length: usize) {
72
+ #[cfg(target_os = "linux")]
73
+ let _ = self.mmap.advise_range(Advice::DontNeed, offset, length);
74
+ }
75
+
76
+ pub fn total_bytes(&self) -> usize {
77
+ self.mmap.len()
78
+ }
79
+ }
80
+ ```
81
+
82
+ ---
83
+
84
+ ## 3. High-Performance Zero-Copy Static Asset Serving (Axum 0.8)
85
+
86
+ In web services, serving static files via `tokio::fs::read` loads file contents into per-request heap buffers. Under high concurrent traffic, 100 concurrent requests for a 10MB file consume 1GB of RSS.
87
+
88
+ Using `memmap2` allows hundreds of concurrent requests to borrow directly from the same shared kernel page cache:
89
+
90
+ ```rust
91
+ use axum::{
92
+ extract::{Path as AxumPath, State},
93
+ http::{header, HeaderMap, StatusCode},
94
+ response::IntoResponse,
95
+ routing::get,
96
+ Router,
97
+ };
98
+ use memmap2::Mmap;
99
+ use std::collections::HashMap;
100
+ use std::fs::File;
101
+ use std::sync::Arc;
102
+
103
+ pub struct SharedAssetCache {
104
+ mapped_assets: HashMap<String, Arc<Mmap>>,
105
+ }
106
+
107
+ impl SharedAssetCache {
108
+ pub fn new() -> Self {
109
+ Self {
110
+ mapped_assets: HashMap::new(),
111
+ }
112
+ }
113
+
114
+ pub fn preload_asset(&mut self, route_key: &str, file_path: &str) -> std::io::Result<()> {
115
+ let file = File::open(file_path)?;
116
+ // Safety: Read-only memory map for immutable server assets
117
+ let mmap = unsafe { Mmap::map(&file)? };
118
+ self.mapped_assets.insert(route_key.to_string(), Arc::new(mmap));
119
+ Ok(())
120
+ }
121
+ }
122
+
123
+ pub async fn serve_mmap_asset(
124
+ AxumPath(asset_name): AxumPath<String>,
125
+ State(cache): State<Arc<SharedAssetCache>>,
126
+ ) -> Result<impl IntoResponse, StatusCode> {
127
+ let mmap = cache.mapped_assets.get(&asset_name).ok_or(StatusCode::NOT_FOUND)?;
128
+
129
+ // Zero userspace copying: bytes are streamed directly from shared OS pages
130
+ let bytes = mmap.as_ref();
131
+ let body_slice = bytes.to_vec(); // Or wrap in bytes::Bytes::from_static if static lifetime
132
+
133
+ let mut headers = HeaderMap::new();
134
+ headers.insert(header::CONTENT_TYPE, "application/octet-stream".parse().unwrap());
135
+ headers.insert(header::CONTENT_LENGTH, mmap.len().into());
136
+
137
+ Ok((headers, body_slice))
138
+ }
139
+ ```
140
+
141
+ ---
142
+
143
+ ## 4. Safety Invariants & Mitigation
144
+
145
+ 1. **External File Truncation (SIGBUS Defense)**:
146
+ - If another process on Linux truncates an open mapped file while your service reads beyond the new EOF, the kernel generates a `SIGBUS` signal.
147
+ - **Mitigation**: Exclusively map files owned by the service process, enforce read-only filesystem permissions, or verify file size via `file.metadata()?.len()`.
148
+
149
+ 2. **Writable Memory Maps (`MmapMut`)**:
150
+ - For Write-Ahead Logs (WAL) or shared ring buffers, use `MmapMut::map_mut(&file)`.
151
+ - Call `mmap.flush_async()?` or `mmap.flush()?` to persist dirty pages deterministically without blocking the Tokio reactor loop.
@@ -0,0 +1,124 @@
1
+ # Numeric Safety & Saturating Arithmetic
2
+
3
+ In production services, integer overflow, uncontrolled bit truncation via `as` casts, and IEEE 754 floating-point comparisons represent critical runtime hazards.
4
+
5
+ In debug builds, unhandled integer overflow triggers a process panic. In release builds, integer overflow wraps silently via two's complement. In high-frequency metrics pipelines, financial engines, and token-bucket rate limiters, unhandled numeric edge cases lead to negative balances, infinite rate-limit allowances, or unexpected process aborts.
6
+
7
+ This reference guide documents zero-cost numeric disciplines: explicit overflow handling (`saturating_*`, `checked_*`, `wrapping_*`), safe narrowing via `TryFrom`, and deterministic floating-point ordering.
8
+
9
+ ---
10
+
11
+ ## 1. The Four Arithmetic Intents
12
+
13
+ Instead of relying on ambiguous operators (`+`, `-`, `*`), production services must declare explicit mathematical intent:
14
+
15
+ | Method | Behavior on Overflow | Best Production Use Case |
16
+ |---|---|---|
17
+ | **`saturating_*`** | Clamps at `MAX` or `MIN` (never overflows) | **Rate limiters, metrics counters, gauge tracking** |
18
+ | **`checked_*`** | Returns `None` on overflow | **Financial ledgers, memory buffer pre-sizing** |
19
+ | **`wrapping_*`** | Explicitly wraps modulo $2^N$ | **Hash algorithms, ring buffers, sequence numbers** |
20
+ | **`overflowing_*`** | Returns `(value, has_overflowed)` | **Low-level crypto primitives, multi-word math** |
21
+
22
+ ### Code Example: Production Token Bucket
23
+ ```rust
24
+ pub struct TokenBucket {
25
+ pub available_tokens: u64,
26
+ pub max_capacity: u64,
27
+ }
28
+
29
+ impl TokenBucket {
30
+ pub fn refill(&mut self, added: u64) {
31
+ // ZERO-PANIC: Automatically caps at max_capacity without overflow risk
32
+ self.available_tokens = self
33
+ .available_tokens
34
+ .saturating_add(added)
35
+ .min(self.max_capacity);
36
+ }
37
+
38
+ pub fn try_consume(&mut self, cost: u64) -> bool {
39
+ // ZERO-PANIC: Returns None if cost > available_tokens
40
+ if let Some(remaining) = self.available_tokens.checked_sub(cost) {
41
+ self.available_tokens = remaining;
42
+ true
43
+ } else {
44
+ false
45
+ }
46
+ }
47
+ }
48
+ ```
49
+
50
+ ### Hardware Efficiency of Saturating Arithmetic
51
+ Modern x86_64 and ARM64 CPUs implement hardware saturation instructions. Rust's `saturating_add` and `saturating_sub` compile down to **1–2 machine instructions** (e.g. `add` + conditional move on x86, or native saturating instructions on ARM), with **zero conditional panic branches** in the generated assembly.
52
+
53
+ ---
54
+
55
+ ## 2. Eliminating the Silent Truncation Trap of `as`
56
+
57
+ Using `as` for narrowing numeric conversions silently drops the upper bits, creating severe data corruption bugs:
58
+
59
+ ```rust
60
+ // HAZARD: 65,537 exceeds u16::MAX (65,535)
61
+ let large_port: u32 = 65_537;
62
+ let port: u16 = large_port as u16; // SILENT TRUNCATION! port is now 1!
63
+ assert_eq!(port, 1);
64
+ ```
65
+
66
+ ### The Solution: Safe Narrowing with `TryFrom`
67
+ Use `TryFrom` / `TryInto` to detect narrowing failures at runtime without panicking:
68
+
69
+ ```rust
70
+ use std::convert::TryFrom;
71
+
72
+ pub fn parse_port(val: u32) -> Result<u16, &'static str> {
73
+ u16::try_from(val).map_err(|_| "Port number exceeds 65535 boundary")
74
+ }
75
+
76
+ assert!(parse_port(65_537).is_err());
77
+ assert_eq!(parse_port(8080).unwrap(), 8080);
78
+ ```
79
+
80
+ For widening conversions (e.g. `u16` to `u32`), always use `u32::from(val)`, which is guaranteed to be lossless and verified at compile time.
81
+
82
+ ---
83
+
84
+ ## 3. Floating-Point Comparisons & Ordering
85
+
86
+ Because IEEE 754 floating-point numbers include `NaN` (Not a Number) and negative zero (`-0.0`), floats do not implement `Eq` or `Ord`:
87
+
88
+ ```rust
89
+ let x = f64::NAN;
90
+ assert!(!(x == x)); // NaN is not equal to itself!
91
+ ```
92
+
93
+ ### Safe Equality Check with Epsilon
94
+ Never compare floating-point numbers with `==`. Compare within an acceptable tolerance:
95
+
96
+ ```rust
97
+ pub fn approx_equal(a: f64, b: f64, epsilon: f64) -> bool {
98
+ (a - b).abs() < epsilon
99
+ }
100
+
101
+ assert!(approx_equal(0.1 + 0.2, 0.3, 1e-10));
102
+ ```
103
+
104
+ ### Safe Sorting with `f64::total_cmp`
105
+ Calling standard `.sort()` on `Vec<f64>` fails to compile because floats do not implement `Ord`. Using naive `.partial_cmp().unwrap()` panics in production if a slice contains `NaN`.
106
+
107
+ Use `f64::total_cmp`, which enforces a total ordering across all IEEE 754 values (including `NaN` and `-0.0`):
108
+
109
+ ```rust
110
+ pub fn sort_latencies(latencies: &mut [f64]) {
111
+ // ZERO-PANIC: total_cmp handles NaN and infinities predictably
112
+ latencies.sort_by(|a, b| a.total_cmp(b));
113
+ }
114
+ ```
115
+
116
+ ---
117
+
118
+ ## 4. Architectural Checklist for Numeric Safety
119
+
120
+ 1. Enforce `#![warn(clippy::cast_possible_truncation, clippy::cast_sign_loss)]` to catch unsafe `as` casts.
121
+ 2. Use `saturating_*` for token buckets, rate limiters, gauges, and queue counters.
122
+ 3. Use `checked_*` for monetary balances, slice indexing math, and memory allocations.
123
+ 4. Always use `TryFrom` for narrowing integer casts.
124
+ 5. Sort floating-point metrics using `.sort_by(f64::total_cmp)`.
@@ -2,7 +2,7 @@
2
2
 
3
3
  In Rust systems architecture, memory safety and extreme runtime efficiency are direct consequences of the **Ownership and Borrow Checker Permission Model**. Novice developers and unguided AI agents frequently resort to `.clone()` as a crutch to bypass compiler borrow errors, introducing unnecessary heap churn, latency spikes, and CPU cache misses.
4
4
 
5
- This playbook provides the authoritative **Decision Matrix** for placing data on the Stack vs Heap, mastering the Borrow Checker's permission mechanics, and applying strict visibility encapsulation.
5
+ This reference guide provides the authoritative **Decision Matrix** for placing data on the Stack vs Heap, mastering the Borrow Checker's permission mechanics, and applying strict visibility encapsulation.
6
6
 
7
7
  ---
8
8