Skip to content

Commit

Permalink
Add test for const MaybeUninit
Browse files Browse the repository at this point in the history
  • Loading branch information
jhpratt committed Nov 28, 2021
1 parent ad8e6bf commit 44b5b83
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions library/core/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
32 changes: 32 additions & 0 deletions library/core/tests/mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
}

0 comments on commit 44b5b83

Please sign in to comment.