Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: enhance Rust snippets #75

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
349 changes: 349 additions & 0 deletions public/consolidated/all_snippets.json
Original file line number Diff line number Diff line change
Expand Up @@ -3891,6 +3891,25 @@
"utility"
],
"author": "Mathys-Gasnier"
},
{
"title": "String to Vec<char>",
"description": "Convert a String into a vector of characters",
"code": [
"fn string_to_chars(s: &str) -> Vec<char> {",
" s.chars().collect()",
"}",
"",
"// Usage:",
"let chars = string_to_chars(\"Hello\"); // ['H', 'e', 'l', 'l', 'o']"
],
"tags": [
"rust",
"string",
"vector",
"chars"
],
"author": "pyyupsk"
}
]
},
Expand Down Expand Up @@ -3954,6 +3973,336 @@
}
]
},
{
"language": "rust",
"categoryName": "Concurrency",
"snippets": [
{
"title": "Thread Pool Implementation",
"description": "A simple thread pool implementation for parallel task execution",
"code": [
"use std::sync::{mpsc, Arc, Mutex};",
"use std::thread;",
"",
"type Job = Box<dyn FnOnce() + Send + 'static>;",
"",
"pub struct ThreadPool {",
" workers: Vec<Worker>,",
" sender: Option<mpsc::Sender<Job>>,",
"}",
"",
"struct Worker {",
" id: usize,",
" thread: Option<thread::JoinHandle<()>>,",
"}",
"",
"impl ThreadPool {",
" pub fn new(size: usize) -> ThreadPool {",
" assert!(size > 0);",
"",
" let (sender, receiver) = mpsc::channel();",
" let receiver = Arc::new(Mutex::new(receiver));",
" let mut workers = Vec::with_capacity(size);",
"",
" for id in 0..size {",
" workers.push(Worker::new(id, Arc::clone(&receiver)));",
" }",
"",
" ThreadPool {",
" workers,",
" sender: Some(sender),",
" }",
" }",
"",
" pub fn execute<F>(&self, f: F)",
" where",
" F: FnOnce() + Send + 'static,",
" {",
" let job = Box::new(f);",
" self.sender.as_ref().unwrap().send(job).unwrap();",
" }",
"}",
"",
"impl Worker {",
" fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {",
" let thread = thread::spawn(move || loop {",
" let message = receiver.lock().unwrap().recv();",
"",
" match message {",
" Ok(job) => {",
" println!(\"Worker {id} got a job; executing.\");",
" job();",
" }",
" Err(_) => {",
" println!(\"Worker {id} disconnected; shutting down.\");",
" break;",
" }",
" }",
" });",
"",
" Worker {",
" id,",
" thread: Some(thread),",
" }",
" }",
"}",
"",
"impl Drop for ThreadPool {",
" fn drop(&mut self) {",
" drop(self.sender.take());",
"",
" for worker in &mut self.workers {",
" if let Some(thread) = worker.thread.take() {",
" thread.join().unwrap();",
" }",
" }",
" }",
"}"
],
"tags": [
"rust",
"concurrency",
"thread-pool",
"parallel"
],
"author": "pyyupsk"
}
]
},
{
"language": "rust",
"categoryName": "Advanced Patterns",
"snippets": [
{
"title": "Type-Safe Builder Pattern",
"description": "Implements a compile-time type-safe builder pattern using phantom types",
"code": [
"use std::marker::PhantomData;",
"",
"#[derive(Debug)]",
"pub struct Builder<Name, Age> {",
" name: Option<String>,",
" age: Option<u32>,",
" _name: PhantomData<Name>,",
" _age: PhantomData<Age>,",
"}",
"",
"pub struct Missing;",
"pub struct Set;",
"",
"#[derive(Debug)]",
"pub struct Person {",
" name: String,",
" age: u32,",
"}",
"",
"impl Default for Builder<Missing, Missing> {",
" fn default() -> Self {",
" Self {",
" name: None,",
" age: None,",
" _name: PhantomData,",
" _age: PhantomData,",
" }",
" }",
"}",
"",
"impl<Age> Builder<Missing, Age> {",
" pub fn name(self, name: impl Into<String>) -> Builder<Set, Age> {",
" Builder {",
" name: Some(name.into()),",
" age: self.age,",
" _name: PhantomData,",
" _age: PhantomData,",
" }",
" }",
"}",
"",
"impl<Name> Builder<Name, Missing> {",
" pub fn age(self, age: u32) -> Builder<Name, Set> {",
" Builder {",
" name: self.name,",
" age: Some(age),",
" _name: PhantomData,",
" _age: PhantomData,",
" }",
" }",
"}",
"",
"impl Builder<Set, Set> {",
" pub fn build(self) -> Person {",
" Person {",
" name: self.name.unwrap(),",
" age: self.age.unwrap(),",
" }",
" }",
"}",
"",
"// Usage:",
"let person = Builder::default()",
" .name(\"John\")",
" .age(30)",
" .build();"
],
"tags": [
"rust",
"design-pattern",
"builder",
"type-safe"
],
"author": "pyyupsk"
}
]
},
{
"language": "rust",
"categoryName": "Async Programming",
"snippets": [
{
"title": "Async Rate Limiter",
"description": "Implementation of a token bucket rate limiter for async operations",
"code": [
"use std::sync::Arc;",
"use tokio::sync::Semaphore;",
"use tokio::time::{interval, Duration};",
"",
"pub struct RateLimiter {",
" semaphore: Arc<Semaphore>,",
"}",
"",
"impl RateLimiter {",
" pub fn new(rate: u32, interval: Duration) -> Self {",
" let semaphore = Arc::new(Semaphore::new(rate as usize));",
" let sem_clone = semaphore.clone();",
"",
" tokio::spawn(async move {",
" let mut ticker = interval(interval);",
" loop {",
" ticker.tick().await;",
" sem_clone.add_permits(rate as usize);",
" }",
" });",
"",
" RateLimiter { semaphore }",
" }",
"",
" pub async fn acquire(&self) -> RateLimit {",
" let permit = self.semaphore.acquire().await.unwrap();",
" RateLimit { _permit: permit }",
" }",
"}",
"",
"pub struct RateLimit<'a> {",
" _permit: tokio::sync::SemaphorePermit<'a>,",
"}",
"",
"// Usage:",
"async fn example() {",
" let limiter = RateLimiter::new(10, Duration::from_secs(1));",
"",
" for i in 0..20 {",
" let _permit = limiter.acquire().await;",
" println!(\"Executing task {}\", i);",
" }",
"}"
],
"tags": [
"rust",
"async",
"rate-limiter",
"tokio"
],
"author": "pyyupsk"
}
]
},
{
"language": "rust",
"categoryName": "Memory Management",
"snippets": [
{
"title": "Custom Smart Pointer",
"description": "Implementation of a custom reference-counted smart pointer with interior mutability",
"code": [
"use std::cell::UnsafeCell;",
"use std::ops::{Deref, DerefMut};",
"use std::sync::atomic::{AtomicUsize, Ordering};",
"use std::sync::Arc;",
"",
"pub struct Interior<T> {",
" ref_count: AtomicUsize,",
" data: UnsafeCell<T>,",
"}",
"",
"pub struct SmartPtr<T> {",
" ptr: Arc<Interior<T>>,",
"}",
"",
"impl<T> SmartPtr<T> {",
" pub fn new(data: T) -> Self {",
" SmartPtr {",
" ptr: Arc::new(Interior {",
" ref_count: AtomicUsize::new(1),",
" data: UnsafeCell::new(data),",
" }),",
" }",
" }",
"",
" pub fn get_ref_count(&self) -> usize {",
" self.ptr.ref_count.load(Ordering::SeqCst)",
" }",
"}",
"",
"impl<T> Clone for SmartPtr<T> {",
" fn clone(&self) -> Self {",
" self.ptr.ref_count.fetch_add(1, Ordering::SeqCst);",
" SmartPtr {",
" ptr: Arc::clone(&self.ptr),",
" }",
" }",
"}",
"",
"impl<T> Drop for SmartPtr<T> {",
" fn drop(&mut self) {",
" if self.ptr.ref_count.fetch_sub(1, Ordering::SeqCst) == 1 {",
" // Last reference is being dropped",
" unsafe {",
" drop(Box::from_raw(self.ptr.data.get()));",
" }",
" }",
" }",
"}",
"",
"impl<T> Deref for SmartPtr<T> {",
" type Target = T;",
"",
" fn deref(&self) -> &Self::Target {",
" unsafe { &*self.ptr.data.get() }",
" }",
"}",
"",
"impl<T> DerefMut for SmartPtr<T> {",
" fn deref_mut(&mut self) -> &mut Self::Target {",
" unsafe { &mut *self.ptr.data.get() }",
" }",
"}",
"",
"// Usage:",
"let ptr = SmartPtr::new(42);",
"let cloned = ptr.clone();",
"assert_eq!(ptr.get_ref_count(), 2);",
"assert_eq!(*ptr, 42);"
],
"tags": [
"rust",
"smart-pointer",
"memory-management",
"unsafe"
],
"author": "pyyupsk"
}
]
},
{
"language": "scss",
"categoryName": "Typography",
Expand Down
Loading