This crate provides abstractions for creating type witnesses.
The inciting motivation for this crate is emulating trait polymorphism in const fn
(as of 2023-04-30 it's not possible to call trait methods in const contexts on stable).
What are type witnesses
Type witnesses are enums that allow coercing between a type parameter and a range of possible types (one per variant).
The simplest type witness is TypeEq<L, R>,
which only allows coercing between L and R.
Most type witnesses are enums with TypeEq fields,
which can coerce between a type parameter and as many types as there are variants.
Examples
Polymorphic branching
This example demonstrates how type witnesses can be used to choose between expressions of different types with a constant.
use TypeEq;
const
/// Evaluates the argument at position `$chosen % 3`, other arguments aren't evaluated.
///
/// The arguments can all be different types.
///
/// `$chosen` must be a `u64` constant.
}
}
// This is a type witness
// Used to get different values of `Branch3` depending on `N`
Indexing polymorphism
This example demonstrates how one can emulate trait polymorphism in const fns
use Range;
use ;
const
/// Trait for all types that can be used as slice indices
// This is a type witness
//////
//////
//////
const
// This is a type-level function from `I` to `<I as SliceIndex<T>>::Returns`
>);
// What makes SliceIndexRets a type-level function
When the wrong type is passed for the index, the compile-time error is the same as with normal generic functions:
error[E0277]: the trait bound `RangeFull: SliceIndex<{integer}>` is not satisfied
--> src/main.rs:43:30
|
13 | assert_eq!(index(&array, ..), [13, 21]);
| ----- ^^ the trait `SliceIndex<{integer}>` is not implemented for `RangeFull`
| |
| required by a bound introduced by this call
|
= help: the following other types implement trait `SliceIndex<T>`:
std::ops::Range<usize>
usize
Cargo features
These are the features of this crates:
-
"alloc": enable items that use anything from the alloc crate. -
"mut_refs": turns functions that take mutable references into const fns. note: as of April 2023, this crate feature requires a stable compiler from the future. -
"nightly_mut_refs"(requires the nightly compiler): Enables the"mut_refs"crate feature and theconst_mut_refsnightly feature.
No-std support
typewit is #![no_std], it can be used anywhere Rust can be used.
Minimum Supported Rust Version
typewit requires Rust 1.57.0.
Features that require newer versions of Rust, or the nightly compiler, need to be explicitly enabled with crate features.