@h1dr0n/skill-pool 0.1.0

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 (189) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +296 -0
  3. package/bin/cli.js +157 -0
  4. package/package.json +41 -0
  5. package/skills/api/agents/backend-specialist.md +69 -0
  6. package/skills/api/agents/database-optimizer.md +176 -0
  7. package/skills/api/manifest.yaml +20 -0
  8. package/skills/api/rules/auth-security.md +45 -0
  9. package/skills/api/skills/api-patterns/SKILL.md +81 -0
  10. package/skills/api/skills/api-patterns/api-style.md +42 -0
  11. package/skills/api/skills/api-patterns/auth.md +24 -0
  12. package/skills/api/skills/api-patterns/documentation.md +26 -0
  13. package/skills/api/skills/api-patterns/graphql.md +41 -0
  14. package/skills/api/skills/api-patterns/rate-limiting.md +31 -0
  15. package/skills/api/skills/api-patterns/response.md +37 -0
  16. package/skills/api/skills/api-patterns/rest.md +40 -0
  17. package/skills/api/skills/api-patterns/scripts/api_validator.py +211 -0
  18. package/skills/api/skills/api-patterns/security-testing.md +122 -0
  19. package/skills/api/skills/api-patterns/trpc.md +41 -0
  20. package/skills/api/skills/api-patterns/versioning.md +22 -0
  21. package/skills/api/skills/database-patterns.md +126 -0
  22. package/skills/api/skills/deployment-patterns.md +105 -0
  23. package/skills/api/skills/docker-patterns.md +135 -0
  24. package/skills/common/agents/code-reviewer.md +78 -0
  25. package/skills/common/agents/planner.md +80 -0
  26. package/skills/common/agents/security-reviewer.md +82 -0
  27. package/skills/common/agents/software-architect.md +81 -0
  28. package/skills/common/manifest.yaml +25 -0
  29. package/skills/common/rules/coding-style.md +39 -0
  30. package/skills/common/rules/git-workflow.md +33 -0
  31. package/skills/common/rules/security.md +25 -0
  32. package/skills/common/skills/architecture/SKILL.md +55 -0
  33. package/skills/common/skills/architecture/context-discovery.md +43 -0
  34. package/skills/common/skills/architecture/examples.md +94 -0
  35. package/skills/common/skills/architecture/pattern-selection.md +68 -0
  36. package/skills/common/skills/architecture/patterns-reference.md +50 -0
  37. package/skills/common/skills/architecture/trade-off-analysis.md +77 -0
  38. package/skills/common/skills/brainstorming/SKILL.md +163 -0
  39. package/skills/common/skills/brainstorming/dynamic-questioning.md +350 -0
  40. package/skills/common/skills/clean-code.md +99 -0
  41. package/skills/common/skills/code-review-checklist.md +86 -0
  42. package/skills/common/skills/plan-writing/SKILL.md +152 -0
  43. package/skills/common/skills/skill-feedback.md +94 -0
  44. package/skills/common/skills/tdd-workflow.md +130 -0
  45. package/skills/common/skills/verification-loop.md +112 -0
  46. package/skills/cpp/agents/cpp-build-resolver.md +90 -0
  47. package/skills/cpp/agents/cpp-reviewer.md +72 -0
  48. package/skills/cpp/manifest.yaml +15 -0
  49. package/skills/cpp/skills/cpp-coding-standards.md +722 -0
  50. package/skills/cpp/skills/cpp-testing.md +323 -0
  51. package/skills/devops/agents/devops-automator.md +376 -0
  52. package/skills/devops/agents/sre.md +90 -0
  53. package/skills/devops/manifest.yaml +20 -0
  54. package/skills/devops/skills/deployment-patterns.md +427 -0
  55. package/skills/devops/skills/deployment-procedures/SKILL.md +241 -0
  56. package/skills/devops/skills/docker-patterns.md +364 -0
  57. package/skills/devops/skills/e2e-testing.md +326 -0
  58. package/skills/devops/skills/github-ops.md +144 -0
  59. package/skills/django/manifest.yaml +16 -0
  60. package/skills/django/skills/django-patterns.md +734 -0
  61. package/skills/django/skills/django-security.md +593 -0
  62. package/skills/django/skills/django-tdd.md +729 -0
  63. package/skills/django/skills/django-verification.md +469 -0
  64. package/skills/dotnet/agents/csharp-reviewer.md +101 -0
  65. package/skills/dotnet/manifest.yaml +14 -0
  66. package/skills/dotnet/skills/csharp-testing.md +321 -0
  67. package/skills/dotnet/skills/dotnet-patterns.md +321 -0
  68. package/skills/go/agents/code-reviewer.md +76 -0
  69. package/skills/go/agents/go-build-resolver.md +94 -0
  70. package/skills/go/agents/go-reviewer.md +76 -0
  71. package/skills/go/manifest.yaml +17 -0
  72. package/skills/go/rules/go-style.md +55 -0
  73. package/skills/go/skills/golang-patterns.md +674 -0
  74. package/skills/go/skills/golang-testing.md +720 -0
  75. package/skills/java/agents/java-build-resolver.md +153 -0
  76. package/skills/java/agents/java-reviewer.md +92 -0
  77. package/skills/java/manifest.yaml +18 -0
  78. package/skills/java/skills/java-coding-standards.md +147 -0
  79. package/skills/java/skills/jpa-patterns.md +151 -0
  80. package/skills/java/skills/springboot-patterns.md +314 -0
  81. package/skills/java/skills/springboot-security.md +272 -0
  82. package/skills/kotlin/agents/kotlin-build-resolver.md +118 -0
  83. package/skills/kotlin/agents/kotlin-reviewer.md +159 -0
  84. package/skills/kotlin/manifest.yaml +17 -0
  85. package/skills/kotlin/skills/kotlin-coroutines-flows.md +284 -0
  86. package/skills/kotlin/skills/kotlin-patterns.md +711 -0
  87. package/skills/kotlin/skills/kotlin-testing.md +824 -0
  88. package/skills/laravel/manifest.yaml +15 -0
  89. package/skills/laravel/skills/laravel-patterns.md +409 -0
  90. package/skills/laravel/skills/laravel-security.md +279 -0
  91. package/skills/laravel/skills/laravel-tdd.md +277 -0
  92. package/skills/laravel/skills/laravel-verification.md +173 -0
  93. package/skills/mobile/agents/dart-build-resolver.md +201 -0
  94. package/skills/mobile/agents/flutter-reviewer.md +243 -0
  95. package/skills/mobile/manifest.yaml +19 -0
  96. package/skills/mobile/skills/android-clean-architecture.md +339 -0
  97. package/skills/mobile/skills/dart-flutter-patterns.md +563 -0
  98. package/skills/mobile/skills/swiftui-patterns.md +259 -0
  99. package/skills/nestjs/manifest.yaml +13 -0
  100. package/skills/nestjs/skills/nestjs-patterns.md +230 -0
  101. package/skills/perl/manifest.yaml +13 -0
  102. package/skills/perl/skills/perl-patterns.md +504 -0
  103. package/skills/perl/skills/perl-security.md +503 -0
  104. package/skills/perl/skills/perl-testing.md +475 -0
  105. package/skills/python/agents/python-reviewer.md +98 -0
  106. package/skills/python/manifest.yaml +18 -0
  107. package/skills/python/rules/python-style.md +69 -0
  108. package/skills/python/skills/python-patterns/SKILL.md +441 -0
  109. package/skills/python/skills/python-patterns.md +90 -0
  110. package/skills/python/skills/python-testing.md +81 -0
  111. package/skills/rust/agents/rust-build-resolver.md +148 -0
  112. package/skills/rust/agents/rust-reviewer.md +94 -0
  113. package/skills/rust/manifest.yaml +16 -0
  114. package/skills/rust/rules/rust-style.md +107 -0
  115. package/skills/rust/skills/rust-patterns.md +499 -0
  116. package/skills/rust/skills/rust-testing.md +500 -0
  117. package/skills/security/agents/accessibility-auditor.md +316 -0
  118. package/skills/security/agents/security-reviewer.md +108 -0
  119. package/skills/security/manifest.yaml +19 -0
  120. package/skills/security/skills/red-team-tactics/SKILL.md +199 -0
  121. package/skills/security/skills/security-bounty-hunter.md +99 -0
  122. package/skills/security/skills/security-review.md +495 -0
  123. package/skills/security/skills/security-scan.md +165 -0
  124. package/skills/security/skills/vulnerability-scanner/SKILL.md +276 -0
  125. package/skills/security/skills/vulnerability-scanner/checklists.md +121 -0
  126. package/skills/security/skills/vulnerability-scanner/scripts/security_scan.py +458 -0
  127. package/skills/swift/manifest.yaml +16 -0
  128. package/skills/swift/skills/swift-actor-persistence.md +142 -0
  129. package/skills/swift/skills/swift-concurrency.md +216 -0
  130. package/skills/swift/skills/swift-protocol-di-testing.md +190 -0
  131. package/skills/swift/skills/swiftui-patterns.md +259 -0
  132. package/skills/unity/agents/game-designer.md +167 -0
  133. package/skills/unity/agents/unity-architect.md +52 -0
  134. package/skills/unity/agents/unity-editor-tool-developer.md +310 -0
  135. package/skills/unity/agents/unity-multiplayer-engineer.md +321 -0
  136. package/skills/unity/agents/unity-shader-graph-artist.md +269 -0
  137. package/skills/unity/manifest.yaml +21 -0
  138. package/skills/unity/rules/csharp-patterns.md +48 -0
  139. package/skills/unity/rules/unity-specific.md +53 -0
  140. package/skills/unity/skills/systematic-debugging.md +92 -0
  141. package/skills/unity/skills/unity-architecture.md +173 -0
  142. package/skills/unreal/agents/level-designer.md +208 -0
  143. package/skills/unreal/agents/technical-artist.md +229 -0
  144. package/skills/unreal/agents/unreal-multiplayer-architect.md +313 -0
  145. package/skills/unreal/agents/unreal-systems-engineer.md +310 -0
  146. package/skills/unreal/agents/unreal-technical-artist.md +256 -0
  147. package/skills/unreal/agents/unreal-world-builder.md +273 -0
  148. package/skills/unreal/manifest.yaml +21 -0
  149. package/skills/unreal/skills/unreal-patterns.md +183 -0
  150. package/skills/web/agents/frontend-specialist.md +71 -0
  151. package/skills/web/agents/ui-designer.md +383 -0
  152. package/skills/web/agents/ux-architect.md +469 -0
  153. package/skills/web/manifest.yaml +22 -0
  154. package/skills/web/rules/accessibility.md +54 -0
  155. package/skills/web/rules/css-performance.md +52 -0
  156. package/skills/web/skills/e2e-testing.md +132 -0
  157. package/skills/web/skills/frontend-design/SKILL.md +452 -0
  158. package/skills/web/skills/frontend-design/animation-guide.md +331 -0
  159. package/skills/web/skills/frontend-design/color-system.md +311 -0
  160. package/skills/web/skills/frontend-design/decision-trees.md +418 -0
  161. package/skills/web/skills/frontend-design/motion-graphics.md +306 -0
  162. package/skills/web/skills/frontend-design/scripts/accessibility_checker.py +183 -0
  163. package/skills/web/skills/frontend-design/scripts/ux_audit.py +722 -0
  164. package/skills/web/skills/frontend-design/typography-system.md +345 -0
  165. package/skills/web/skills/frontend-design/ux-psychology.md +1116 -0
  166. package/skills/web/skills/frontend-design/visual-effects.md +383 -0
  167. package/skills/web/skills/react-nextjs.md +135 -0
  168. package/skills/web/skills/tailwind-patterns/SKILL.md +269 -0
  169. package/src/adapters/antigravity.js +164 -0
  170. package/src/adapters/claude.js +188 -0
  171. package/src/adapters/cursor.js +161 -0
  172. package/src/adapters/index.js +67 -0
  173. package/src/adapters/windsurf.js +158 -0
  174. package/src/commands/add.js +266 -0
  175. package/src/commands/create.js +127 -0
  176. package/src/commands/diff.js +78 -0
  177. package/src/commands/info.js +88 -0
  178. package/src/commands/init.js +224 -0
  179. package/src/commands/install.js +90 -0
  180. package/src/commands/list.js +54 -0
  181. package/src/commands/remove.js +101 -0
  182. package/src/commands/targets.js +32 -0
  183. package/src/commands/update.js +57 -0
  184. package/src/core/manifest.js +57 -0
  185. package/src/core/plugins.js +86 -0
  186. package/src/core/resolver.js +84 -0
  187. package/src/core/tracker.js +49 -0
  188. package/src/utils/fs.js +80 -0
  189. package/src/utils/git.js +52 -0
@@ -0,0 +1,499 @@
1
+ ---
2
+ name: rust-patterns
3
+ description: Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications.
4
+ origin: ECC
5
+ ---
6
+
7
+ # Rust Development Patterns
8
+
9
+ Idiomatic Rust patterns and best practices for building safe, performant, and maintainable applications.
10
+
11
+ ## When to Use
12
+
13
+ - Writing new Rust code
14
+ - Reviewing Rust code
15
+ - Refactoring existing Rust code
16
+ - Designing crate structure and module layout
17
+
18
+ ## How It Works
19
+
20
+ This skill enforces idiomatic Rust conventions across six key areas: ownership and borrowing to prevent data races at compile time, `Result`/`?` error propagation with `thiserror` for libraries and `anyhow` for applications, enums and exhaustive pattern matching to make illegal states unrepresentable, traits and generics for zero-cost abstraction, safe concurrency via `Arc<Mutex<T>>`, channels, and async/await, and minimal `pub` surfaces organized by domain.
21
+
22
+ ## Core Principles
23
+
24
+ ### 1. Ownership and Borrowing
25
+
26
+ Rust's ownership system prevents data races and memory bugs at compile time.
27
+
28
+ ```rust
29
+ // Good: Pass references when you don't need ownership
30
+ fn process(data: &[u8]) -> usize {
31
+ data.len()
32
+ }
33
+
34
+ // Good: Take ownership only when you need to store or consume
35
+ fn store(data: Vec<u8>) -> Record {
36
+ Record { payload: data }
37
+ }
38
+
39
+ // Bad: Cloning unnecessarily to avoid borrow checker
40
+ fn process_bad(data: &Vec<u8>) -> usize {
41
+ let cloned = data.clone(); // Wasteful — just borrow
42
+ cloned.len()
43
+ }
44
+ ```
45
+
46
+ ### Use `Cow` for Flexible Ownership
47
+
48
+ ```rust
49
+ use std::borrow::Cow;
50
+
51
+ fn normalize(input: &str) -> Cow<'_, str> {
52
+ if input.contains(' ') {
53
+ Cow::Owned(input.replace(' ', "_"))
54
+ } else {
55
+ Cow::Borrowed(input) // Zero-cost when no mutation needed
56
+ }
57
+ }
58
+ ```
59
+
60
+ ## Error Handling
61
+
62
+ ### Use `Result` and `?` — Never `unwrap()` in Production
63
+
64
+ ```rust
65
+ // Good: Propagate errors with context
66
+ use anyhow::{Context, Result};
67
+
68
+ fn load_config(path: &str) -> Result<Config> {
69
+ let content = std::fs::read_to_string(path)
70
+ .with_context(|| format!("failed to read config from {path}"))?;
71
+ let config: Config = toml::from_str(&content)
72
+ .with_context(|| format!("failed to parse config from {path}"))?;
73
+ Ok(config)
74
+ }
75
+
76
+ // Bad: Panics on error
77
+ fn load_config_bad(path: &str) -> Config {
78
+ let content = std::fs::read_to_string(path).unwrap(); // Panics!
79
+ toml::from_str(&content).unwrap()
80
+ }
81
+ ```
82
+
83
+ ### Library Errors with `thiserror`, Application Errors with `anyhow`
84
+
85
+ ```rust
86
+ // Library code: structured, typed errors
87
+ use thiserror::Error;
88
+
89
+ #[derive(Debug, Error)]
90
+ pub enum StorageError {
91
+ #[error("record not found: {id}")]
92
+ NotFound { id: String },
93
+ #[error("connection failed")]
94
+ Connection(#[from] std::io::Error),
95
+ #[error("invalid data: {0}")]
96
+ InvalidData(String),
97
+ }
98
+
99
+ // Application code: flexible error handling
100
+ use anyhow::{bail, Result};
101
+
102
+ fn run() -> Result<()> {
103
+ let config = load_config("app.toml")?;
104
+ if config.workers == 0 {
105
+ bail!("worker count must be > 0");
106
+ }
107
+ Ok(())
108
+ }
109
+ ```
110
+
111
+ ### `Option` Combinators Over Nested Matching
112
+
113
+ ```rust
114
+ // Good: Combinator chain
115
+ fn find_user_email(users: &[User], id: u64) -> Option<String> {
116
+ users.iter()
117
+ .find(|u| u.id == id)
118
+ .map(|u| u.email.clone())
119
+ }
120
+
121
+ // Bad: Deeply nested matching
122
+ fn find_user_email_bad(users: &[User], id: u64) -> Option<String> {
123
+ match users.iter().find(|u| u.id == id) {
124
+ Some(user) => match &user.email {
125
+ email => Some(email.clone()),
126
+ },
127
+ None => None,
128
+ }
129
+ }
130
+ ```
131
+
132
+ ## Enums and Pattern Matching
133
+
134
+ ### Model States as Enums
135
+
136
+ ```rust
137
+ // Good: Impossible states are unrepresentable
138
+ enum ConnectionState {
139
+ Disconnected,
140
+ Connecting { attempt: u32 },
141
+ Connected { session_id: String },
142
+ Failed { reason: String, retries: u32 },
143
+ }
144
+
145
+ fn handle(state: &ConnectionState) {
146
+ match state {
147
+ ConnectionState::Disconnected => connect(),
148
+ ConnectionState::Connecting { attempt } if *attempt > 3 => abort(),
149
+ ConnectionState::Connecting { .. } => wait(),
150
+ ConnectionState::Connected { session_id } => use_session(session_id),
151
+ ConnectionState::Failed { retries, .. } if *retries < 5 => retry(),
152
+ ConnectionState::Failed { reason, .. } => log_failure(reason),
153
+ }
154
+ }
155
+ ```
156
+
157
+ ### Exhaustive Matching — No Catch-All for Business Logic
158
+
159
+ ```rust
160
+ // Good: Handle every variant explicitly
161
+ match command {
162
+ Command::Start => start_service(),
163
+ Command::Stop => stop_service(),
164
+ Command::Restart => restart_service(),
165
+ // Adding a new variant forces handling here
166
+ }
167
+
168
+ // Bad: Wildcard hides new variants
169
+ match command {
170
+ Command::Start => start_service(),
171
+ _ => {} // Silently ignores Stop, Restart, and future variants
172
+ }
173
+ ```
174
+
175
+ ## Traits and Generics
176
+
177
+ ### Accept Generics, Return Concrete Types
178
+
179
+ ```rust
180
+ // Good: Generic input, concrete output
181
+ fn read_all(reader: &mut impl Read) -> std::io::Result<Vec<u8>> {
182
+ let mut buf = Vec::new();
183
+ reader.read_to_end(&mut buf)?;
184
+ Ok(buf)
185
+ }
186
+
187
+ // Good: Trait bounds for multiple constraints
188
+ fn process<T: Display + Send + 'static>(item: T) -> String {
189
+ format!("processed: {item}")
190
+ }
191
+ ```
192
+
193
+ ### Trait Objects for Dynamic Dispatch
194
+
195
+ ```rust
196
+ // Use when you need heterogeneous collections or plugin systems
197
+ trait Handler: Send + Sync {
198
+ fn handle(&self, request: &Request) -> Response;
199
+ }
200
+
201
+ struct Router {
202
+ handlers: Vec<Box<dyn Handler>>,
203
+ }
204
+
205
+ // Use generics when you need performance (monomorphization)
206
+ fn fast_process<H: Handler>(handler: &H, request: &Request) -> Response {
207
+ handler.handle(request)
208
+ }
209
+ ```
210
+
211
+ ### Newtype Pattern for Type Safety
212
+
213
+ ```rust
214
+ // Good: Distinct types prevent mixing up arguments
215
+ struct UserId(u64);
216
+ struct OrderId(u64);
217
+
218
+ fn get_order(user: UserId, order: OrderId) -> Result<Order> {
219
+ // Can't accidentally swap user and order IDs
220
+ todo!()
221
+ }
222
+
223
+ // Bad: Easy to swap arguments
224
+ fn get_order_bad(user_id: u64, order_id: u64) -> Result<Order> {
225
+ todo!()
226
+ }
227
+ ```
228
+
229
+ ## Structs and Data Modeling
230
+
231
+ ### Builder Pattern for Complex Construction
232
+
233
+ ```rust
234
+ struct ServerConfig {
235
+ host: String,
236
+ port: u16,
237
+ max_connections: usize,
238
+ }
239
+
240
+ impl ServerConfig {
241
+ fn builder(host: impl Into<String>, port: u16) -> ServerConfigBuilder {
242
+ ServerConfigBuilder { host: host.into(), port, max_connections: 100 }
243
+ }
244
+ }
245
+
246
+ struct ServerConfigBuilder { host: String, port: u16, max_connections: usize }
247
+
248
+ impl ServerConfigBuilder {
249
+ fn max_connections(mut self, n: usize) -> Self { self.max_connections = n; self }
250
+ fn build(self) -> ServerConfig {
251
+ ServerConfig { host: self.host, port: self.port, max_connections: self.max_connections }
252
+ }
253
+ }
254
+
255
+ // Usage: ServerConfig::builder("localhost", 8080).max_connections(200).build()
256
+ ```
257
+
258
+ ## Iterators and Closures
259
+
260
+ ### Prefer Iterator Chains Over Manual Loops
261
+
262
+ ```rust
263
+ // Good: Declarative, lazy, composable
264
+ let active_emails: Vec<String> = users.iter()
265
+ .filter(|u| u.is_active)
266
+ .map(|u| u.email.clone())
267
+ .collect();
268
+
269
+ // Bad: Imperative accumulation
270
+ let mut active_emails = Vec::new();
271
+ for user in &users {
272
+ if user.is_active {
273
+ active_emails.push(user.email.clone());
274
+ }
275
+ }
276
+ ```
277
+
278
+ ### Use `collect()` with Type Annotation
279
+
280
+ ```rust
281
+ // Collect into different types
282
+ let names: Vec<_> = items.iter().map(|i| &i.name).collect();
283
+ let lookup: HashMap<_, _> = items.iter().map(|i| (i.id, i)).collect();
284
+ let combined: String = parts.iter().copied().collect();
285
+
286
+ // Collect Results — short-circuits on first error
287
+ let parsed: Result<Vec<i32>, _> = strings.iter().map(|s| s.parse()).collect();
288
+ ```
289
+
290
+ ## Concurrency
291
+
292
+ ### `Arc<Mutex<T>>` for Shared Mutable State
293
+
294
+ ```rust
295
+ use std::sync::{Arc, Mutex};
296
+
297
+ let counter = Arc::new(Mutex::new(0));
298
+ let handles: Vec<_> = (0..10).map(|_| {
299
+ let counter = Arc::clone(&counter);
300
+ std::thread::spawn(move || {
301
+ let mut num = counter.lock().expect("mutex poisoned");
302
+ *num += 1;
303
+ })
304
+ }).collect();
305
+
306
+ for handle in handles {
307
+ handle.join().expect("worker thread panicked");
308
+ }
309
+ ```
310
+
311
+ ### Channels for Message Passing
312
+
313
+ ```rust
314
+ use std::sync::mpsc;
315
+
316
+ let (tx, rx) = mpsc::sync_channel(16); // Bounded channel with backpressure
317
+
318
+ for i in 0..5 {
319
+ let tx = tx.clone();
320
+ std::thread::spawn(move || {
321
+ tx.send(format!("message {i}")).expect("receiver disconnected");
322
+ });
323
+ }
324
+ drop(tx); // Close sender so rx iterator terminates
325
+
326
+ for msg in rx {
327
+ println!("{msg}");
328
+ }
329
+ ```
330
+
331
+ ### Async with Tokio
332
+
333
+ ```rust
334
+ use tokio::time::Duration;
335
+
336
+ async fn fetch_with_timeout(url: &str) -> Result<String> {
337
+ let response = tokio::time::timeout(
338
+ Duration::from_secs(5),
339
+ reqwest::get(url),
340
+ )
341
+ .await
342
+ .context("request timed out")?
343
+ .context("request failed")?;
344
+
345
+ response.text().await.context("failed to read body")
346
+ }
347
+
348
+ // Spawn concurrent tasks
349
+ async fn fetch_all(urls: Vec<String>) -> Vec<Result<String>> {
350
+ let handles: Vec<_> = urls.into_iter()
351
+ .map(|url| tokio::spawn(async move {
352
+ fetch_with_timeout(&url).await
353
+ }))
354
+ .collect();
355
+
356
+ let mut results = Vec::with_capacity(handles.len());
357
+ for handle in handles {
358
+ results.push(handle.await.unwrap_or_else(|e| panic!("spawned task panicked: {e}")));
359
+ }
360
+ results
361
+ }
362
+ ```
363
+
364
+ ## Unsafe Code
365
+
366
+ ### When Unsafe Is Acceptable
367
+
368
+ ```rust
369
+ // Acceptable: FFI boundary with documented invariants (Rust 2024+)
370
+ /// # Safety
371
+ /// `ptr` must be a valid, aligned pointer to an initialized `Widget`.
372
+ unsafe fn widget_from_raw<'a>(ptr: *const Widget) -> &'a Widget {
373
+ // SAFETY: caller guarantees ptr is valid and aligned
374
+ unsafe { &*ptr }
375
+ }
376
+
377
+ // Acceptable: Performance-critical path with proof of correctness
378
+ // SAFETY: index is always < len due to the loop bound
379
+ unsafe { slice.get_unchecked(index) }
380
+ ```
381
+
382
+ ### When Unsafe Is NOT Acceptable
383
+
384
+ ```rust
385
+ // Bad: Using unsafe to bypass borrow checker
386
+ // Bad: Using unsafe for convenience
387
+ // Bad: Using unsafe without a Safety comment
388
+ // Bad: Transmuting between unrelated types
389
+ ```
390
+
391
+ ## Module System and Crate Structure
392
+
393
+ ### Organize by Domain, Not by Type
394
+
395
+ ```text
396
+ my_app/
397
+ ├── src/
398
+ │ ├── main.rs
399
+ │ ├── lib.rs
400
+ │ ├── auth/ # Domain module
401
+ │ │ ├── mod.rs
402
+ │ │ ├── token.rs
403
+ │ │ └── middleware.rs
404
+ │ ├── orders/ # Domain module
405
+ │ │ ├── mod.rs
406
+ │ │ ├── model.rs
407
+ │ │ └── service.rs
408
+ │ └── db/ # Infrastructure
409
+ │ ├── mod.rs
410
+ │ └── pool.rs
411
+ ├── tests/ # Integration tests
412
+ ├── benches/ # Benchmarks
413
+ └── Cargo.toml
414
+ ```
415
+
416
+ ### Visibility — Expose Minimally
417
+
418
+ ```rust
419
+ // Good: pub(crate) for internal sharing
420
+ pub(crate) fn validate_input(input: &str) -> bool {
421
+ !input.is_empty()
422
+ }
423
+
424
+ // Good: Re-export public API from lib.rs
425
+ pub mod auth;
426
+ pub use auth::AuthMiddleware;
427
+
428
+ // Bad: Making everything pub
429
+ pub fn internal_helper() {} // Should be pub(crate) or private
430
+ ```
431
+
432
+ ## Tooling Integration
433
+
434
+ ### Essential Commands
435
+
436
+ ```bash
437
+ # Build and check
438
+ cargo build
439
+ cargo check # Fast type checking without codegen
440
+ cargo clippy # Lints and suggestions
441
+ cargo fmt # Format code
442
+
443
+ # Testing
444
+ cargo test
445
+ cargo test -- --nocapture # Show println output
446
+ cargo test --lib # Unit tests only
447
+ cargo test --test integration # Integration tests only
448
+
449
+ # Dependencies
450
+ cargo audit # Security audit
451
+ cargo tree # Dependency tree
452
+ cargo update # Update dependencies
453
+
454
+ # Performance
455
+ cargo bench # Run benchmarks
456
+ ```
457
+
458
+ ## Quick Reference: Rust Idioms
459
+
460
+ | Idiom | Description |
461
+ |-------|-------------|
462
+ | Borrow, don't clone | Pass `&T` instead of cloning unless ownership is needed |
463
+ | Make illegal states unrepresentable | Use enums to model valid states only |
464
+ | `?` over `unwrap()` | Propagate errors, never panic in library/production code |
465
+ | Parse, don't validate | Convert unstructured data to typed structs at the boundary |
466
+ | Newtype for type safety | Wrap primitives in newtypes to prevent argument swaps |
467
+ | Prefer iterators over loops | Declarative chains are clearer and often faster |
468
+ | `#[must_use]` on Results | Ensure callers handle return values |
469
+ | `Cow` for flexible ownership | Avoid allocations when borrowing suffices |
470
+ | Exhaustive matching | No wildcard `_` for business-critical enums |
471
+ | Minimal `pub` surface | Use `pub(crate)` for internal APIs |
472
+
473
+ ## Anti-Patterns to Avoid
474
+
475
+ ```rust
476
+ // Bad: .unwrap() in production code
477
+ let value = map.get("key").unwrap();
478
+
479
+ // Bad: .clone() to satisfy borrow checker without understanding why
480
+ let data = expensive_data.clone();
481
+ process(&original, &data);
482
+
483
+ // Bad: Using String when &str suffices
484
+ fn greet(name: String) { /* should be &str */ }
485
+
486
+ // Bad: Box<dyn Error> in libraries (use thiserror instead)
487
+ fn parse(input: &str) -> Result<Data, Box<dyn std::error::Error>> { todo!() }
488
+
489
+ // Bad: Ignoring must_use warnings
490
+ let _ = validate(input); // Silently discarding a Result
491
+
492
+ // Bad: Blocking in async context
493
+ async fn bad_async() {
494
+ std::thread::sleep(Duration::from_secs(1)); // Blocks the executor!
495
+ // Use: tokio::time::sleep(Duration::from_secs(1)).await;
496
+ }
497
+ ```
498
+
499
+ **Remember**: If it compiles, it's probably correct — but only if you avoid `unwrap()`, minimize `unsafe`, and let the type system work for you.