condtype
Choose Rust types at compile-time via boolean constants, brought to you by Nikolai Vazquez.
If you find this crate useful, consider starring it as well as sponsoring or donating once. 💖
Conditional Typing
The CondType type and condval! macro choose types at compile-time using
bool constants, just like std::conditional_t in C++.
Unlike Either, the chosen type is directly used, rather than wrapping it
with an enum type. This may be considered a form of dependent typing,
but it is limited in ability and is restricted to compile-time constants rather
than runtime values.
Examples
In the following example, CondType aliases &str or i32:
use CondType;
let str: = "hello";
let int: = 42;
// Unsized types are also supported:
let str: & = "world";
condval! enables choosing differently-typed values without specifying types.
In the following example, val is inferred to be either &str or i32,
depending on COND.
use condval;
const COND: bool = true;
let val = condval!;
This crate also enables making code for some platforms more efficient by using
smaller-sized types depending on platform-specific constants. In the following
example, the RlimOption type can either be Option<rlim_t> or rlim_t
itself, where rlim_t::MAX can be treated as a sentinel value for
Option::None.
use ;
use ;
const RLIM_INFINITY_IS_MAX: bool = RLIM_INFINITY == rlim_tMAX;
type RlimOption = ;
const RLIM_NONE: RlimOption = condval!;
// Convert from either `RlimOption` type to `Option` via the `Into` trait:
let rlim_none: = RLIM_NONE.into;
Without this crate, one could otherwise use cfg_if! to achieve the same
goal. However, using #[cfg] requires maintaining a list of platforms
and being more fine-grained if RLIM_INFINITY is dependent on CPU architecture.
use cfg_if;
use rlim_t;
cfg_if!
Limitations
It is currently not possible to use CondType or condval! with a generic
constant because Rust does not yet consider trait implementations based on
booleans to be exhaustive.
Once that issue is resolved, all versions of this crate should just work with
generic constants.
Install
This crate is available on crates.io and can be
used by running the following cargo command in your project directory:
or by manually adding the following to your project's Cargo.toml:
[]
= "1.1.0"
License
Like the Rust project, this library may be used under either the MIT License or Apache License (Version 2.0).