ctoption
A compile-time option type for Rust with the discriminant elevated to compile time.
Add to your project
cargo add ctoption
Usage
Creating and using CTSome and CTNone
use *;
// enforcing constant evaluation
const _: = ;
Inserting values into a CTNone and extracting them from a CTSome
use *;
// enforcing constant evaluation
const _: = ;
Limitations
const drop
At the moment of writing, const_destruct feature of Rust is unstable. This means that CTSome and CTNone cannot be dropped in a const context.
However,
CTSomecan be disposed of by callingCTSome::into_inner,CTNonecan be disposed of by callingCTNone::forget.
.map-like methods
At the moment of writing, methods like std::option::Option::map cannot be implemented for CTSome and CTNone because they require a closure to be passed to them. Closures cannot be evaluated in const contexts. And the attempts to provide a sealed trait with an implementation for a function pointer failed because implementing a trait that would allow using it in a const context is impossible at the time of writing.
Type narrowing
At the moment of writing, matching on IS_SOME_VAL for CTOption<T, IS_SOME_VAL: bool does not narrow the type to CTSome<T> or CTNone<T>.
However, you can manually narrow the type using the unsafe methods
CTOption::assume_some and CTOption::assume_none:
use *;
const
const _: = ;
Additionally, since Rust's compiler can't infer after checking IS_SOME_VAL in const context that, for example, CTOption<T, IS_SOME_VAL> is the same as CTSome<T>, you may be in a situation where
- you have
CTSome<T>, - the check in const context inferred that
IS_SOME_VAListrue, - you need to return
CTOption<T, IS_SOME_VAL>
and be confused why returning CTSome<T> doesn't work.
To resolve this, you can use, CTSome::assume_const_generic_val or CTNone::assume_const_generic_val.
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.