Make Slab::new const on Rust 1.39+

This commit is contained in:
Taiki Endo 2022-07-10 02:09:55 +09:00
parent 0732ab6c61
commit ad47e0ca6d
4 changed files with 54 additions and 2 deletions

View File

@ -21,9 +21,13 @@ exclude = ["/.*"]
std = []
default = ["std"]
[build-dependencies]
autocfg = "1"
[dependencies]
serde = { version = "1.0.95", optional = true, default-features = false, features = ["alloc"] }
[dev-dependencies]
rustversion = "1"
serde = { version = "1", features = ["derive"] }
serde_test = "1"

21
build.rs Normal file
View File

@ -0,0 +1,21 @@
fn main() {
let cfg = match autocfg::AutoCfg::new() {
Ok(cfg) => cfg,
Err(e) => {
// If we couldn't detect the compiler version and features, just
// print a warning. This isn't a fatal error: we can still build
// Tokio, we just can't enable cfgs automatically.
println!(
"cargo:warning=slab: failed to detect compiler features: {}",
e
);
return;
}
};
// Note that this is `no_`*, not `has_*`. This allows treating as the latest
// stable rustc is used when the build script doesn't run. This is useful
// for non-cargo build systems that don't run the build script.
if !cfg.probe_rustc_version(1, 39) {
println!("cargo:rustc-cfg=slab_no_const_vec_new");
}
}

View File

@ -219,14 +219,35 @@ impl<T> Slab<T> {
/// The function does not allocate and the returned slab will have no
/// capacity until `insert` is called or capacity is explicitly reserved.
///
/// This is `const fn` on Rust 1.39+.
///
/// # Examples
///
/// ```
/// # use slab::*;
/// let slab: Slab<i32> = Slab::new();
/// ```
pub fn new() -> Slab<T> {
Slab::with_capacity(0)
#[cfg(not(slab_no_const_vec_new))]
pub const fn new() -> Self {
Self {
entries: Vec::new(),
next: 0,
len: 0,
}
}
/// Construct a new, empty `Slab`.
///
/// The function does not allocate and the returned slab will have no
/// capacity until `insert` is called or capacity is explicitly reserved.
///
/// This is `const fn` on Rust 1.39+.
#[cfg(slab_no_const_vec_new)]
pub fn new() -> Self {
Self {
entries: Vec::new(),
next: 0,
len: 0,
}
}
/// Construct a new, empty `Slab` with the specified capacity.

View File

@ -696,3 +696,9 @@ fn try_remove() {
assert_eq!(slab.try_remove(key), None);
assert_eq!(slab.get(key), None);
}
#[rustversion::since(1.39)]
#[test]
fn const_new() {
static _SLAB: Slab<()> = Slab::new();
}