FEAT: Implement a "MaybeUninit" and use it conditionally

Use a build script to detect if we can use MaybeUninit or NoDrop.
Enabling unstable features automatically is not ideal, but since it's
a soundness issue we should do it.

Use a MaybeUninit-like union on nightly when we can. We use a feature
detection script in build.rs, so that we also go back to the fallback if
the unstable feature changes in an unexpected way.

We need to continue to use NoDrop for best working stable
implementation, but we eagerly use our union solution where we can,
currently only in nightlies.

Rustc feature probe code written by Josh Stone (cuviper),
taken from num-bigint.
This commit is contained in:
bluss
2018-03-25 22:28:33 +02:00
parent 8f8617b967
commit 29012231a8
5 changed files with 194 additions and 21 deletions
+79
View File
@@ -0,0 +1,79 @@
use std::env;
use std::io::Write;
use std::process::{Command, Stdio};
fn main() {
// we need to output *some* file to opt out of the default
println!("cargo:rerun-if-changed=build.rs");
detect_maybe_uninit();
}
fn detect_maybe_uninit() {
let has_unstable_union_with_md = probe(&maybe_uninit_code(true));
if has_unstable_union_with_md {
println!("cargo:rustc-cfg=has_manually_drop_in_union");
println!("cargo:rustc-cfg=has_union_feature");
return;
}
let has_stable_union_with_md = probe(&maybe_uninit_code(false));
if has_stable_union_with_md {
println!("cargo:rustc-cfg=has_manually_drop_in_union");
}
}
// To guard against changes in this currently unstable feature, use
// a detection tests instead of a Rustc version and/or date test.
fn maybe_uninit_code(use_feature: bool) -> String {
let feature = if use_feature { "#![feature(untagged_unions)]" } else { "" };
let code = "
#![allow(warnings)]
use std::mem::ManuallyDrop;
#[derive(Copy)]
pub union MaybeUninit<T> {
empty: (),
value: ManuallyDrop<T>,
}
impl<T> Clone for MaybeUninit<T> where T: Copy
{
fn clone(&self) -> Self { *self }
}
fn main() {
let value1 = MaybeUninit::<[i32; 3]> { empty: () };
let value2 = MaybeUninit { value: ManuallyDrop::new([1, 2, 3]) };
}
";
[feature, code].concat()
}
/// Test if a code snippet can be compiled
fn probe(code: &str) -> bool {
let rustc = env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());
let out_dir = env::var_os("OUT_DIR").expect("environment variable OUT_DIR");
let mut child = Command::new(rustc)
.arg("--out-dir")
.arg(out_dir)
.arg("--emit=obj")
.arg("-")
.stdin(Stdio::piped())
.spawn()
.expect("rustc probe");
child
.stdin
.as_mut()
.expect("rustc stdin")
.write_all(code.as_bytes())
.expect("write rustc stdin");
child.wait().expect("rustc probe").success()
}