Skip to content

Commit 9008fe9

Browse files
committed
feat: enhance Rust snippets
1 parent 21c1695 commit 9008fe9

File tree

1 file changed

+332
-12
lines changed

1 file changed

+332
-12
lines changed

public/data/rust.json

Lines changed: 332 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@
22
{
33
"categoryName": "Basics",
44
"snippets": [
5-
{
6-
"title": "Hello, World!",
7-
"description": "Prints Hello, World! to the terminal.",
8-
"code": [
9-
"fn main() { // Defines the main running function",
10-
" println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.",
11-
"}"
12-
],
13-
"tags": ["rust", "printing", "hello-world", "utility"],
14-
"author": "James-Beans"
15-
}
16-
]
5+
{
6+
"title": "Hello, World!",
7+
"description": "Prints Hello, World! to the terminal.",
8+
"code": [
9+
"fn main() { // Defines the main running function",
10+
" println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.",
11+
"}"
12+
],
13+
"tags": ["rust", "printing", "hello-world", "utility"],
14+
"author": "James-Beans"
15+
}
16+
]
1717
},
1818
{
1919
"categoryName": "String Manipulation",
@@ -35,6 +35,20 @@
3535
],
3636
"tags": ["rust", "string", "capitalize", "utility"],
3737
"author": "Mathys-Gasnier"
38+
},
39+
{
40+
"title": "String to Vec<char>",
41+
"description": "Convert a String into a vector of characters",
42+
"code": [
43+
"fn string_to_chars(s: &str) -> Vec<char> {",
44+
" s.chars().collect()",
45+
"}",
46+
"",
47+
"// Usage:",
48+
"let chars = string_to_chars(\"Hello\"); // ['H', 'e', 'l', 'l', 'o']"
49+
],
50+
"tags": ["rust", "string", "vector", "chars"],
51+
"author": "pyyupsk"
3852
}
3953
]
4054
},
@@ -87,5 +101,311 @@
87101
"author": "Mathys-Gasnier"
88102
}
89103
]
104+
},
105+
{
106+
"categoryName": "Concurrency",
107+
"snippets": [
108+
{
109+
"title": "Thread Pool Implementation",
110+
"description": "A simple thread pool implementation for parallel task execution",
111+
"code": [
112+
"use std::sync::{mpsc, Arc, Mutex};",
113+
"use std::thread;",
114+
"",
115+
"type Job = Box<dyn FnOnce() + Send + 'static>;",
116+
"",
117+
"pub struct ThreadPool {",
118+
" workers: Vec<Worker>,",
119+
" sender: Option<mpsc::Sender<Job>>,",
120+
"}",
121+
"",
122+
"struct Worker {",
123+
" id: usize,",
124+
" thread: Option<thread::JoinHandle<()>>,",
125+
"}",
126+
"",
127+
"impl ThreadPool {",
128+
" pub fn new(size: usize) -> ThreadPool {",
129+
" assert!(size > 0);",
130+
"",
131+
" let (sender, receiver) = mpsc::channel();",
132+
" let receiver = Arc::new(Mutex::new(receiver));",
133+
" let mut workers = Vec::with_capacity(size);",
134+
"",
135+
" for id in 0..size {",
136+
" workers.push(Worker::new(id, Arc::clone(&receiver)));",
137+
" }",
138+
"",
139+
" ThreadPool {",
140+
" workers,",
141+
" sender: Some(sender),",
142+
" }",
143+
" }",
144+
"",
145+
" pub fn execute<F>(&self, f: F)",
146+
" where",
147+
" F: FnOnce() + Send + 'static,",
148+
" {",
149+
" let job = Box::new(f);",
150+
" self.sender.as_ref().unwrap().send(job).unwrap();",
151+
" }",
152+
"}",
153+
"",
154+
"impl Worker {",
155+
" fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {",
156+
" let thread = thread::spawn(move || loop {",
157+
" let message = receiver.lock().unwrap().recv();",
158+
"",
159+
" match message {",
160+
" Ok(job) => {",
161+
" println!(\"Worker {id} got a job; executing.\");",
162+
" job();",
163+
" }",
164+
" Err(_) => {",
165+
" println!(\"Worker {id} disconnected; shutting down.\");",
166+
" break;",
167+
" }",
168+
" }",
169+
" });",
170+
"",
171+
" Worker {",
172+
" id,",
173+
" thread: Some(thread),",
174+
" }",
175+
" }",
176+
"}",
177+
"",
178+
"impl Drop for ThreadPool {",
179+
" fn drop(&mut self) {",
180+
" drop(self.sender.take());",
181+
"",
182+
" for worker in &mut self.workers {",
183+
" if let Some(thread) = worker.thread.take() {",
184+
" thread.join().unwrap();",
185+
" }",
186+
" }",
187+
" }",
188+
"}"
189+
],
190+
"tags": ["rust", "concurrency", "thread-pool", "parallel"],
191+
"author": "pyyupsk"
192+
}
193+
]
194+
},
195+
{
196+
"categoryName": "Advanced Patterns",
197+
"snippets": [
198+
{
199+
"title": "Type-Safe Builder Pattern",
200+
"description": "Implements a compile-time type-safe builder pattern using phantom types",
201+
"code": [
202+
"use std::marker::PhantomData;",
203+
"",
204+
"#[derive(Debug)]",
205+
"pub struct Builder<Name, Age> {",
206+
" name: Option<String>,",
207+
" age: Option<u32>,",
208+
" _name: PhantomData<Name>,",
209+
" _age: PhantomData<Age>,",
210+
"}",
211+
"",
212+
"pub struct Missing;",
213+
"pub struct Set;",
214+
"",
215+
"#[derive(Debug)]",
216+
"pub struct Person {",
217+
" name: String,",
218+
" age: u32,",
219+
"}",
220+
"",
221+
"impl Default for Builder<Missing, Missing> {",
222+
" fn default() -> Self {",
223+
" Self {",
224+
" name: None,",
225+
" age: None,",
226+
" _name: PhantomData,",
227+
" _age: PhantomData,",
228+
" }",
229+
" }",
230+
"}",
231+
"",
232+
"impl<Age> Builder<Missing, Age> {",
233+
" pub fn name(self, name: impl Into<String>) -> Builder<Set, Age> {",
234+
" Builder {",
235+
" name: Some(name.into()),",
236+
" age: self.age,",
237+
" _name: PhantomData,",
238+
" _age: PhantomData,",
239+
" }",
240+
" }",
241+
"}",
242+
"",
243+
"impl<Name> Builder<Name, Missing> {",
244+
" pub fn age(self, age: u32) -> Builder<Name, Set> {",
245+
" Builder {",
246+
" name: self.name,",
247+
" age: Some(age),",
248+
" _name: PhantomData,",
249+
" _age: PhantomData,",
250+
" }",
251+
" }",
252+
"}",
253+
"",
254+
"impl Builder<Set, Set> {",
255+
" pub fn build(self) -> Person {",
256+
" Person {",
257+
" name: self.name.unwrap(),",
258+
" age: self.age.unwrap(),",
259+
" }",
260+
" }",
261+
"}",
262+
"",
263+
"// Usage:",
264+
"let person = Builder::default()",
265+
" .name(\"John\")",
266+
" .age(30)",
267+
" .build();"
268+
],
269+
"tags": ["rust", "design-pattern", "builder", "type-safe"],
270+
"author": "pyyupsk"
271+
}
272+
]
273+
},
274+
{
275+
"categoryName": "Async Programming",
276+
"snippets": [
277+
{
278+
"title": "Async Rate Limiter",
279+
"description": "Implementation of a token bucket rate limiter for async operations",
280+
"code": [
281+
"use std::sync::Arc;",
282+
"use tokio::sync::Semaphore;",
283+
"use tokio::time::{interval, Duration};",
284+
"",
285+
"pub struct RateLimiter {",
286+
" semaphore: Arc<Semaphore>,",
287+
"}",
288+
"",
289+
"impl RateLimiter {",
290+
" pub fn new(rate: u32, interval: Duration) -> Self {",
291+
" let semaphore = Arc::new(Semaphore::new(rate as usize));",
292+
" let sem_clone = semaphore.clone();",
293+
"",
294+
" tokio::spawn(async move {",
295+
" let mut ticker = interval(interval);",
296+
" loop {",
297+
" ticker.tick().await;",
298+
" sem_clone.add_permits(rate as usize);",
299+
" }",
300+
" });",
301+
"",
302+
" RateLimiter { semaphore }",
303+
" }",
304+
"",
305+
" pub async fn acquire(&self) -> RateLimit {",
306+
" let permit = self.semaphore.acquire().await.unwrap();",
307+
" RateLimit { _permit: permit }",
308+
" }",
309+
"}",
310+
"",
311+
"pub struct RateLimit<'a> {",
312+
" _permit: tokio::sync::SemaphorePermit<'a>,",
313+
"}",
314+
"",
315+
"// Usage:",
316+
"async fn example() {",
317+
" let limiter = RateLimiter::new(10, Duration::from_secs(1));",
318+
"",
319+
" for i in 0..20 {",
320+
" let _permit = limiter.acquire().await;",
321+
" println!(\"Executing task {}\", i);",
322+
" }",
323+
"}"
324+
],
325+
"tags": ["rust", "async", "rate-limiter", "tokio"],
326+
"author": "pyyupsk"
327+
}
328+
]
329+
},
330+
{
331+
"categoryName": "Memory Management",
332+
"snippets": [
333+
{
334+
"title": "Custom Smart Pointer",
335+
"description": "Implementation of a custom reference-counted smart pointer with interior mutability",
336+
"code": [
337+
"use std::cell::UnsafeCell;",
338+
"use std::ops::{Deref, DerefMut};",
339+
"use std::sync::atomic::{AtomicUsize, Ordering};",
340+
"use std::sync::Arc;",
341+
"",
342+
"pub struct Interior<T> {",
343+
" ref_count: AtomicUsize,",
344+
" data: UnsafeCell<T>,",
345+
"}",
346+
"",
347+
"pub struct SmartPtr<T> {",
348+
" ptr: Arc<Interior<T>>,",
349+
"}",
350+
"",
351+
"impl<T> SmartPtr<T> {",
352+
" pub fn new(data: T) -> Self {",
353+
" SmartPtr {",
354+
" ptr: Arc::new(Interior {",
355+
" ref_count: AtomicUsize::new(1),",
356+
" data: UnsafeCell::new(data),",
357+
" }),",
358+
" }",
359+
" }",
360+
"",
361+
" pub fn get_ref_count(&self) -> usize {",
362+
" self.ptr.ref_count.load(Ordering::SeqCst)",
363+
" }",
364+
"}",
365+
"",
366+
"impl<T> Clone for SmartPtr<T> {",
367+
" fn clone(&self) -> Self {",
368+
" self.ptr.ref_count.fetch_add(1, Ordering::SeqCst);",
369+
" SmartPtr {",
370+
" ptr: Arc::clone(&self.ptr),",
371+
" }",
372+
" }",
373+
"}",
374+
"",
375+
"impl<T> Drop for SmartPtr<T> {",
376+
" fn drop(&mut self) {",
377+
" if self.ptr.ref_count.fetch_sub(1, Ordering::SeqCst) == 1 {",
378+
" // Last reference is being dropped",
379+
" unsafe {",
380+
" drop(Box::from_raw(self.ptr.data.get()));",
381+
" }",
382+
" }",
383+
" }",
384+
"}",
385+
"",
386+
"impl<T> Deref for SmartPtr<T> {",
387+
" type Target = T;",
388+
"",
389+
" fn deref(&self) -> &Self::Target {",
390+
" unsafe { &*self.ptr.data.get() }",
391+
" }",
392+
"}",
393+
"",
394+
"impl<T> DerefMut for SmartPtr<T> {",
395+
" fn deref_mut(&mut self) -> &mut Self::Target {",
396+
" unsafe { &mut *self.ptr.data.get() }",
397+
" }",
398+
"}",
399+
"",
400+
"// Usage:",
401+
"let ptr = SmartPtr::new(42);",
402+
"let cloned = ptr.clone();",
403+
"assert_eq!(ptr.get_ref_count(), 2);",
404+
"assert_eq!(*ptr, 42);"
405+
],
406+
"tags": ["rust", "smart-pointer", "memory-management", "unsafe"],
407+
"author": "pyyupsk"
408+
}
409+
]
90410
}
91411
]

0 commit comments

Comments
 (0)