Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit1c1c0d1

Browse files
committed
refactor: change code snippets to new format
1 parent922c915 commit1c1c0d1

File tree

5 files changed

+305
-0
lines changed

5 files changed

+305
-0
lines changed
Lines changed: 75 additions & 0 deletions
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+
usestd::marker::PhantomData;
10+
11+
#[derive(Debug)]
12+
pubstructBuilder<Name,Age> {
13+
name:Option<String>,
14+
age:Option<u32>,
15+
_name:PhantomData<Name>,
16+
_age:PhantomData<Age>,
17+
}
18+
19+
pubstructMissing;
20+
pubstructSet;
21+
22+
#[derive(Debug)]
23+
pubstructPerson {
24+
name:String,
25+
age:u32,
26+
}
27+
28+
implDefaultforBuilder<Missing,Missing> {
29+
fndefault()->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+
pubfnname(self,name:implInto<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+
pubfnage(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+
implBuilder<Set,Set> {
62+
pubfnbuild(self)->Person {
63+
Person {
64+
name:self.name.unwrap(),
65+
age:self.age.unwrap(),
66+
}
67+
}
68+
}
69+
70+
// Usage:
71+
letperson=Builder::default()
72+
.name("John")
73+
.age(30)
74+
.build();
75+
```
Lines changed: 52 additions & 0 deletions
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+
usestd::sync::Arc;
10+
usetokio::sync::Semaphore;
11+
usetokio::time::{interval,Duration};
12+
13+
pubstructRateLimiter {
14+
semaphore:Arc<Semaphore>,
15+
}
16+
17+
implRateLimiter {
18+
pubfnnew(rate:u32,interval:Duration)->Self {
19+
letsemaphore=Arc::new(Semaphore::new(rateasusize));
20+
letsem_clone=semaphore.clone();
21+
22+
tokio::spawn(asyncmove {
23+
letmutticker=interval(interval);
24+
loop {
25+
ticker.tick().await;
26+
sem_clone.add_permits(rateasusize);
27+
}
28+
});
29+
30+
RateLimiter {semaphore }
31+
}
32+
33+
pubasyncfnacquire(&self)->RateLimit {
34+
letpermit=self.semaphore.acquire().await.unwrap();
35+
RateLimit {_permit:permit }
36+
}
37+
}
38+
39+
pubstructRateLimit<'a> {
40+
_permit:tokio::sync::SemaphorePermit<'a>,
41+
}
42+
43+
// Usage:
44+
asyncfnexample() {
45+
letlimiter=RateLimiter::new(10,Duration::from_secs(1));
46+
47+
foriin0..20 {
48+
let_permit=limiter.acquire().await;
49+
println!("Executing task {}",i);
50+
}
51+
}
52+
```
Lines changed: 86 additions & 0 deletions
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+
usestd::sync::{mpsc,Arc,Mutex};
10+
usestd::thread;
11+
12+
typeJob=Box<dynFnOnce()+Send+ 'static>;
13+
14+
pubstructThreadPool {
15+
workers:Vec<Worker>,
16+
sender:Option<mpsc::Sender<Job>>,
17+
}
18+
19+
structWorker {
20+
id:usize,
21+
thread:Option<thread::JoinHandle<()>>,
22+
}
23+
24+
implThreadPool {
25+
pubfnnew(size:usize)->ThreadPool {
26+
assert!(size>0);
27+
28+
let (sender,receiver)=mpsc::channel();
29+
letreceiver=Arc::new(Mutex::new(receiver));
30+
letmutworkers=Vec::with_capacity(size);
31+
32+
foridin0..size {
33+
workers.push(Worker::new(id,Arc::clone(&receiver)));
34+
}
35+
36+
ThreadPool {
37+
workers,
38+
sender:Some(sender),
39+
}
40+
}
41+
42+
pubfnexecute<F>(&self,f:F)
43+
where
44+
F:FnOnce()+Send+ 'static,
45+
{
46+
letjob=Box::new(f);
47+
self.sender.as_ref().unwrap().send(job).unwrap();
48+
}
49+
}
50+
51+
implWorker {
52+
fnnew(id:usize,receiver:Arc<Mutex<mpsc::Receiver<Job>>>)->Worker {
53+
letthread=thread::spawn(move||loop {
54+
letmessage=receiver.lock().unwrap().recv();
55+
56+
matchmessage {
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+
implDropforThreadPool {
76+
fndrop(&mutself) {
77+
drop(self.sender.take());
78+
79+
forworkerin&mutself.workers {
80+
ifletSome(thread)=worker.thread.take() {
81+
thread.join().unwrap();
82+
}
83+
}
84+
}
85+
}
86+
```
Lines changed: 77 additions & 0 deletions
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+
usestd::cell::UnsafeCell;
10+
usestd::ops::{Deref,DerefMut};
11+
usestd::sync::atomic::{AtomicUsize,Ordering};
12+
usestd::sync::Arc;
13+
14+
pubstructInterior<T> {
15+
ref_count:AtomicUsize,
16+
data:UnsafeCell<T>,
17+
}
18+
19+
pubstructSmartPtr<T> {
20+
ptr:Arc<Interior<T>>,
21+
}
22+
23+
impl<T>SmartPtr<T> {
24+
pubfnnew(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+
pubfnget_ref_count(&self)->usize {
34+
self.ptr.ref_count.load(Ordering::SeqCst)
35+
}
36+
}
37+
38+
impl<T>CloneforSmartPtr<T> {
39+
fnclone(&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>DropforSmartPtr<T> {
48+
fndrop(&mutself) {
49+
ifself.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>DerefforSmartPtr<T> {
59+
typeTarget=T;
60+
61+
fnderef(&self)->&Self::Target {
62+
unsafe {&*self.ptr.data.get() }
63+
}
64+
}
65+
66+
impl<T>DerefMutforSmartPtr<T> {
67+
fnderef_mut(&mutself)->&mutSelf::Target {
68+
unsafe {&mut*self.ptr.data.get() }
69+
}
70+
}
71+
72+
// Usage:
73+
letptr=SmartPtr::new(42);
74+
letcloned=ptr.clone();
75+
assert_eq!(ptr.get_ref_count(),2);
76+
assert_eq!(*ptr,42);
77+
```
Lines changed: 15 additions & 0 deletions
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+
fnstring_to_chars(s:&str)->Vec<char> {
10+
s.chars().collect()
11+
}
12+
13+
// Usage:
14+
letchars=string_to_chars("Hello");// ['H', 'e', 'l', 'l', 'o']
15+
```

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp