|
| 1 | +// SPDX-License-Identifier: GPL-2.0 |
| 2 | + |
| 3 | +use macros::pin_data; |
| 4 | + |
| 5 | +use crate::{init::PinInit, pin_init, try_pin_init}; |
| 6 | + |
| 7 | +/// Wrapper type that alings content to a cache line. |
| 8 | +#[repr(align(64))] |
| 9 | +#[pin_data] |
| 10 | +pub struct CacheAligned<T: ?Sized> { |
| 11 | + #[pin] |
| 12 | + value: T, |
| 13 | +} |
| 14 | + |
| 15 | +impl<T> CacheAligned<T> { |
| 16 | + /// Pads and aligns a value to 64 bytes. |
| 17 | + pub const fn new(t: T) -> CacheAligned<T> { |
| 18 | + CacheAligned::<T> { value: t } |
| 19 | + } |
| 20 | + |
| 21 | + /// Creates an initializer for `CacheAligned<T>` form an initalizer for `T` |
| 22 | + pub fn new_initializer( |
| 23 | + t: impl PinInit<T>, |
| 24 | + ) -> impl PinInit<CacheAligned<T>> { |
| 25 | + pin_init!( CacheAligned { |
| 26 | + value <- t |
| 27 | + }) |
| 28 | + } |
| 29 | + |
| 30 | + /// Creates a fallible initializer for `CacheAligned<T>` form a fallible |
| 31 | + /// initalizer for `T` |
| 32 | + pub fn try_new_initializer( |
| 33 | + t: impl PinInit<T, crate::error::Error>, |
| 34 | + ) -> impl PinInit<CacheAligned<T>, crate::error::Error> { |
| 35 | + try_pin_init!( CacheAligned { |
| 36 | + value <- t |
| 37 | + }) |
| 38 | + } |
| 39 | + |
| 40 | + /// Get a pointer to the contained value without creating a reference. |
| 41 | + /// |
| 42 | + /// # Safety |
| 43 | + /// |
| 44 | + /// `ptr` must point to a valid and initialized instance of `Self` and it |
| 45 | + /// must be valid for read and write. |
| 46 | + pub const unsafe fn raw_get(ptr: *mut Self) -> *mut T { |
| 47 | + // SAFETY: by function safety requirements `ptr` is valid for read |
| 48 | + unsafe { core::ptr::addr_of_mut!((*ptr).value) } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +impl<T: ?Sized> core::ops::Deref for CacheAligned<T> { |
| 53 | + type Target = T; |
| 54 | + |
| 55 | + fn deref(&self) -> &T { |
| 56 | + &self.value |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +impl<T: ?Sized> core::ops::DerefMut for CacheAligned<T> { |
| 61 | + fn deref_mut(&mut self) -> &mut T { |
| 62 | + &mut self.value |
| 63 | + } |
| 64 | +} |
0 commit comments