add more tests

This commit is contained in:
2026-07-26 14:41:22 +02:00
parent f6a1132023
commit 0a8bad4d21
2 changed files with 88 additions and 2 deletions
+10 -2
View File
@@ -85,8 +85,6 @@ impl TypeErasedVec {
/// # Safety
/// The caller must ensure that the existing elements can be safely transmuted
/// into the new type `T` and that dropping them as `T` is sound.
///
/// The `Layout` of the new type `T` does not match the `Layout` of the allocated capacity
pub unsafe fn cast_type<T>(&mut self) -> ContentGuard<'_, T> {
debug_assert_eq!(self.layout, Layout::new::<T>());
@@ -168,6 +166,16 @@ impl TypeErasedVec {
self.as_type::<T>().take()
}
/// Convert the capacity of the erased `Vec` into a `Vec<T>`.
///
/// # Safety
/// The caller must ensure that the existing elements can be safely transmuted
/// into the new type `T` and that dropping them as `T` is sound.
#[must_use]
pub unsafe fn cast_into_vec<T>(mut self) -> Vec<T> {
unsafe { self.cast_type::<T>() }.take()
}
/// Convert the capacity of the erased `Vec` into a `Vec<T>`.
///
/// # Safety
+78
View File
@@ -290,3 +290,81 @@ fn test_drop_cleans_up_allocation() {
assert_eq!(drop_count.get(), 1);
}
#[test]
fn test_guard_into_slice() {
let mut vec = Vec::<i32>::new();
vec.push(1);
vec.push(2);
let mut erased = TypeErasedVec::new(vec);
let guard = unsafe { erased.cast_type::<i32>() };
let slice = guard.into_slice();
assert_eq!(slice, &[1, 2]);
}
#[test]
fn test_guard_into_slice_mut() {
let mut vec = Vec::<i32>::new();
vec.push(1);
vec.push(2);
let mut erased = TypeErasedVec::new(vec);
let guard = unsafe { erased.cast_type::<i32>() };
let slice = guard.into_slice_mut();
slice[0] = 99;
assert_eq!(slice, &[99, 2]);
}
#[test]
fn test_guard_push() {
let vec = Vec::<i32>::new();
let mut erased = TypeErasedVec::new(vec);
let mut guard = erased.as_type::<i32>();
guard.push(42);
assert_eq!(guard.length(), 1);
assert_eq!(guard.as_slice(), &[42]);
}
#[test]
fn test_erased_layout_and_capacity_bytes() {
let vec = Vec::<u64>::with_capacity(8);
let erased = TypeErasedVec::new(vec);
assert_eq!(erased.layout(), Layout::new::<u64>());
assert_eq!(erased.capacity_bytes(), erased.capacity() * 8);
}
#[test]
fn test_unchecked_methods() {
let mut vec = Vec::<u32>::new();
vec.push(123);
let mut erased = TypeErasedVec::new(vec);
let mut guard = unsafe { erased.cast_type::<u32>() };
assert_eq!(guard.as_slice(), &[123]);
let restored = guard.take();
assert_eq!(restored, vec![123]);
let vec2 = Vec::<u32>::new();
let erased2 = TypeErasedVec::new(vec2);
let restored2 = unsafe { erased2.into_vec_unchecked::<u32>() };
assert!(restored2.is_empty());
}
#[test]
fn test_multiple_compatible_type_casts() {
let mut vec = Vec::<i32>::new();
vec.push(-1);
let mut erased = TypeErasedVec::new(vec);
{
let mut guard = unsafe { erased.cast_type::<u32>() };
assert_eq!(guard.as_slice(), &[u32::MAX]);
guard.push(42);
}
let restored = unsafe { erased.cast_into_vec::<i32>() };
assert_eq!(restored, vec![-1, 42]);
}