Skip to content

Commit c8cbd5c

Browse files
committed
Hoist IS_ZST check out of RawVecInner::from_*_in
1 parent e843f71 commit c8cbd5c

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

alloc/src/raw_vec.rs

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ struct Cap(usize);
4040

4141
impl Cap {
4242
const ZERO: Cap = unsafe { Cap(0) };
43+
44+
/// `Cap(cap)`, except if `T` is a ZST then `Cap::ZERO`.
45+
///
46+
/// # Safety: cap must be <= `isize::MAX`.
47+
unsafe fn new<T>(cap: usize) -> Self {
48+
if T::IS_ZST { Cap::ZERO } else { unsafe { Self(cap) } }
49+
}
4350
}
4451

4552
/// A low-level utility for more ergonomically allocating, reallocating, and deallocating
@@ -258,6 +265,8 @@ impl<T, A: Allocator> RawVec<T, A> {
258265
pub unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, alloc: A) -> Self {
259266
// SAFETY: Precondition passed to the caller
260267
unsafe {
268+
let ptr = ptr.cast();
269+
let capacity = Cap::new::<T>(capacity);
261270
Self {
262271
inner: RawVecInner::from_raw_parts_in(ptr, capacity, alloc),
263272
_marker: PhantomData,
@@ -274,6 +283,8 @@ impl<T, A: Allocator> RawVec<T, A> {
274283
pub unsafe fn from_nonnull_in(ptr: NonNull<T>, capacity: usize, alloc: A) -> Self {
275284
// SAFETY: Precondition passed to the caller
276285
unsafe {
286+
let ptr = ptr.cast();
287+
let capacity = Cap::new::<T>(capacity);
277288
Self { inner: RawVecInner::from_nonnull_in(ptr, capacity, alloc), _marker: PhantomData }
278289
}
279290
}
@@ -474,15 +485,13 @@ impl<A: Allocator> RawVecInner<A> {
474485
}
475486

476487
#[inline]
477-
unsafe fn from_raw_parts_in<T>(ptr: *mut T, capacity: usize, alloc: A) -> Self {
478-
let cap = if T::IS_ZST { Cap::ZERO } else { unsafe { Cap(capacity) } };
479-
Self { ptr: unsafe { Unique::new_unchecked(ptr.cast()) }, cap, alloc }
488+
unsafe fn from_raw_parts_in(ptr: *mut u8, cap: Cap, alloc: A) -> Self {
489+
Self { ptr: unsafe { Unique::new_unchecked(ptr) }, cap, alloc }
480490
}
481491

482492
#[inline]
483-
unsafe fn from_nonnull_in<T>(ptr: NonNull<T>, capacity: usize, alloc: A) -> Self {
484-
let cap = if T::IS_ZST { Cap::ZERO } else { unsafe { Cap(capacity) } };
485-
Self { ptr: Unique::from(ptr.cast()), cap, alloc }
493+
unsafe fn from_nonnull_in(ptr: NonNull<u8>, cap: Cap, alloc: A) -> Self {
494+
Self { ptr: Unique::from(ptr), cap, alloc }
486495
}
487496

488497
#[inline]

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy