more alignment fun

This commit is contained in:
nora 2021-12-21 12:16:12 +01:00
parent c49c716c9a
commit e9965ca40f
2 changed files with 32 additions and 6 deletions

View file

@ -107,7 +107,7 @@ impl<T: ?Sized> Vechonk<T> {
// SAFETY: capacity has been checked to not be 0 and the len is 0
unsafe {
vechonk.grow_to(NonZeroUsize::new_unchecked(capacity));
vechonk.realloc(NonZeroUsize::new_unchecked(capacity));
}
vechonk
}
@ -238,7 +238,7 @@ impl<T: ?Sized> Vechonk<T> {
// SAFETY: new_cap can't be 0 because of the +1
// We will copy the elements over
unsafe {
self.grow_to(NonZeroUsize::new_unchecked(new_cap));
self.realloc(NonZeroUsize::new_unchecked(new_cap));
}
// copy the elements first
@ -266,15 +266,15 @@ impl<T: ?Sized> Vechonk<T> {
}
}
/// Grows the `Vechonk` to a new capacity. This will not copy any elements. This will put the `Vechonk`
/// into an invalid state, since the `len` is still the length of the old allocation.
/// Reallocs the `Vechonk`, setting its capacity to `size`. This will not copy any elements. This will put the `Vechonk`
/// into an invalid state, since the `len` is still the length of the elements in the old allocation.
///
/// This doesn't free any memory
///
/// # Safety
/// The caller must either set the `len` to zero, or copy the elements to the new allocation by saving
/// `self.ptr` before calling this function.
unsafe fn grow_to(&mut self, size: NonZeroUsize) {
unsafe fn realloc(&mut self, size: NonZeroUsize) {
let layout = Layout::from_size_align(size.get(), Self::data_align()).unwrap();
// SAFETY: layout is guaranteed to have a non-zero size

View file

@ -3,6 +3,9 @@
use crate::Vechonk;
use alloc::boxed::Box;
#[repr(align(2048))]
struct BigAlign(u8);
#[test]
fn new() {
let chonk = Vechonk::<()>::new();
@ -128,11 +131,34 @@ fn grow_from_alloc() {
fn push_alignment() {
use core::any::Any;
let mut chonk = Vechonk::<dyn Any>::with_capacity(96);
let mut chonk = Vechonk::<dyn Any>::with_capacity(4096);
chonk.push(Box::new(0_u8));
chonk.push(Box::new(BigAlign(5)));
chonk.push(Box::new(1_u64));
let _ = chonk[0];
let _ = chonk[1];
}
#[test]
fn grow_alignment() {
use core::any::Any;
let mut chonk = Vechonk::<dyn Any>::with_capacity(32);
chonk.push(Box::new(0_u8));
chonk.push(Box::new(1_u64));
chonk.push(Box::new(0_u128));
chonk.push(Box::new(BigAlign(5)));
chonk.push(Box::new(8_u128));
chonk.push(Box::new("dsajkfhdsajklfdsklaöfjdklsöjfkldsfjlkds"));
chonk.push(Box::new(4_u128));
chonk.push(Box::new(5_u128));
chonk.push(Box::new(BigAlign(5)));
chonk.push(Box::new(6_u128));
chonk.push(Box::new(3_u128));
let _ = chonk[0];
let _ = chonk[1];
}