Const-time checked numeric conversions?

⚓ Rust    📅 2025-07-08    👤 surdeus    👁️ 2      

surdeus

Currently I use a utility module I wrote that has a lot of functions like this:

#[cfg(target_pointer_width = "64")]
pub const fn u32_to_usize<const N: u32>() -> usize {
    N as usize
}

#[cfg(target_pointer_width = "64")]
pub const fn usize_to_u32<const N: usize>() -> u32 {
    const { assert!(N <= u32::MAX as usize) };
    N as u32
}

Primarily for use in const asserts, e.g.

pub fn has_changed<const I: u8>(&self, previous: u32) -> bool {
    const { assert!(u8_to_usize::<I>() < N) };
    self.history[u8_to_usize::<I>()] >= previous
}

(This is a slightly contrived example, so while I could simply make INDEX a usize here, I can't always in my actual code. :slightly_smiling_face:)

Is there anything better that's built-in that I could use? Or any crates that do this already? I'm specifically trying to avoid just plain as outside of these verified functions so that the conversions are compile-time checked, and Into or TryInto etc. are traits so their conversions can't be const (yet :crossed_fingers:).

1 post - 1 participant

Read full topic

🏷️ rust_feed