Pre-RFC: Add explicitly-named numeric conversion APIs

One thing that is missing from both the current and proposed APIs is a way to do ergonomic casts that panic on out of bounds / overflow. Yes, I can litter my code with unwrap() calls, but there is a reason that Vec supports indexing rather than requiring get().unwrap() calls everywhere: the common option should ideally have the most concise syntax. This absence is especially annoying for u64 <--> usize conversions since in many cases realistically my code is never going to run on anything other than a 64-bit machine, yet I still have to spend mental cycles thinking about it.

That is not how .ceil() , .floor() and .truc() work, they are exactly what you are asking for. I have seen the names misused in the way you described (old versions of Excel), but most programing language (including Rust) follow their mathematical definition.

There is no equivalent for f64 to f32, but I don't see any use them. If someone can provide a good use then we can consider add them in the future.

2 Likes

Prior art:

That RFC proposed what this RFC proposes, basically, and was rejected because library team wanted to try to do it with a trait first (TryFrom).

Differences:

  • cast was used instead of to (wrapping_to -> wrapping_cast).
  • The Option-returning operation followed the analogy with arithmetic operations too (checked_add -> checked_cast, not try_into).
  • The RFC also introduced a simple cast operation that panicked on failure, like simple arithmetic operations (add -> cast).
  • Conversions involving floats weren't considered.

(I still think that RFC did everything right :p)

5 Likes

I would personally really like to see a better casting method for integers. right now you can't to u32->usize or usize->u32 safely. there should be a way to do this conversion with compile time safety (I don't want my code to compile if this can't be done safely).

2 Likes

I suppose would could have modules with names like at_least_32bit in core::arch and std::arch that only exist for corresponding targets. But I think this is unique enough that it deserves to be proposed in its own RFC. So I’m not planning to integrate that idea in this proposal, but feel free to pursue it separately!

In the meantime, consider making your own library (or module) with cfg like this:

#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
pub fn u32_to_usize(x: u32) -> usize {
    x as _
}

With a 16-bit target this function won’t exist, so calling it would cause a compilation error.

2 Likes

Such proposals were deferred before, because Rust is getting portability lints. Once they're implemented, this could be a regular From impl.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.