0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
Rust · ExpertSnippet

Pinned Memory for Async State Machines

The 'Pin' wrapper ensures that a value stays at a fixed memory address. This is critical for self-referential structs where a field stores a pointer to another field within the same object. If the object moved, the internal pointer would become dangling.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use std::pin::Pin;
use std::marker::PhantomPinned;
struct SelfReferential {
data: String,
ptr: *const String,
_pin: PhantomPinned,
}
impl SelfReferential {
pub fn new(data: String) -> Pin<Box<Self>> {
let res = SelfReferential {
data,
ptr: std::ptr::null(),
_pin: PhantomPinned,
};
let mut boxed = Box::pin(res);
let self_ptr: *const String = &boxed.data;
unsafe {
let mut_ref: Pin<&mut Self> = boxed.as_mut();
Pin::get_unchecked_mut(mut_ref).ptr = self_ptr;
}
boxed
}
}
Memory ManagementAsync & Concurrency
Rust · ExpertSnippet

Optimizing with UnsafeCell

'UnsafeCell' is the only legal way to obtain a mutable reference from an immutable one in Rust. It is the primitive behind 'Cell' and 'RefCell'. Using it directly is highly unsafe and requires the developer to manually guarantee that no other references exist simultaneously.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::cell::UnsafeCell;
struct MyCell<T> {
value: UnsafeCell<T>,
}
impl<T> MyCell<T> {
pub fn get_mut_unsafe(&self) -> &mut T {
unsafe { &mut *self.value.get() }
}
}
// Usage is dangerous and requires strict manual tracking of borrows.
Memory ManagementPerformance
Rust · ExpertSnippet

Manual Send/Sync for FFI Wrappers

By default, types containing raw pointers are neither Send nor Sync. To pass them between threads or share references across threads, you must manually implement these marker traits. This requires an 'unsafe' block because the compiler cannot verify that your synchronization logic or pointer management is sound.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct RawBuffer {
ptr: *mut u8,
len: usize,
}
// SAFETY: We ensure that access to the buffer is synchronized
// and that the pointer is valid for the duration of its use.
unsafe impl Send for RawBuffer {}
unsafe impl Sync for RawBuffer {}
impl RawBuffer {
pub fn as_slice(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
}
Memory ManagementPerformance
Rust · ExpertSnippet

Generic Associated Types (GATs) for Iteration

Generic Associated Types allow associated types to carry a lifetime or type parameter. This is essential for 'Lending Iterators', where the item yielded by the iterator borrows from the iterator itself, a pattern that standard Iterators cannot express efficiently.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
trait LendingIterator {
type Item<'a> where Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
struct MyStream(Vec<u32>);
impl LendingIterator for MyStream {
type Item<'a> = &'a u32;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> {
self.0.get(0) // Simplified logic
}
}
SyntaxBest Practices
Rust · ExpertSnippet

Higher-Rank Trait Bounds (HRTB)

Higher-Rank Trait Bounds (HRTB) allow you to specify that a bound holds for all possible lifetimes. The 'for<'a>' syntax ensures the closure can handle a reference with any lifetime, rather than a specific one fixed at the call site.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
fn process_data<F>(data: &str, handler: F)
where
F: for<'a> Fn(&'a str),
{
handler(data);
}
fn main() {
process_data("expert", |s| println!("Processing: {}", s));
}
SyntaxFunctions
Rust · ExpertSnippet

Data-Level Parallelism with Portable SIMD

Portable SIMD (Single Instruction, Multiple Data) allows you to perform operations on multiple values simultaneously using CPU vector instructions. By packing four f32 values into a single f32x4 register, we can perform additions in parallel, significantly boosting performance for numerical computations and signal processing.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
#![feature(portable_simd)]
use std::simd::f32x4;
fn fast_add(a: [f32; 4], b: [f32; 4]) -> [f32; 4] {
let va = f32x4::from_array(a);
let vb = f32x4::from_array(b);
let sum = va + vb; // Executes a single SIMD instruction (e.g., ADDPS)
sum.to_array()
}
PerformanceArrays & Lists
Rust · ExpertSnippet

Object Safety and Vtable Constraints

Not all traits can be used as dynamic trait objects (dyn Trait). For a trait to be 'object-safe', it cannot have generic methods or return 'Self' by value. However, you can keep a trait object-safe by adding a 'where Self: Sized' bound to specific methods, which excludes them from the vtable and prevents them from being called on dynamic objects.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
trait AdvancedPlugin {
fn execute(&self);
// This method makes the trait NOT object-safe if called on a Trait Object
fn generic_helper<T>(&self, _data: T) where Self: Sized;
}
fn run_plugins(plugins: &[Box<dyn AdvancedPlugin>]) {
for p in plugins {
p.execute();
// p.generic_helper(42); // Error: cannot call generic method on dyn trait
}
}
FunctionsMemory Management
Rust · ExpertSnippet

Zero-Cost Typestate Pattern with PhantomData

The Typestate pattern uses Rust's type system to enforce state transitions at compile time. By using PhantomData, we can differentiate states without incurring any runtime memory overhead. This ensures that methods like 'process' can only be called once the data has reached the 'Checked' state.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use std::marker::PhantomData;
struct Unchecked;
struct Checked;
struct Data<S> {
value: String,
_state: PhantomData<S>,
}
impl Data<Unchecked> {
fn new(v: &str) -> Self {
Data { value: v.into(), _state: PhantomData }
}
fn validate(self) -> Data<Checked> {
// Perform complex validation logic here
Data { value: self.value, _state: PhantomData }
}
}
impl Data<Checked> {
fn process(&self) {
println!("Processing validated data: {}", self.value);
}
}
SyntaxBest Practices