Gnat - a typenum alternative better than `generic_const_exprs`

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

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 uses generic associated types to be more expressive than typenum and generic_const_exprs. Here is an example of the elusive generic array concat function:

#![feature(generic_const_exprs)]
const fn concat_arrays_gcex<T, const M: usize, const N: usize>(
    a: [T; M],
    b: [T; N],
) -> [T; M + N]
where
    [T; M + N]:, // well-formedness bound
{
    todo!()
}

use generic_array::{GenericArray, ArrayLength};
const fn concat_arrays_tnum<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!()
}

// Using this crate:
use gnat::{Nat, array::Arr};
const fn concat_arrays_gnat<T, M: Nat, N: Nat>(
    a: Arr<T, M>,
    b: Arr<T, N>,
) -> Arr<T, gnat::eval!(M + N)> { // no extra bounds!
    a.concat_arr(b).retype()
}

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