Skip to content

Commit aa32a97

Browse files
committed
Update consolidated snippets
1 parent 9008fe9 commit aa32a97

File tree

1 file changed

+349
-0
lines changed

1 file changed

+349
-0
lines changed

public/consolidated/all_snippets.json

Lines changed: 349 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3891,6 +3891,25 @@
38913891
"utility"
38923892
],
38933893
"author": "Mathys-Gasnier"
3894+
},
3895+
{
3896+
"title": "String to Vec<char>",
3897+
"description": "Convert a String into a vector of characters",
3898+
"code": [
3899+
"fn string_to_chars(s: &str) -> Vec<char> {",
3900+
" s.chars().collect()",
3901+
"}",
3902+
"",
3903+
"// Usage:",
3904+
"let chars = string_to_chars(\"Hello\"); // ['H', 'e', 'l', 'l', 'o']"
3905+
],
3906+
"tags": [
3907+
"rust",
3908+
"string",
3909+
"vector",
3910+
"chars"
3911+
],
3912+
"author": "pyyupsk"
38943913
}
38953914
]
38963915
},
@@ -3954,6 +3973,336 @@
39543973
}
39553974
]
39563975
},
3976+
{
3977+
"language": "rust",
3978+
"categoryName": "Concurrency",
3979+
"snippets": [
3980+
{
3981+
"title": "Thread Pool Implementation",
3982+
"description": "A simple thread pool implementation for parallel task execution",
3983+
"code": [
3984+
"use std::sync::{mpsc, Arc, Mutex};",
3985+
"use std::thread;",
3986+
"",
3987+
"type Job = Box<dyn FnOnce() + Send + 'static>;",
3988+
"",
3989+
"pub struct ThreadPool {",
3990+
" workers: Vec<Worker>,",
3991+
" sender: Option<mpsc::Sender<Job>>,",
3992+
"}",
3993+
"",
3994+
"struct Worker {",
3995+
" id: usize,",
3996+
" thread: Option<thread::JoinHandle<()>>,",
3997+
"}",
3998+
"",
3999+
"impl ThreadPool {",
4000+
" pub fn new(size: usize) -> ThreadPool {",
4001+
" assert!(size > 0);",
4002+
"",
4003+
" let (sender, receiver) = mpsc::channel();",
4004+
" let receiver = Arc::new(Mutex::new(receiver));",
4005+
" let mut workers = Vec::with_capacity(size);",
4006+
"",
4007+
" for id in 0..size {",
4008+
" workers.push(Worker::new(id, Arc::clone(&receiver)));",
4009+
" }",
4010+
"",
4011+
" ThreadPool {",
4012+
" workers,",
4013+
" sender: Some(sender),",
4014+
" }",
4015+
" }",
4016+
"",
4017+
" pub fn execute<F>(&self, f: F)",
4018+
" where",
4019+
" F: FnOnce() + Send + 'static,",
4020+
" {",
4021+
" let job = Box::new(f);",
4022+
" self.sender.as_ref().unwrap().send(job).unwrap();",
4023+
" }",
4024+
"}",
4025+
"",
4026+
"impl Worker {",
4027+
" fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {",
4028+
" let thread = thread::spawn(move || loop {",
4029+
" let message = receiver.lock().unwrap().recv();",
4030+
"",
4031+
" match message {",
4032+
" Ok(job) => {",
4033+
" println!(\"Worker {id} got a job; executing.\");",
4034+
" job();",
4035+
" }",
4036+
" Err(_) => {",
4037+
" println!(\"Worker {id} disconnected; shutting down.\");",
4038+
" break;",
4039+
" }",
4040+
" }",
4041+
" });",
4042+
"",
4043+
" Worker {",
4044+
" id,",
4045+
" thread: Some(thread),",
4046+
" }",
4047+
" }",
4048+
"}",
4049+
"",
4050+
"impl Drop for ThreadPool {",
4051+
" fn drop(&mut self) {",
4052+
" drop(self.sender.take());",
4053+
"",
4054+
" for worker in &mut self.workers {",
4055+
" if let Some(thread) = worker.thread.take() {",
4056+
" thread.join().unwrap();",
4057+
" }",
4058+
" }",
4059+
" }",
4060+
"}"
4061+
],
4062+
"tags": [
4063+
"rust",
4064+
"concurrency",
4065+
"thread-pool",
4066+
"parallel"
4067+
],
4068+
"author": "pyyupsk"
4069+
}
4070+
]
4071+
},
4072+
{
4073+
"language": "rust",
4074+
"categoryName": "Advanced Patterns",
4075+
"snippets": [
4076+
{
4077+
"title": "Type-Safe Builder Pattern",
4078+
"description": "Implements a compile-time type-safe builder pattern using phantom types",
4079+
"code": [
4080+
"use std::marker::PhantomData;",
4081+
"",
4082+
"#[derive(Debug)]",
4083+
"pub struct Builder<Name, Age> {",
4084+
" name: Option<String>,",
4085+
" age: Option<u32>,",
4086+
" _name: PhantomData<Name>,",
4087+
" _age: PhantomData<Age>,",
4088+
"}",
4089+
"",
4090+
"pub struct Missing;",
4091+
"pub struct Set;",
4092+
"",
4093+
"#[derive(Debug)]",
4094+
"pub struct Person {",
4095+
" name: String,",
4096+
" age: u32,",
4097+
"}",
4098+
"",
4099+
"impl Default for Builder<Missing, Missing> {",
4100+
" fn default() -> Self {",
4101+
" Self {",
4102+
" name: None,",
4103+
" age: None,",
4104+
" _name: PhantomData,",
4105+
" _age: PhantomData,",
4106+
" }",
4107+
" }",
4108+
"}",
4109+
"",
4110+
"impl<Age> Builder<Missing, Age> {",
4111+
" pub fn name(self, name: impl Into<String>) -> Builder<Set, Age> {",
4112+
" Builder {",
4113+
" name: Some(name.into()),",
4114+
" age: self.age,",
4115+
" _name: PhantomData,",
4116+
" _age: PhantomData,",
4117+
" }",
4118+
" }",
4119+
"}",
4120+
"",
4121+
"impl<Name> Builder<Name, Missing> {",
4122+
" pub fn age(self, age: u32) -> Builder<Name, Set> {",
4123+
" Builder {",
4124+
" name: self.name,",
4125+
" age: Some(age),",
4126+
" _name: PhantomData,",
4127+
" _age: PhantomData,",
4128+
" }",
4129+
" }",
4130+
"}",
4131+
"",
4132+
"impl Builder<Set, Set> {",
4133+
" pub fn build(self) -> Person {",
4134+
" Person {",
4135+
" name: self.name.unwrap(),",
4136+
" age: self.age.unwrap(),",
4137+
" }",
4138+
" }",
4139+
"}",
4140+
"",
4141+
"// Usage:",
4142+
"let person = Builder::default()",
4143+
" .name(\"John\")",
4144+
" .age(30)",
4145+
" .build();"
4146+
],
4147+
"tags": [
4148+
"rust",
4149+
"design-pattern",
4150+
"builder",
4151+
"type-safe"
4152+
],
4153+
"author": "pyyupsk"
4154+
}
4155+
]
4156+
},
4157+
{
4158+
"language": "rust",
4159+
"categoryName": "Async Programming",
4160+
"snippets": [
4161+
{
4162+
"title": "Async Rate Limiter",
4163+
"description": "Implementation of a token bucket rate limiter for async operations",
4164+
"code": [
4165+
"use std::sync::Arc;",
4166+
"use tokio::sync::Semaphore;",
4167+
"use tokio::time::{interval, Duration};",
4168+
"",
4169+
"pub struct RateLimiter {",
4170+
" semaphore: Arc<Semaphore>,",
4171+
"}",
4172+
"",
4173+
"impl RateLimiter {",
4174+
" pub fn new(rate: u32, interval: Duration) -> Self {",
4175+
" let semaphore = Arc::new(Semaphore::new(rate as usize));",
4176+
" let sem_clone = semaphore.clone();",
4177+
"",
4178+
" tokio::spawn(async move {",
4179+
" let mut ticker = interval(interval);",
4180+
" loop {",
4181+
" ticker.tick().await;",
4182+
" sem_clone.add_permits(rate as usize);",
4183+
" }",
4184+
" });",
4185+
"",
4186+
" RateLimiter { semaphore }",
4187+
" }",
4188+
"",
4189+
" pub async fn acquire(&self) -> RateLimit {",
4190+
" let permit = self.semaphore.acquire().await.unwrap();",
4191+
" RateLimit { _permit: permit }",
4192+
" }",
4193+
"}",
4194+
"",
4195+
"pub struct RateLimit<'a> {",
4196+
" _permit: tokio::sync::SemaphorePermit<'a>,",
4197+
"}",
4198+
"",
4199+
"// Usage:",
4200+
"async fn example() {",
4201+
" let limiter = RateLimiter::new(10, Duration::from_secs(1));",
4202+
"",
4203+
" for i in 0..20 {",
4204+
" let _permit = limiter.acquire().await;",
4205+
" println!(\"Executing task {}\", i);",
4206+
" }",
4207+
"}"
4208+
],
4209+
"tags": [
4210+
"rust",
4211+
"async",
4212+
"rate-limiter",
4213+
"tokio"
4214+
],
4215+
"author": "pyyupsk"
4216+
}
4217+
]
4218+
},
4219+
{
4220+
"language": "rust",
4221+
"categoryName": "Memory Management",
4222+
"snippets": [
4223+
{
4224+
"title": "Custom Smart Pointer",
4225+
"description": "Implementation of a custom reference-counted smart pointer with interior mutability",
4226+
"code": [
4227+
"use std::cell::UnsafeCell;",
4228+
"use std::ops::{Deref, DerefMut};",
4229+
"use std::sync::atomic::{AtomicUsize, Ordering};",
4230+
"use std::sync::Arc;",
4231+
"",
4232+
"pub struct Interior<T> {",
4233+
" ref_count: AtomicUsize,",
4234+
" data: UnsafeCell<T>,",
4235+
"}",
4236+
"",
4237+
"pub struct SmartPtr<T> {",
4238+
" ptr: Arc<Interior<T>>,",
4239+
"}",
4240+
"",
4241+
"impl<T> SmartPtr<T> {",
4242+
" pub fn new(data: T) -> Self {",
4243+
" SmartPtr {",
4244+
" ptr: Arc::new(Interior {",
4245+
" ref_count: AtomicUsize::new(1),",
4246+
" data: UnsafeCell::new(data),",
4247+
" }),",
4248+
" }",
4249+
" }",
4250+
"",
4251+
" pub fn get_ref_count(&self) -> usize {",
4252+
" self.ptr.ref_count.load(Ordering::SeqCst)",
4253+
" }",
4254+
"}",
4255+
"",
4256+
"impl<T> Clone for SmartPtr<T> {",
4257+
" fn clone(&self) -> Self {",
4258+
" self.ptr.ref_count.fetch_add(1, Ordering::SeqCst);",
4259+
" SmartPtr {",
4260+
" ptr: Arc::clone(&self.ptr),",
4261+
" }",
4262+
" }",
4263+
"}",
4264+
"",
4265+
"impl<T> Drop for SmartPtr<T> {",
4266+
" fn drop(&mut self) {",
4267+
" if self.ptr.ref_count.fetch_sub(1, Ordering::SeqCst) == 1 {",
4268+
" // Last reference is being dropped",
4269+
" unsafe {",
4270+
" drop(Box::from_raw(self.ptr.data.get()));",
4271+
" }",
4272+
" }",
4273+
" }",
4274+
"}",
4275+
"",
4276+
"impl<T> Deref for SmartPtr<T> {",
4277+
" type Target = T;",
4278+
"",
4279+
" fn deref(&self) -> &Self::Target {",
4280+
" unsafe { &*self.ptr.data.get() }",
4281+
" }",
4282+
"}",
4283+
"",
4284+
"impl<T> DerefMut for SmartPtr<T> {",
4285+
" fn deref_mut(&mut self) -> &mut Self::Target {",
4286+
" unsafe { &mut *self.ptr.data.get() }",
4287+
" }",
4288+
"}",
4289+
"",
4290+
"// Usage:",
4291+
"let ptr = SmartPtr::new(42);",
4292+
"let cloned = ptr.clone();",
4293+
"assert_eq!(ptr.get_ref_count(), 2);",
4294+
"assert_eq!(*ptr, 42);"
4295+
],
4296+
"tags": [
4297+
"rust",
4298+
"smart-pointer",
4299+
"memory-management",
4300+
"unsafe"
4301+
],
4302+
"author": "pyyupsk"
4303+
}
4304+
]
4305+
},
39574306
{
39584307
"language": "scss",
39594308
"categoryName": "Typography",

0 commit comments

Comments
 (0)