A generic integer type for consts?

This idea is mainly motivated by creating bindings. Ideally, I wouldn't have to manually modify files created by bindgen. Though, the problem is that when bindgen comes across a #define FLAG 2 for example, the rust translation gets i32 as its type.

However, the functions that use those flags aren't guaranteed to accept i32s. In my case, they happen to accept i16s.

Perhaps, we could have a generic integer type, restricted to consts? Something like:

const FLAG: {integer} = 2;

Though, the simplest solution would be just putting a as i16 at the end. Honestly, I'm not even sure if this idea is worthwhile. Just putting this out there to get the people who are smarter than me's opinions :P.

1 Like

One thing I've wanted for a while is a compile-time-only BigInteger type. It'd be convenient in various places, especially const generics where sometimes there's no one right type for a value, or in custom literals where it'd be nice to have takes_nonzero(3) work.

Then you could have types like IntegerLiteral<2> (and IntegerLiteral<847637503530476925760294567024753948730945672879264550319546353972>) for cases like this.

4 Likes

One possibility is generic consts à la C++:

const FLAG<I: From<u8>>: I = I::from(2);

fn foo(a: u16) {}
fn bar(b: i32) {}

foo(FLAG); // FLAG::<u16>
bar(FLAG); // FLAG::<i32>

(assuming const traits, of course.)

And for someone like me who wants ranged integers, compile-time-only bigints are realistically the only solution to what the generic type should be. It would be very useful in a number of situations. I'm unsure how difficult it would be to implement, however.

1 Like

Previous discussions about such things include:

1 Like