#macros #attribute #const #static

macro no-std const_fn

An attribute for easy generation of const functions with conditional compilations

19 releases

0.4.7 Apr 17, 2021
0.4.6 Mar 27, 2021
0.4.5 Jan 5, 2021
0.4.4 Dec 9, 2020
0.1.2 Dec 27, 2018

#1030 in Rust patterns

Download history 208206/week @ 2021-01-17 229087/week @ 2021-01-24 233493/week @ 2021-01-31 235795/week @ 2021-02-07 247041/week @ 2021-02-14 185176/week @ 2021-02-21 179532/week @ 2021-02-28 172046/week @ 2021-03-07 175875/week @ 2021-03-14 174236/week @ 2021-03-21 169082/week @ 2021-03-28 164941/week @ 2021-04-04 173593/week @ 2021-04-11 171711/week @ 2021-04-18 175993/week @ 2021-04-25 143579/week @ 2021-05-02

842,932 downloads per month
Used in 1,354 crates (6 directly)

Apache-2.0 OR MIT

26KB
519 lines

#[const_fn]

crates.io docs.rs license rustc build status

An attribute for easy generation of const functions with conditional compilations.

Usage

Add this to your Cargo.toml:

[dependencies]
const_fn = "0.4"

Compiler support: requires rustc 1.31+

Examples

use const_fn::const_fn;

// function is `const` on specified version and later compiler (including beta, nightly, and dev build)
#[const_fn("1.36")]
pub const fn version() {
    /* ... */
}

// function is `const` on nightly compiler (including dev build)
#[const_fn(nightly)]
pub const fn nightly() {
    /* ... */
}

// function is `const` if `cfg(...)` is true
#[const_fn(cfg(...))]
pub const fn cfg() {
    /* ... */
}

// function is `const` if `cfg(feature = "...")` is true
#[const_fn(feature = "...")]
pub const fn feature() {
    /* ... */
}

Use this crate as an optional dependency

If no arguments are passed, consf_fn will always make the function const.

Therefore, you can use const_fn as an optional dependency by combination with cfg_attr.

// function is `const` if `cfg(feature = "...")` is true
#[cfg_attr(feature = "...", const_fn::const_fn)]
pub fn optional() {
    /* ... */
}

Alternatives

This crate is proc-macro, but is very lightweight, and has no dependencies.

You can manually define declarative macros with similar functionality (see if_rust_version), or you can define the same function twice with different cfg. (Note: the former approach requires more macros to be defined depending on the number of version requirements, the latter approach requires more functions to be maintained manually)

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps