@sinkaroid/rust-shapeshift 1.0.5 → 1.0.8
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.
- package/README.md +73 -5
- package/package.json +6 -6
- package/skills/rust-shapeshift/SKILL.md +73 -27
- package/skills/rust-shapeshift/resources/anti_bot_and_cookie_challenges.md +1 -1
- package/skills/rust-shapeshift/resources/cache_line_alignment_and_struct_layout.md +1 -1
- package/skills/rust-shapeshift/resources/collection_reuse_and_capacity_retention.md +135 -0
- package/skills/rust-shapeshift/resources/concurrency_primitives_and_lock_contention.md +1 -1
- package/skills/rust-shapeshift/resources/deadlock_elimination_and_locks_across_await.md +149 -0
- package/skills/rust-shapeshift/resources/docker_slimming_and_build_hygiene.md +1 -1
- package/skills/rust-shapeshift/resources/dom_and_scraper_pruning.md +47 -23
- package/skills/rust-shapeshift/resources/enum_variant_boxing_and_stack_squashing.md +136 -0
- package/skills/rust-shapeshift/resources/framework_and_stack_selection_matrix.md +1 -1
- package/skills/rust-shapeshift/resources/graphql_memory_and_query_containment.md +1 -1
- package/skills/rust-shapeshift/resources/lock_free_ring_buffers_and_disruptor.md +185 -0
- package/skills/rust-shapeshift/resources/memory_mapped_files_and_zero_copy_paging.md +151 -0
- package/skills/rust-shapeshift/resources/numeric_safety_and_saturating_arithmetic.md +124 -0
- package/skills/rust-shapeshift/resources/ownership_borrowing_and_memory_decisions.md +1 -1
- package/skills/rust-shapeshift/resources/production_memory_leak_diagnostics_and_ebpf.md +120 -0
- package/skills/rust-shapeshift/resources/real_world_testing_and_dom_fixtures.md +378 -0
- package/skills/rust-shapeshift/resources/realtime_websocket_and_connection_scaling.md +1 -1
- package/skills/rust-shapeshift/resources/stack_inlining_and_allocation_reduction.md +1 -1
- package/skills/rust-shapeshift/resources/telemetry_and_metrics.md +1 -1
- package/skills/rust-shapeshift/resources/zero_allocation_error_architecture.md +1 -1
- package/skills/rust-shapeshift/resources/zero_copy_serde_and_streaming_serialization.md +1 -1
- package/skills/rust-shapeshift/resources/zero_copy_zero_alloc_serialization_rkyv.md +135 -0
- package/skills/rust-shapeshift/resources/zero_cost_iterators_and_pipeline_inlining.md +121 -0
- package/skills/rust-shapeshift/resources/zero_cost_state_machines_and_enum_dispatch.md +162 -0
- package/skills/rust-shapeshift/resources/zero_panic_and_router_architecture.md +1 -1
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# Zero-Cost Iterators & Pipeline Inlining
|
|
2
|
+
|
|
3
|
+
In high-throughput Rust services, data transformation loops (filtering HTTP headers, parsing delimiter streams, normalizing metrics) frequently fall victim to **intermediate allocation bloat**.
|
|
4
|
+
|
|
5
|
+
Developers migrating from languages like Python, JavaScript, or Java commonly chain `.collect::<Vec<_>>()` at intermediate stages of a pipeline. Each `.collect()` forces a heap allocation, dynamic vector resizing, and redundant cache-line churn before the next transformation even begins.
|
|
6
|
+
|
|
7
|
+
This reference guide documents how to construct purely lazy, zero-allocation iterator pipelines that LLVM compiles down to single-pass vectorized machine loops.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## 1. The Intermediate `.collect()` Anti-Pattern
|
|
12
|
+
|
|
13
|
+
### Naive Implementation (Multiple Allocations & Cache Misses)
|
|
14
|
+
```rust
|
|
15
|
+
// ANTI-PATTERN: Allocates 2 heap vectors for a simple pipeline!
|
|
16
|
+
pub fn process_metrics_naive(raw: &[i64]) -> Vec<i64> {
|
|
17
|
+
// Allocation #1: intermediate filtered vector
|
|
18
|
+
let positive: Vec<i64> = raw.iter().copied().filter(|&x| x > 0).collect();
|
|
19
|
+
|
|
20
|
+
// Allocation #2: final mapped vector
|
|
21
|
+
let doubled: Vec<i64> = positive.into_iter().map(|x| x * 2).collect();
|
|
22
|
+
|
|
23
|
+
doubled
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Zero-Allocation Lazy Inlining (Zero Heap Overhead)
|
|
28
|
+
```rust
|
|
29
|
+
// ZERO-COST: Evaluated in a single pass directly into the final container
|
|
30
|
+
pub fn process_metrics_optimal(raw: &[i64]) -> Vec<i64> {
|
|
31
|
+
raw.iter()
|
|
32
|
+
.copied()
|
|
33
|
+
.filter(|&x| x > 0)
|
|
34
|
+
.map(|x| x * 2)
|
|
35
|
+
.collect() // Exactly ONE allocation with pre-sized capacity when possible
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
In the optimal version, Rust's iterator combinators (`filter`, `map`, `take`) are zero-sized types (ZSTs) or small stack wrappers. LLVM fuses them together and inlines the entire pipeline into a single assembly loop, eliminating all intermediate heap allocations.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 2. In-Place Allocation Recycling with `.drain()`
|
|
44
|
+
|
|
45
|
+
When processing queues or batches inside worker loops, dropping and recreating a `Vec` causes continuous allocator churn. Use `.drain(..)` to consume elements while **preserving the underlying allocated capacity**:
|
|
46
|
+
|
|
47
|
+
```rust
|
|
48
|
+
pub struct BatchWorker {
|
|
49
|
+
buffer: Vec<String>,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
impl BatchWorker {
|
|
53
|
+
pub fn new(capacity: usize) -> Self {
|
|
54
|
+
Self {
|
|
55
|
+
buffer: Vec::with_capacity(capacity),
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// Processes items using an iterator and leaves `self.buffer` empty
|
|
60
|
+
/// with zero deallocations.
|
|
61
|
+
pub fn flush_and_process<F>(&mut self, mut processor: F)
|
|
62
|
+
where
|
|
63
|
+
F: FnMut(&str),
|
|
64
|
+
{
|
|
65
|
+
// .drain(..) produces an iterator that moves elements out of the buffer
|
|
66
|
+
// and restores len to 0 while keeping capacity intact!
|
|
67
|
+
for item in self.buffer.drain(..) {
|
|
68
|
+
processor(&item);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Buffer capacity remains completely intact for the next request cycle!
|
|
72
|
+
debug_assert_eq!(self.buffer.len(), 0);
|
|
73
|
+
debug_assert!(self.buffer.capacity() > 0);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## 3. Monomorphized `impl Iterator` vs `Box<dyn Iterator>`
|
|
81
|
+
|
|
82
|
+
When returning an iterator from a function or struct method, avoid dynamic trait objects (`Box<dyn Iterator>`), which introduce heap allocation and vtable indirect call penalties:
|
|
83
|
+
|
|
84
|
+
```rust
|
|
85
|
+
// BAD: Triggers heap allocation for the Box + dynamic vtable dispatch on every .next()
|
|
86
|
+
pub fn active_tokens_dyn<'a>(tokens: &'a [str]) -> Box<dyn Iterator<Item = &'a str> + 'a> {
|
|
87
|
+
Box::new(tokens.iter().copied().filter(|s| !s.is_empty()))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// GOOD: Zero heap allocation, fully inlined by LLVM at the call site
|
|
91
|
+
pub fn active_tokens_impl<'a>(tokens: &'a [str]) -> impl Iterator<Item = &'a str> + 'a {
|
|
92
|
+
tokens.iter().copied().filter(|s| !s.is_empty())
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
| Trait Form | Heap Allocations | Function Call Overhead | LLVM Inlining |
|
|
97
|
+
|---|---|---|---|
|
|
98
|
+
| `Box<dyn Iterator>` | 1 heap allocation (`Box`) | Indirect pointer jump | Prevented (virtual call) |
|
|
99
|
+
| `impl Iterator` | **0 heap allocations** | **0 overhead** | **Fully inlined & vectorized** |
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## 4. Batch Ingestion with `Extend` and Pre-Sizing
|
|
104
|
+
|
|
105
|
+
When appending multiple elements to an existing collection, avoid repeated `.push()` calls in a loop. Use `.extend()`, which leverages `Iterator::size_hint()` to pre-allocate capacity in a single resize:
|
|
106
|
+
|
|
107
|
+
```rust
|
|
108
|
+
pub fn ingest_records(target: &mut Vec<u32>, source: impl IntoIterator<Item = u32>) {
|
|
109
|
+
// Leverages TrustedLen specialization in stdlib for single-reallocation growth
|
|
110
|
+
target.extend(source);
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## 5. Architectural Checklist for Iterators
|
|
117
|
+
|
|
118
|
+
1. Never chain `.collect()` in the middle of a processing pipeline. Keep iterators lazy until the terminal consumer.
|
|
119
|
+
2. In hot worker loops, use `buffer.drain(..)` or `buffer.clear()` to reuse pre-allocated capacity.
|
|
120
|
+
3. Return `impl Iterator<Item = T>` instead of `Box<dyn Iterator<Item = T>>`.
|
|
121
|
+
4. Prefer iterators over manual indexing (`for i in 0..slice.len()`) to automatically eliminate bounds checks (`BCE`).
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# Zero-Cost State Machines and Enum Dispatch Architecture
|
|
2
|
+
|
|
3
|
+
In object-oriented and dynamically-typed runtimes, polymorphic dispatch and state machines are typically implemented via runtime interfaces, virtual method tables (vtables), or dynamic subclassing.
|
|
4
|
+
|
|
5
|
+
In Rust, using dynamic trait objects (`Box<dyn Trait>` or `&dyn Trait`):
|
|
6
|
+
1. **Requires Heap Allocation**: Storing heterogeneous implementations in collections requires `Box<dyn Trait>`, adding heap allocation and pointer indirection.
|
|
7
|
+
2. **Inhibits Compiler Inlining**: Calls through vtables cannot be inlined by LLVM, disabling loop unrolling and dead-code elimination.
|
|
8
|
+
3. **Breaks SIMD Vectorization**: The CPU cannot vectorize operations across unpredictable indirect function pointers.
|
|
9
|
+
|
|
10
|
+
Using **Compile-Time Enum Dispatch** (`enum_dispatch`) and **Type-State Pattern State Machines**, polymorphic behavior achieves **zero heap allocation, zero pointer chasing, and full LLVM inlining**.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 1. Dynamic Dispatch (`dyn Trait`) vs. Static Enum Dispatch
|
|
15
|
+
|
|
16
|
+
| Architectural Feature | Dynamic Dispatch (`Box<dyn Trait>`) | Static Enum Dispatch (`enum_dispatch`) |
|
|
17
|
+
|---|---|---|
|
|
18
|
+
| **Memory Allocation** | Heap (`Box<T>`) | **Stack (Inline discriminated union)** |
|
|
19
|
+
| **Pointer Indirection** | 2-word fat pointer (data ptr + vtable ptr) | **1 enum discriminant byte + data** |
|
|
20
|
+
| **LLVM Inlining** | No (indirect branch) | **Full inlining permitted** |
|
|
21
|
+
| **Branch Prediction** | Indirect call misprediction hazard | **Direct jump table / match statement** |
|
|
22
|
+
| **SIMD Auto-Vectorization** | Blocked | **Fully enabled** |
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 2. Zero-Allocation Polymorphism with `enum_dispatch`
|
|
27
|
+
|
|
28
|
+
Add `enum_dispatch` to `Cargo.toml`:
|
|
29
|
+
```toml
|
|
30
|
+
[dependencies]
|
|
31
|
+
enum_dispatch = "0.3"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Eliminating Dynamic Vtables
|
|
35
|
+
|
|
36
|
+
```rust
|
|
37
|
+
use enum_dispatch::enum_dispatch;
|
|
38
|
+
|
|
39
|
+
// Define the common trait
|
|
40
|
+
#[enum_dispatch]
|
|
41
|
+
pub trait StreamCodec {
|
|
42
|
+
fn encode(&self, payload: &[u8], output: &mut Vec<u8>);
|
|
43
|
+
fn is_compressed(&self) -> bool;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Concrete Implementations
|
|
47
|
+
pub struct RawCodec;
|
|
48
|
+
impl StreamCodec for RawCodec {
|
|
49
|
+
#[inline(always)]
|
|
50
|
+
fn encode(&self, payload: &[u8], output: &mut Vec<u8>) {
|
|
51
|
+
output.extend_from_slice(payload);
|
|
52
|
+
}
|
|
53
|
+
#[inline(always)]
|
|
54
|
+
fn is_compressed(&self) -> bool { false }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
pub struct ZstdCodec {
|
|
58
|
+
pub compression_level: i32,
|
|
59
|
+
}
|
|
60
|
+
impl StreamCodec for ZstdCodec {
|
|
61
|
+
#[inline(always)]
|
|
62
|
+
fn encode(&self, payload: &[u8], output: &mut Vec<u8>) {
|
|
63
|
+
// Zstd streaming compression logic...
|
|
64
|
+
output.extend_from_slice(payload);
|
|
65
|
+
}
|
|
66
|
+
#[inline(always)]
|
|
67
|
+
fn is_compressed(&self) -> bool { true }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Enum Dispatch replaces Box<dyn StreamCodec>
|
|
71
|
+
#[enum_dispatch(StreamCodec)]
|
|
72
|
+
pub enum PipelineCodec {
|
|
73
|
+
Raw(RawCodec),
|
|
74
|
+
Zstd(ZstdCodec),
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
pub fn execute_pipeline_stream(codecs: &[PipelineCodec], data: &[u8]) -> Vec<u8> {
|
|
78
|
+
let mut buffer = Vec::with_capacity(data.len());
|
|
79
|
+
|
|
80
|
+
// ZERO HEAP INDIRECTION: Dispatches via direct compiler-generated match.
|
|
81
|
+
// Inlines completely under LTO release builds.
|
|
82
|
+
for codec in codecs {
|
|
83
|
+
codec.encode(data, &mut buffer);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
buffer
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## 3. The Typestate Pattern: Zero-Cost Lifecycle State Machines
|
|
93
|
+
|
|
94
|
+
To prevent illegal lifecycle transitions (e.g. attempting to send data over an unauthenticated or disconnected socket), encode states as **Zero-Sized Types (ZSTs)** into the type system:
|
|
95
|
+
|
|
96
|
+
```rust
|
|
97
|
+
use std::marker::PhantomData;
|
|
98
|
+
|
|
99
|
+
// Lifecycle States (Zero-Sized Types - consume 0 bytes of memory)
|
|
100
|
+
pub struct Disconnected;
|
|
101
|
+
pub struct Connecting;
|
|
102
|
+
pub struct Authenticated;
|
|
103
|
+
|
|
104
|
+
pub struct SecureGatewayConnection<State> {
|
|
105
|
+
socket_fd: i32,
|
|
106
|
+
session_token: Option<String>,
|
|
107
|
+
_state: PhantomData<State>,
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
impl SecureGatewayConnection<Disconnected> {
|
|
111
|
+
pub fn new(fd: i32) -> Self {
|
|
112
|
+
Self {
|
|
113
|
+
socket_fd: fd,
|
|
114
|
+
session_token: None,
|
|
115
|
+
_state: PhantomData,
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
pub fn connect(self) -> SecureGatewayConnection<Connecting> {
|
|
120
|
+
// Socket connection logic...
|
|
121
|
+
SecureGatewayConnection {
|
|
122
|
+
socket_fd: self.socket_fd,
|
|
123
|
+
session_token: None,
|
|
124
|
+
_state: PhantomData,
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
impl SecureGatewayConnection<Connecting> {
|
|
130
|
+
pub fn authenticate(self, token: String) -> Result<SecureGatewayConnection<Authenticated>, Self> {
|
|
131
|
+
if !token.is_empty() {
|
|
132
|
+
Ok(SecureGatewayConnection {
|
|
133
|
+
socket_fd: self.socket_fd,
|
|
134
|
+
session_token: Some(token),
|
|
135
|
+
_state: PhantomData,
|
|
136
|
+
})
|
|
137
|
+
} else {
|
|
138
|
+
Err(self) // Return connection in Connecting state on auth failure
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
impl SecureGatewayConnection<Authenticated> {
|
|
144
|
+
// This method physically CANNOT be called on Disconnected or Connecting states!
|
|
145
|
+
// Enforced at compile-time with 0 runtime checks.
|
|
146
|
+
pub fn send_secure_payload(&self, payload: &[u8]) -> Result<(), std::io::Error> {
|
|
147
|
+
println!("Sending {} bytes on socket {}", payload.len(), self.socket_fd);
|
|
148
|
+
Ok(())
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## 4. Architectural Rules for Zero-Cost State Machines
|
|
156
|
+
|
|
157
|
+
1. **Replace `Box<dyn Trait>` with `enum_dispatch`**:
|
|
158
|
+
- Whenever the set of polymorphic types is known within the crate/service boundary, use `enum_dispatch` or a manual enum match instead of `Box<dyn Trait>`.
|
|
159
|
+
2. **Use ZSTs (`PhantomData`) for State Tracking**:
|
|
160
|
+
- Never use runtime flags like `is_authenticated: bool` or `state: u8` when states can be modeled statically via typestates. Compile-time states have **zero runtime memory footprint and zero branch misprediction penalty**.
|
|
161
|
+
3. **Static Size Verification**:
|
|
162
|
+
- Verify that enum variants are balanced using `static_assertions::assert_type_size!`. If one variant is significantly larger (>128 bytes), box only that rare variant to keep the main enum discriminant compact on the stack.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
In high-throughput services, an unhandled panic on a Tokio worker thread drops the task, risks corrupting thread-local state, orphans synchronization locks, and degrades long-term process throughput. A robust production service must be mathematically panic-free at compile time.
|
|
4
4
|
|
|
5
|
-
This
|
|
5
|
+
This reference guide documents the **Zero-Panic Policy**, router recursion management, and correct middleware layer ordering used in high-efficiency production services.
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|