This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Niche optimization | |
| // A clever way to make Option<T> (or similar enums) use the exact same memory | |
| // size as T itself, without wasting space for a "tag" | |
| // (like a boolean for Some/None). | |
| use std::mem::{size_of, MaybeUninit}; | |
| fn main() { | |
| // Seeing the size overhead of using Option types | |
| println!("size_of::<i32>(): {}", size_of::<i32>()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Creating a heapless vector type using MaybeUninit<T> safely with | |
| // unintialized memory (useful in embedded systems where there's limited | |
| // memory space for heap allocations). | |
| #![no_std] | |
| extern crate std; | |
| use arrayvec::ArrayVec; | |
| mod arrayvec { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Creating a heapless vector type using MaybeUninit<T> safely for | |
| // unintialized memory (useful in embedded systems where there's limited | |
| // memory space for heap allocations). | |
| #![no_std] | |
| extern crate std; | |
| use arrayvec::ArrayVec; | |
| mod arrayvec { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Creating a heapless vector type (useful in embedded systems where there's | |
| // limited memory space for heap allocations) | |
| #[derive(Debug)] | |
| struct ArrayVec<T, const N: usize> | |
| where | |
| T: Copy | |
| { | |
| values: [Option<T>; N], | |
| len: usize, |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; | |
| use std::thread; | |
| static DATA: AtomicU64 = AtomicU64::new(0); // Atomic Data | |
| static READY: AtomicBool = AtomicBool::new(false); // Flag | |
| fn main() { | |
| let _producer = thread::spawn(|| { | |
| // ...Expensive operations captured by Ordering::Release. | |
| DATA.store(123456, Ordering::Relaxed); // Data store here, though relaxed, is covered by Ordering::Release. |