Gnat - a typenum alternative equivalent to generic_const_exprs

⚓ Rust    📅 2026-04-03    👤 surdeus    👁️ 1      

surdeus

Hey,

I've been writing this on the side for over a year now and am happy to finally release my crate gnat. It is to generic_const_exprs what typenum was to min_const_generics: It allows using types instead of const generics, but unlike typenum, does not require any extra bounds to use operations on type numbers (powered by generic associated types). Here is an example of the elusive generic array concat function:

// Ideal function, using #![feature(generic_const_expr)]
const fn concat_arrays_gce<T, const M: usize, const N: usize>(
    a: [T; M],
    b: [T; N],
) -> [T; M + N] {
    todo!()
}

// typenum + generic-array implementation
use generic_array::{GenericArray, ArrayLength};
const fn concat_arrays_gar<T, M: ArrayLength, N: ArrayLength>(
    a: GenericArray<T, M>,
    b: GenericArray<T, N>,
) -> GenericArray<T, typenum::op!(M + N)>
where // ArrayLength is not enough, we also need to add a bound for `+`
    M: std::ops::Add<N, Output: ArrayLength>,
{
    todo!()
}

// gnat implementation
use gnat::{Nat, array::Arr};
const fn concat_arrays_nat<T, M: Nat, N: Nat>(
    a: Arr<T, M>,
    b: Arr<T, N>,
) -> Arr<T, gnat::eval!(M + N)> {
    a.concat_arr(b).retype()
}

As you can see, the only bound that is required is Nat, which specifies that the types are numbers. You can implement your own operations in a way that also does not require bounds, using bit-level operations, conditionals and recursion (which is also how Add is implemented). This can be used to implement any computable function, as it is turing-complete!

Disclaimer: Many compilers were harmed in the making of this library. ^^

1 post - 1 participant

Read full topic

🏷️ Rust_feed