rust/library/alloc/tests/boxed.rs

60 lines
1.7 KiB
Rust
Raw Normal View History

use std::cell::Cell;
use std::mem::MaybeUninit;
2019-11-29 21:30:49 -06:00
use std::ptr::NonNull;
#[test]
fn unitialized_zero_size_box() {
assert_eq!(
&*Box::<()>::new_uninit() as *const _,
NonNull::<MaybeUninit<()>>::dangling().as_ptr(),
);
assert_eq!(
Box::<[()]>::new_uninit_slice(4).as_ptr(),
NonNull::<MaybeUninit<()>>::dangling().as_ptr(),
);
assert_eq!(
Box::<[String]>::new_uninit_slice(0).as_ptr(),
NonNull::<MaybeUninit<String>>::dangling().as_ptr(),
);
}
2020-05-23 10:51:02 -05:00
#[derive(Clone, PartialEq, Eq, Debug)]
struct Dummy {
_data: u8,
}
#[test]
fn box_clone_and_clone_from_equivalence() {
for size in (0..8).map(|i| 2usize.pow(i)) {
let control = vec![Dummy { _data: 42 }; size].into_boxed_slice();
let clone = control.clone();
let mut copy = vec![Dummy { _data: 84 }; size].into_boxed_slice();
copy.clone_from(&control);
assert_eq!(control, clone);
assert_eq!(control, copy);
}
}
/// This test might give a false positive in case the box realocates, but the alocator keeps the
/// original pointer.
///
2020-08-02 10:20:00 -05:00
/// On the other hand it won't give a false negative, if it fails than the memory was definitely not
/// reused
2020-05-23 10:51:02 -05:00
#[test]
fn box_clone_from_ptr_stability() {
for size in (0..8).map(|i| 2usize.pow(i)) {
let control = vec![Dummy { _data: 42 }; size].into_boxed_slice();
let mut copy = vec![Dummy { _data: 84 }; size].into_boxed_slice();
let copy_raw = copy.as_ptr() as usize;
copy.clone_from(&control);
assert_eq!(copy.as_ptr() as usize, copy_raw);
}
}
2020-09-08 16:38:23 -05:00
#[test]
fn box_deref_lval() {
let x = Box::new(Cell::new(5));
x.set(1000);
assert_eq!(x.get(), 1000);
}