Created
August 3, 2019 10:32
-
-
Save DutchGhost/5ce031385bcf730440a4e1caa76f3637 to your computer and use it in GitHub Desktop.
Gist for a question about `first_ptr` and `first_ptr_mut`
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
| pub(crate) struct MaybeArray<T, const N: usize> { | |
| array: [MaybeUninit<T>; N], | |
| } | |
| impl<T, const N: usize> Default for MaybeArray<T, { N }> { | |
| #[inline(always)] | |
| fn default() -> Self { | |
| Self { | |
| array: unsafe { MaybeUninit::<_>::uninit().assume_init() }, | |
| } | |
| } | |
| } | |
| impl<T, const N: usize> MaybeArray<T, { N }> { | |
| /// Returns the capacity of the array. | |
| pub const fn capacity(&self) -> usize { | |
| N | |
| } | |
| /// Returns a pointer to the element at `index`. | |
| /// This element *may* be uninitialized. | |
| #[inline(always)] | |
| pub fn nth_ptr(&self, index: usize) -> *const T { | |
| debug_assert!(index < N); | |
| unsafe { | |
| let nth_element = &*(self.array.get_unchecked(index)); | |
| nth_element.as_ptr() | |
| } | |
| } | |
| /// Returns a mutable pointer to the element at `index`. | |
| /// This element *may* be uninitialized. | |
| #[inline(always)] | |
| pub fn nth_ptr_mut(&mut self, index: usize) -> *mut T { | |
| debug_assert!(index < N); | |
| unsafe { | |
| let nth_element = &mut *(self.array.get_unchecked_mut(index)); | |
| nth_element.as_mut_ptr() | |
| } | |
| } | |
| /// Returns a pointer to the first element of the array. | |
| /// This element *may* be uninitialized. | |
| #[inline(always)] | |
| pub fn first_ptr(&self) -> *const T { | |
| self.nth_ptr(0) | |
| } | |
| /// Returns a mutable pointer to the first element of the array. | |
| /// This element *may* be uninitialized. | |
| #[inline(always)] | |
| pub fn first_ptr_mut(&mut self) -> *mut T { | |
| self.nth_ptr_mut(0) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment