Hacker News new | past | comments | ask | show | jobs | submit login

How does the lack of integer size promotion make it easier to overflow? I don't follow.



I want to convert between types without precision loss, but Rust has only option of no conversion at all, or a bug-prone conversion allowing precision loss.

The problem is that `x as usize` will compile without warnings to something I didn't intend and causes bugs if usize is smaller than the type of `x`.

AFAIK I can't avoid casts to `usize` any other way than using `usize` for almost every integer type in Rust. To make things worse my main use case for Rust is interfacing with C code, which means I have to deal with other types as often as `usize` and end up with these risky casts in almost every expression! It's awful.

What I'd prefer is something (it could be another operator, but I'd prefer promotion to keep syntactical noise low) that would either compile if typeof(x) <= usize, or would not compile at all (i.e. if I write code that is accidentally 64-bit only, I want it to fail to compile on 32-bit machine, instead of merrily compiling to something that is buggy and will corrupt the data or even be exploitable through FFI which requires these casts that become unsafe).


Couldn't you write that operator yourself?

    #[cfg(target_word_size="32")]
    struct ThisCastIsUnsafeFixIt;
    #[cfg(target_word_size="32")]
    const u64_to_usize: ThisCastIsUnsafeFixIt = ThisCastIsUnsafeFixIt;
    #[cfg(target_word_size="64")]
    fn u64_to_usize(x: u64) -> usize { x }
    
    ...
    
    u64_to_usize(123) // won't compile on 32-bit
If "u64_to_usize" is too long of a name for you, then you should be able to do the same thing with a trait instead.


> Couldn't you write that operator yourself?

I guess I could (thanks for the tip - I didn't know about this cfg(), I've been trying with traits and sizeof::<>).

But I'd prefer it to be in the language:

• lossless integer type conversion seems like a very basic problem to me, that shouldn't need programmers to fix it themselves in a custom way in every crate.

• even if I fix it in my code, I'm still worried about other people's code, because I assume that they also develop on x64 and unintentionally write casts that are subtly broken on smaller architectures.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: