Add test for const MaybeUninit

This commit is contained in:
Jacob Pratt 2021-11-16 19:58:52 -05:00
parent ad8e6bf5cc
commit 44b5b838d2
No known key found for this signature in database
GPG Key ID: B80E19E4662B5AA4
2 changed files with 33 additions and 0 deletions

View File

@ -10,6 +10,7 @@
#![feature(const_assume)]
#![feature(const_cell_into_inner)]
#![feature(const_convert)]
#![feature(const_maybe_uninit_as_mut_ptr)]
#![feature(const_maybe_uninit_assume_init)]
#![feature(const_ptr_read)]
#![feature(const_ptr_write)]

View File

@ -269,3 +269,35 @@ fn uninit_const_assume_init_read() {
const FOO: u32 = unsafe { MaybeUninit::new(42).assume_init_read() };
assert_eq!(FOO, 42);
}
#[test]
fn const_maybe_uninit() {
use std::ptr;
#[derive(Debug, PartialEq)]
struct Foo {
x: u8,
y: u8,
}
const FIELD_BY_FIELD: Foo = unsafe {
let mut val = MaybeUninit::uninit();
init_y(&mut val); // order shouldn't matter
init_x(&mut val);
val.assume_init()
};
const fn init_x(foo: &mut MaybeUninit<Foo>) {
unsafe {
*ptr::addr_of_mut!((*foo.as_mut_ptr()).x) = 1;
}
}
const fn init_y(foo: &mut MaybeUninit<Foo>) {
unsafe {
*ptr::addr_of_mut!((*foo.as_mut_ptr()).y) = 2;
}
}
assert_eq!(FIELD_BY_FIELD, Foo { x: 1, y: 2 });
}