Skip to content

Commit 697a9e4

Browse files
committed
vec_recycle: implementation
1 parent 6a884ad commit 697a9e4

File tree

2 files changed

+88
-1
lines changed

2 files changed

+88
-1
lines changed

library/alloc/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@
144144
#![feature(std_internals)]
145145
#![feature(str_internals)]
146146
#![feature(temporary_niche_types)]
147+
#![feature(transmutability)]
147148
#![feature(trusted_fused)]
148149
#![feature(trusted_len)]
149150
#![feature(trusted_random_access)]

library/alloc/src/vec/mod.rs

Lines changed: 87 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ use core::hash::{Hash, Hasher};
8080
#[cfg(not(no_global_oom_handling))]
8181
use core::iter;
8282
use core::marker::PhantomData;
83-
use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties};
83+
use core::mem::{self, Assume, ManuallyDrop, MaybeUninit, SizedTypeProperties, TransmuteFrom};
8484
use core::ops::{self, Index, IndexMut, Range, RangeBounds};
8585
use core::ptr::{self, NonNull};
8686
use core::slice::{self, SliceIndex};
@@ -3259,6 +3259,92 @@ impl<T, A: Allocator> Vec<T, A> {
32593259
// - `cap / N` fits the size of the allocated memory after shrinking
32603260
unsafe { Vec::from_raw_parts_in(ptr.cast(), len / N, cap / N, alloc) }
32613261
}
3262+
3263+
/// This clears out this `Vec` and recycles the allocation into a new `Vec`.
3264+
/// The item type of the resulting `Vec` needs to have the same size and
3265+
/// alignment as the item type of the original `Vec`.
3266+
///
3267+
/// # Examples
3268+
///
3269+
/// ```
3270+
/// #![feature(vec_recycle, transmutability)]
3271+
/// let a: Vec<u8> = vec![0; 100];
3272+
/// let capacity = a.capacity();
3273+
/// let addr = a.as_ptr().addr();
3274+
/// let b: Vec<i8> = a.recycle();
3275+
/// assert_eq!(b.len(), 0);
3276+
/// assert_eq!(b.capacity(), capacity);
3277+
/// assert_eq!(b.as_ptr().addr(), addr);
3278+
/// ```
3279+
///
3280+
/// The `Recyclable` bound prevents this method from being called when `T` and `U` have different sizes; e.g.:
3281+
///
3282+
/// ```compile_fail,E0277
3283+
/// #![feature(vec_recycle, transmutability)]
3284+
/// let vec: Vec<[u8; 2]> = Vec::new();
3285+
/// let _: Vec<[u8; 1]> = vec.recycle();
3286+
/// ```
3287+
/// ...or different alignments:
3288+
///
3289+
/// ```compile_fail,E0277
3290+
/// #![feature(vec_recycle, transmutability)]
3291+
/// let vec: Vec<[u16; 0]> = Vec::new();
3292+
/// let _: Vec<[u8; 0]> = vec.recycle();
3293+
/// ```
3294+
///
3295+
/// However, due to temporary implementation limitations of `Recyclable`,
3296+
/// this method is not yet callable when `T` or `U` are slices, trait objects,
3297+
/// or other exotic types; e.g.:
3298+
///
3299+
/// ```compile_fail,E0277
3300+
/// #![feature(vec_recycle, transmutability)]
3301+
/// # let inputs = ["a b c", "d e f"];
3302+
/// # fn process(_: &[&str]) {}
3303+
/// let mut storage: Vec<&[&str]> = Vec::new();
3304+
///
3305+
/// for input in inputs {
3306+
/// let mut buffer: Vec<&str> = storage.recycle();
3307+
/// buffer.extend(input.split(" "));
3308+
/// process(&buffer);
3309+
/// storage = buffer.recycle();
3310+
/// }
3311+
/// ```
3312+
#[unstable(feature = "vec_recycle", issue = "148227")]
3313+
#[expect(private_bounds)]
3314+
pub fn recycle<U>(mut self) -> Vec<U, A>
3315+
where
3316+
U: Recyclable<T>,
3317+
{
3318+
self.clear();
3319+
const {
3320+
// FIXME(const-hack, 146097): compare `Layout`s
3321+
assert!(size_of::<T>() == size_of::<U>());
3322+
assert!(align_of::<T>() == align_of::<U>());
3323+
};
3324+
let (ptr, length, capacity, alloc) = self.into_parts_with_alloc();
3325+
debug_assert_eq!(length, 0);
3326+
// SAFETY:
3327+
// - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_alloc()`
3328+
// - `T` & `U` have the same layout, so `capacity` does not need to be changed and we can safely use `alloc.dealloc` later
3329+
// - the original vector was cleared, so there is no problem with "transmuting" the stored values
3330+
unsafe { Vec::from_parts_in(ptr.cast::<U>(), length, capacity, alloc) }
3331+
}
3332+
}
3333+
3334+
/// Denotes that an allocation of `From` can be recycled into an allocation of `Self`.
3335+
///
3336+
/// # Safety
3337+
///
3338+
/// `Self` is `Recyclable<From>` if `Layout::new::<Self>() == Layout::new::<From>()`.
3339+
unsafe trait Recyclable<From: Sized>: Sized {}
3340+
3341+
#[unstable_feature_bound(transmutability)]
3342+
// SAFETY: enforced by `TransmuteFrom`
3343+
unsafe impl<From, To> Recyclable<From> for To
3344+
where
3345+
for<'a> &'a MaybeUninit<To>: TransmuteFrom<&'a MaybeUninit<From>, { Assume::SAFETY }>,
3346+
for<'a> &'a MaybeUninit<From>: TransmuteFrom<&'a MaybeUninit<To>, { Assume::SAFETY }>,
3347+
{
32623348
}
32633349

32643350
impl<T: Clone, A: Allocator> Vec<T, A> {

0 commit comments

Comments
 (0)