refactor(data_structures): add read method to NonNull shim (#7022)

Emulate [`NonNull::read`](https://doc.rust-lang.org/beta/std/ptr/struct.NonNull.html#method.read) method in `NonNull` shim. This is more ergonomic, and will be ideal usage once our MSRV reaches 1.80.0 and we can remove the shim.
This commit is contained in:
overlookmotel 2024-10-30 13:00:21 +00:00
parent c58ec89b81
commit f1fc8db2fb
3 changed files with 10 additions and 4 deletions

View file

@ -295,7 +295,7 @@ impl<T> NonEmptyStack<T> {
debug_assert!(self.cursor < self.end);
// SAFETY: All methods ensure `self.cursor` is always in bounds, is aligned for `T`,
// and points to a valid initialized `T`
let value = self.cursor.as_ptr().read();
let value = self.cursor.read();
// SAFETY: Caller guarantees there's at least 2 entries on stack, so subtracting 1
// cannot be out of bounds
self.cursor = self.cursor.sub(1);

View file

@ -1,6 +1,7 @@
use std::{cmp::Ordering, ptr::NonNull as NativeNonNull};
/// Wrapper around `NonNull<T>`, which adds methods `add`, `sub`, `offset_from` and `byte_offset_from`.
/// Wrapper around `NonNull<T>`, which adds methods `add`, `sub`, `offset_from`, `byte_offset_from`,
/// and `read`.
/// These methods exist on `std::ptr::NonNull`, and became stable in Rust 1.80.0, but are not yet
/// stable in our MSRV.
///
@ -8,7 +9,7 @@ use std::{cmp::Ordering, ptr::NonNull as NativeNonNull};
/// and make code using them easier to understand.
///
/// Once we bump MSRV and these methods are natively supported, this type can be removed.
/// `#[expect(clippy::incompatible_msrv)]` on `non_null_add_is_not_stable` below will trigger
/// `#[expect(clippy::incompatible_msrv)]` on `_non_null_add_is_not_stable` below will trigger
/// a lint warning when that happens.
/// Then this module can be deleted, and all uses of this type can be switched to `std::ptr::NonNull`.
#[derive(Debug)]
@ -71,6 +72,11 @@ impl<T> NonNull<T> {
pub unsafe fn as_mut<'t>(mut self) -> &'t mut T {
self.0.as_mut()
}
#[inline]
pub unsafe fn read(self) -> T {
self.0.as_ptr().read()
}
}
impl<T> Copy for NonNull<T> {}

View file

@ -307,7 +307,7 @@ impl<T> Stack<T> {
// SAFETY: All methods ensure `self.cursor` is always in bounds, is aligned for `T`,
// and points to a valid initialized `T`, if stack is not empty.
// Caller guarantees stack was not empty.
self.cursor.as_ptr().read()
self.cursor.read()
}
/// Get number of entries on stack.