"Alright generic gurus assemble..." <- > <@korken89:matrix.org> Alright generic gurus assemble! I'm trying to write an algorithm generic over atomic width. More or less, I want to build a `BitChannel` where the atomic holds flags from `bitflags` crate. The thing is, below is my try to make an atomic that is generic over width - i.e. place stuff in memory and dance it like it was an atomic. Is there any better way to get this generic width atomic? > > > ``` > use core::{cell::UnsafeCell, marker::PhantomData}; > use bitflags::{Bits, Flags}; > use portable_atomic::{AtomicU16, AtomicU8, Ordering}; > > // > // Bit channel > // > > pub struct BitChannel { > _p: PhantomData, > atomic: AtomicStorage<::Bits>, > } > > impl BitChannel > where > T: Flags, > AtomicStorage<::Bits>: AtomicOps<::Bits>, > { > pub fn new() -> Self { > BitChannel { > _p: PhantomData, > atomic: AtomicStorage(UnsafeCell::new(::Bits::EMPTY)), > } > } > > pub fn test(&self) -> T { > ::from_bits_retain(self.atomic.fetch_and(::Bits::EMPTY)) > } > } > > // > // Atomic ops of generic width > // > > trait AtomicOps { > fn fetch_and(&self, val: T) -> T; > } > > struct AtomicStorage(UnsafeCell); > > impl AtomicOps for AtomicStorage { > fn fetch_and(&self, val: u8) -> u8 { > unsafe { &*(self.0.get() as *const AtomicU8) }.fetch_and(val, Ordering::Relaxed) > } > } > > impl AtomicOps for AtomicStorage { > fn fetch_and(&self, val: u16) -> u16 { > unsafe { &*(self.0.get() as *const AtomicU16) }.fetch_and(val, Ordering::Relaxed) > } > } > > // etc... > ``` This was the original one