Cache-padded data structures for MoonBit to reduce false sharing
// Create cache-padded integer
let padded_counter = CachePaddedInt::new(42)
// Access the value
let value = padded_counter.get() // Returns 42
// Update the value
padded_counter.set(100)
let new_value = padded_counter.get() // Returns 100
// Update using a transformation function
padded_counter.update(fn(x) { x * 2 })
// Clean up (important!)
padded_counter.destroy()| Feature | Rust CachePadded | This MoonBit Implementation |
|---|---|---|
| Memory Allocation | Stack allocation | Heap allocation (malloc) |
| Alignment Method | Compile-time repr(align) | Runtime pointer calculation |
| Access Overhead | Zero-cost (Deref trait) | FFI function calls |
| Memory Management | Automatic cleanup | Manual destroy() required |
| Space Overhead | Exact padding calculation | Extra cache line allocation |
// Rust achieves true zero-cost abstraction
#[repr(align(64))]
pub struct CachePadded<T> {
value: T,
}
// Stack allocated, compile-time aligned, zero runtime overhead
let padded = CachePadded::new(42); // No malloc!
let value = *padded; // Direct memory access, no function call!// Without padding: two variables might share a cache line
let a = 1
let b = 2 // Might be on same cache line as 'a'
// With padding: each variable gets its own cache line
let padded_a = CachePaddedInt::new(1)
let padded_b = CachePaddedInt::new(2) // Guaranteed on different cache linelet cache_size = get_cache_line_size() // Returns 64 on most modern systems# Check code
moon check --target native
# Run tests
moon test --target native
# Format code
moon fmtCache-padded data structures for MoonBit to reduce false sharing