Make use of [wrapping_]byte_{add,sub}

...replacing `.cast().wrapping_offset().cast()` & similar code.
This commit is contained in:
Maybe Waffle 2022-08-19 13:20:22 +04:00
parent 1cff564203
commit 53565b23ac
10 changed files with 17 additions and 18 deletions

View File

@ -16,6 +16,7 @@
#![feature(maybe_uninit_slice)] #![feature(maybe_uninit_slice)]
#![feature(min_specialization)] #![feature(min_specialization)]
#![feature(decl_macro)] #![feature(decl_macro)]
#![feature(pointer_byte_offsets)]
#![feature(rustc_attrs)] #![feature(rustc_attrs)]
#![cfg_attr(test, feature(test))] #![cfg_attr(test, feature(test))]
#![feature(strict_provenance)] #![feature(strict_provenance)]
@ -211,7 +212,7 @@ pub fn alloc(&self, object: T) -> &mut T {
unsafe { unsafe {
if mem::size_of::<T>() == 0 { if mem::size_of::<T>() == 0 {
self.ptr.set((self.ptr.get() as *mut u8).wrapping_offset(1) as *mut T); self.ptr.set(self.ptr.get().wrapping_byte_add(1));
let ptr = ptr::NonNull::<T>::dangling().as_ptr(); let ptr = ptr::NonNull::<T>::dangling().as_ptr();
// Don't drop the object. This `write` is equivalent to `forget`. // Don't drop the object. This `write` is equivalent to `forget`.
ptr::write(ptr, object); ptr::write(ptr, object);

View File

@ -4,7 +4,6 @@
use crate::raw_vec::RawVec; use crate::raw_vec::RawVec;
use core::array; use core::array;
use core::fmt; use core::fmt;
use core::intrinsics::arith_offset;
use core::iter::{ use core::iter::{
FusedIterator, InPlaceIterable, SourceIter, TrustedLen, TrustedRandomAccessNoCoerce, FusedIterator, InPlaceIterable, SourceIter, TrustedLen, TrustedRandomAccessNoCoerce,
}; };
@ -154,7 +153,7 @@ fn next(&mut self) -> Option<T> {
// purposefully don't use 'ptr.offset' because for // purposefully don't use 'ptr.offset' because for
// vectors with 0-size elements this would return the // vectors with 0-size elements this would return the
// same pointer. // same pointer.
self.ptr = unsafe { arith_offset(self.ptr as *const i8, 1) as *mut T }; self.ptr = self.ptr.wrapping_byte_add(1);
// Make up a value of this ZST. // Make up a value of this ZST.
Some(unsafe { mem::zeroed() }) Some(unsafe { mem::zeroed() })
@ -184,7 +183,7 @@ fn advance_by(&mut self, n: usize) -> Result<(), usize> {
// SAFETY: due to unchecked casts of unsigned amounts to signed offsets the wraparound // SAFETY: due to unchecked casts of unsigned amounts to signed offsets the wraparound
// effectively results in unsigned pointers representing positions 0..usize::MAX, // effectively results in unsigned pointers representing positions 0..usize::MAX,
// which is valid for ZSTs. // which is valid for ZSTs.
self.ptr = unsafe { arith_offset(self.ptr as *const i8, step_size as isize) as *mut T } self.ptr = self.ptr.wrapping_byte_add(step_size);
} else { } else {
// SAFETY: the min() above ensures that step_size is in bounds // SAFETY: the min() above ensures that step_size is in bounds
self.ptr = unsafe { self.ptr.add(step_size) }; self.ptr = unsafe { self.ptr.add(step_size) };
@ -217,7 +216,7 @@ fn count(self) -> usize {
return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) }); return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) });
} }
self.ptr = unsafe { arith_offset(self.ptr as *const i8, N as isize) as *mut T }; self.ptr = self.ptr.wrapping_byte_add(N);
// Safety: ditto // Safety: ditto
return Ok(unsafe { MaybeUninit::array_assume_init(raw_ary) }); return Ok(unsafe { MaybeUninit::array_assume_init(raw_ary) });
} }
@ -267,7 +266,7 @@ fn next_back(&mut self) -> Option<T> {
None None
} else if mem::size_of::<T>() == 0 { } else if mem::size_of::<T>() == 0 {
// See above for why 'ptr.offset' isn't used // See above for why 'ptr.offset' isn't used
self.end = unsafe { arith_offset(self.end as *const i8, -1) as *mut T }; self.end = self.ptr.wrapping_byte_sub(1);
// Make up a value of this ZST. // Make up a value of this ZST.
Some(unsafe { mem::zeroed() }) Some(unsafe { mem::zeroed() })
@ -283,9 +282,7 @@ fn advance_back_by(&mut self, n: usize) -> Result<(), usize> {
let step_size = self.len().min(n); let step_size = self.len().min(n);
if mem::size_of::<T>() == 0 { if mem::size_of::<T>() == 0 {
// SAFETY: same as for advance_by() // SAFETY: same as for advance_by()
self.end = unsafe { self.end = self.end.wrapping_byte_sub(step_size);
arith_offset(self.end as *const i8, step_size.wrapping_neg() as isize) as *mut T
}
} else { } else {
// SAFETY: same as for advance_by() // SAFETY: same as for advance_by()
self.end = unsafe { self.end.sub(step_size) }; self.end = unsafe { self.end.sub(step_size) };

View File

@ -59,7 +59,7 @@
use core::convert::TryFrom; use core::convert::TryFrom;
use core::fmt; use core::fmt;
use core::hash::{Hash, Hasher}; use core::hash::{Hash, Hasher};
use core::intrinsics::{arith_offset, assume}; use core::intrinsics::assume;
use core::iter; use core::iter;
#[cfg(not(no_global_oom_handling))] #[cfg(not(no_global_oom_handling))]
use core::iter::FromIterator; use core::iter::FromIterator;
@ -2678,7 +2678,7 @@ fn into_iter(self) -> IntoIter<T, A> {
let alloc = ManuallyDrop::new(ptr::read(me.allocator())); let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
let begin = me.as_mut_ptr(); let begin = me.as_mut_ptr();
let end = if mem::size_of::<T>() == 0 { let end = if mem::size_of::<T>() == 0 {
arith_offset(begin as *const i8, me.len() as isize) as *const T begin.wrapping_byte_add(me.len())
} else { } else {
begin.add(me.len()) as *const T begin.add(me.len()) as *const T
}; };

View File

@ -249,7 +249,7 @@ pub fn with_addr(self, addr: usize) -> Self
let offset = dest_addr.wrapping_sub(self_addr); let offset = dest_addr.wrapping_sub(self_addr);
// This is the canonical desugarring of this operation // This is the canonical desugarring of this operation
self.cast::<u8>().wrapping_offset(offset).cast::<T>() self.wrapping_byte_offset(offset)
} }
/// Creates a new pointer by mapping `self`'s address to a new one. /// Creates a new pointer by mapping `self`'s address to a new one.

View File

@ -255,7 +255,7 @@ pub fn with_addr(self, addr: usize) -> Self
let offset = dest_addr.wrapping_sub(self_addr); let offset = dest_addr.wrapping_sub(self_addr);
// This is the canonical desugarring of this operation // This is the canonical desugarring of this operation
self.cast::<u8>().wrapping_offset(offset).cast::<T>() self.wrapping_byte_offset(offset)
} }
/// Creates a new pointer by mapping `self`'s address to a new one. /// Creates a new pointer by mapping `self`'s address to a new one.

View File

@ -64,7 +64,7 @@ macro_rules! next_back_unchecked {
// backwards by `n`. `n` must not exceed `self.len()`. // backwards by `n`. `n` must not exceed `self.len()`.
macro_rules! zst_shrink { macro_rules! zst_shrink {
($self: ident, $n: ident) => { ($self: ident, $n: ident) => {
$self.end = ($self.end as * $raw_mut u8).wrapping_offset(-$n) as * $raw_mut T; $self.end = $self.end.wrapping_byte_offset(-$n);
} }
} }

View File

@ -155,7 +155,7 @@ fn ptr_add_data() {
assert_eq!(atom.fetch_ptr_sub(1, SeqCst), n.wrapping_add(1)); assert_eq!(atom.fetch_ptr_sub(1, SeqCst), n.wrapping_add(1));
assert_eq!(atom.load(SeqCst), n); assert_eq!(atom.load(SeqCst), n);
let bytes_from_n = |b| n.cast::<u8>().wrapping_add(b).cast::<i64>(); let bytes_from_n = |b| n.wrapping_byte_add(b);
assert_eq!(atom.fetch_byte_add(1, SeqCst), n); assert_eq!(atom.fetch_byte_add(1, SeqCst), n);
assert_eq!(atom.load(SeqCst), bytes_from_n(1)); assert_eq!(atom.load(SeqCst), bytes_from_n(1));

View File

@ -650,7 +650,7 @@ pub fn new<Value: std::marker::Unsize<T>>(value: Value) -> Self {
.unwrap_or_else(|| handle_alloc_error(layout)) .unwrap_or_else(|| handle_alloc_error(layout))
.cast::<DynMetadata<T>>(); .cast::<DynMetadata<T>>();
ptr.as_ptr().write(meta); ptr.as_ptr().write(meta);
ptr.cast::<u8>().as_ptr().add(offset).cast::<Value>().write(value); ptr.as_ptr().byte_add(offset).cast::<Value>().write(value);
Self { ptr, phantom: PhantomData } Self { ptr, phantom: PhantomData }
} }
} }

View File

@ -269,10 +269,10 @@ unsafe fn decode_repr<C, F>(ptr: NonNull<()>, make_custom: F) -> ErrorData<C>
} }
TAG_SIMPLE_MESSAGE => ErrorData::SimpleMessage(&*ptr.cast::<SimpleMessage>().as_ptr()), TAG_SIMPLE_MESSAGE => ErrorData::SimpleMessage(&*ptr.cast::<SimpleMessage>().as_ptr()),
TAG_CUSTOM => { TAG_CUSTOM => {
// It would be correct for us to use `ptr::sub` here (see the // It would be correct for us to use `ptr::byte_sub` here (see the
// comment above the `wrapping_add` call in `new_custom` for why), // comment above the `wrapping_add` call in `new_custom` for why),
// but it isn't clear that it makes a difference, so we don't. // but it isn't clear that it makes a difference, so we don't.
let custom = ptr.as_ptr().cast::<u8>().wrapping_sub(TAG_CUSTOM).cast::<Custom>(); let custom = ptr.as_ptr().wrapping_byte_sub(TAG_CUSTOM).cast::<Custom>();
ErrorData::Custom(make_custom(custom)) ErrorData::Custom(make_custom(custom))
} }
_ => { _ => {

View File

@ -296,6 +296,7 @@
#![feature(panic_can_unwind)] #![feature(panic_can_unwind)]
#![feature(panic_info_message)] #![feature(panic_info_message)]
#![feature(panic_internals)] #![feature(panic_internals)]
#![feature(pointer_byte_offsets)]
#![feature(pointer_is_aligned)] #![feature(pointer_is_aligned)]
#![feature(portable_simd)] #![feature(portable_simd)]
#![feature(prelude_2024)] #![feature(prelude_2024)]