Skip to content

Commit 1c1c0d1

Browse files
committed
refactor: change code snippets to new format
1 parent 922c915 commit 1c1c0d1

File tree

5 files changed

+305
-0
lines changed

5 files changed

+305
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
---
2+
title: Type-Safe Builder Pattern
3+
description: Implements a compile-time type-safe builder pattern using phantom types
4+
author: pyyupsk
5+
tags: rust,design-pattern,builder,type-safe
6+
---
7+
8+
```rust
9+
use std::marker::PhantomData;
10+
11+
#[derive(Debug)]
12+
pub struct Builder<Name, Age> {
13+
name: Option<String>,
14+
age: Option<u32>,
15+
_name: PhantomData<Name>,
16+
_age: PhantomData<Age>,
17+
}
18+
19+
pub struct Missing;
20+
pub struct Set;
21+
22+
#[derive(Debug)]
23+
pub struct Person {
24+
name: String,
25+
age: u32,
26+
}
27+
28+
impl Default for Builder<Missing, Missing> {
29+
fn default() -> Self {
30+
Self {
31+
name: None,
32+
age: None,
33+
_name: PhantomData,
34+
_age: PhantomData,
35+
}
36+
}
37+
}
38+
39+
impl<Age> Builder<Missing, Age> {
40+
pub fn name(self, name: impl Into<String>) -> Builder<Set, Age> {
41+
Builder {
42+
name: Some(name.into()),
43+
age: self.age,
44+
_name: PhantomData,
45+
_age: PhantomData,
46+
}
47+
}
48+
}
49+
50+
impl<Name> Builder<Name, Missing> {
51+
pub fn age(self, age: u32) -> Builder<Name, Set> {
52+
Builder {
53+
name: self.name,
54+
age: Some(age),
55+
_name: PhantomData,
56+
_age: PhantomData,
57+
}
58+
}
59+
}
60+
61+
impl Builder<Set, Set> {
62+
pub fn build(self) -> Person {
63+
Person {
64+
name: self.name.unwrap(),
65+
age: self.age.unwrap(),
66+
}
67+
}
68+
}
69+
70+
// Usage:
71+
let person = Builder::default()
72+
.name("John")
73+
.age(30)
74+
.build();
75+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
---
2+
title: Async Rate Limiter
3+
description: Implementation of a token bucket rate limiter for async operations
4+
author: pyyupsk
5+
tags: rust,async,rate-limiter,tokio
6+
---
7+
8+
```rust
9+
use std::sync::Arc;
10+
use tokio::sync::Semaphore;
11+
use tokio::time::{interval, Duration};
12+
13+
pub struct RateLimiter {
14+
semaphore: Arc<Semaphore>,
15+
}
16+
17+
impl RateLimiter {
18+
pub fn new(rate: u32, interval: Duration) -> Self {
19+
let semaphore = Arc::new(Semaphore::new(rate as usize));
20+
let sem_clone = semaphore.clone();
21+
22+
tokio::spawn(async move {
23+
let mut ticker = interval(interval);
24+
loop {
25+
ticker.tick().await;
26+
sem_clone.add_permits(rate as usize);
27+
}
28+
});
29+
30+
RateLimiter { semaphore }
31+
}
32+
33+
pub async fn acquire(&self) -> RateLimit {
34+
let permit = self.semaphore.acquire().await.unwrap();
35+
RateLimit { _permit: permit }
36+
}
37+
}
38+
39+
pub struct RateLimit<'a> {
40+
_permit: tokio::sync::SemaphorePermit<'a>,
41+
}
42+
43+
// Usage:
44+
async fn example() {
45+
let limiter = RateLimiter::new(10, Duration::from_secs(1));
46+
47+
for i in 0..20 {
48+
let _permit = limiter.acquire().await;
49+
println!("Executing task {}", i);
50+
}
51+
}
52+
```
+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
---
2+
title: Thread Pool Implementation
3+
description: A simple thread pool implementation for parallel task execution
4+
author: pyyupsk
5+
tags: rust,concurrency,thread-pool,parallel
6+
---
7+
8+
```rust
9+
use std::sync::{mpsc, Arc, Mutex};
10+
use std::thread;
11+
12+
type Job = Box<dyn FnOnce() + Send + 'static>;
13+
14+
pub struct ThreadPool {
15+
workers: Vec<Worker>,
16+
sender: Option<mpsc::Sender<Job>>,
17+
}
18+
19+
struct Worker {
20+
id: usize,
21+
thread: Option<thread::JoinHandle<()>>,
22+
}
23+
24+
impl ThreadPool {
25+
pub fn new(size: usize) -> ThreadPool {
26+
assert!(size > 0);
27+
28+
let (sender, receiver) = mpsc::channel();
29+
let receiver = Arc::new(Mutex::new(receiver));
30+
let mut workers = Vec::with_capacity(size);
31+
32+
for id in 0..size {
33+
workers.push(Worker::new(id, Arc::clone(&receiver)));
34+
}
35+
36+
ThreadPool {
37+
workers,
38+
sender: Some(sender),
39+
}
40+
}
41+
42+
pub fn execute<F>(&self, f: F)
43+
where
44+
F: FnOnce() + Send + 'static,
45+
{
46+
let job = Box::new(f);
47+
self.sender.as_ref().unwrap().send(job).unwrap();
48+
}
49+
}
50+
51+
impl Worker {
52+
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
53+
let thread = thread::spawn(move || loop {
54+
let message = receiver.lock().unwrap().recv();
55+
56+
match message {
57+
Ok(job) => {
58+
println!("Worker {id} got a job; executing.");
59+
job();
60+
}
61+
Err(_) => {
62+
println!("Worker {id} disconnected; shutting down.");
63+
break;
64+
}
65+
}
66+
});
67+
68+
Worker {
69+
id,
70+
thread: Some(thread),
71+
}
72+
}
73+
}
74+
75+
impl Drop for ThreadPool {
76+
fn drop(&mut self) {
77+
drop(self.sender.take());
78+
79+
for worker in &mut self.workers {
80+
if let Some(thread) = worker.thread.take() {
81+
thread.join().unwrap();
82+
}
83+
}
84+
}
85+
}
86+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
---
2+
title: Custom Smart Pointer
3+
description: Implementation of a custom reference-counted smart pointer with interior mutability
4+
author: pyyupsk
5+
tags: rust,smart-pointer,memory-management,unsafe
6+
---
7+
8+
```rust
9+
use std::cell::UnsafeCell;
10+
use std::ops::{Deref, DerefMut};
11+
use std::sync::atomic::{AtomicUsize, Ordering};
12+
use std::sync::Arc;
13+
14+
pub struct Interior<T> {
15+
ref_count: AtomicUsize,
16+
data: UnsafeCell<T>,
17+
}
18+
19+
pub struct SmartPtr<T> {
20+
ptr: Arc<Interior<T>>,
21+
}
22+
23+
impl<T> SmartPtr<T> {
24+
pub fn new(data: T) -> Self {
25+
SmartPtr {
26+
ptr: Arc::new(Interior {
27+
ref_count: AtomicUsize::new(1),
28+
data: UnsafeCell::new(data),
29+
}),
30+
}
31+
}
32+
33+
pub fn get_ref_count(&self) -> usize {
34+
self.ptr.ref_count.load(Ordering::SeqCst)
35+
}
36+
}
37+
38+
impl<T> Clone for SmartPtr<T> {
39+
fn clone(&self) -> Self {
40+
self.ptr.ref_count.fetch_add(1, Ordering::SeqCst);
41+
SmartPtr {
42+
ptr: Arc::clone(&self.ptr),
43+
}
44+
}
45+
}
46+
47+
impl<T> Drop for SmartPtr<T> {
48+
fn drop(&mut self) {
49+
if self.ptr.ref_count.fetch_sub(1, Ordering::SeqCst) == 1 {
50+
// Last reference is being dropped
51+
unsafe {
52+
drop(Box::from_raw(self.ptr.data.get()));
53+
}
54+
}
55+
}
56+
}
57+
58+
impl<T> Deref for SmartPtr<T> {
59+
type Target = T;
60+
61+
fn deref(&self) -> &Self::Target {
62+
unsafe { &*self.ptr.data.get() }
63+
}
64+
}
65+
66+
impl<T> DerefMut for SmartPtr<T> {
67+
fn deref_mut(&mut self) -> &mut Self::Target {
68+
unsafe { &mut *self.ptr.data.get() }
69+
}
70+
}
71+
72+
// Usage:
73+
let ptr = SmartPtr::new(42);
74+
let cloned = ptr.clone();
75+
assert_eq!(ptr.get_ref_count(), 2);
76+
assert_eq!(*ptr, 42);
77+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
title: String to Vec<char>
3+
description: Convert a String into a vector of characters
4+
author: pyyupsk
5+
tags: rust,string,vector,chars
6+
---
7+
8+
```rust
9+
fn string_to_chars(s: &str) -> Vec<char> {
10+
s.chars().collect()
11+
}
12+
13+
// Usage:
14+
let chars = string_to_chars("Hello"); // ['H', 'e', 'l', 'l', 'o']
15+
```

0 commit comments

Comments
 (0)