I64 <-> u64 mapping, revisited

When I wanted to find The Best Way(tm) to map u64 to i64 and then back to u64, I found this thread, which indicates that as can be used for 1-to-1 bit mappings of same-size integers.

Today someone linked a thread about as-for-lossy-casts deprecation, which indicates that as may be deprecated for such use-cases in the future.

Is there a way to perform u64 <-> i64 bit-for-bit conversions today which is guaranteed not to add conversion overhead (i.e. no {over,under}flow checks), and that is low-to-no risk of being deprecated in the future?


XY: My app uses u64 but stores them in a database that takes in and returns i64.

The compiler (in release mode) is clued up enough to recognise that:

fn convert(num: u64) -> i64 {
    i64::from_ne_bytes(num.to_ne_bytes())
}

is a no-op. See this Rust Godbolt where both that, and simply returning the input, compile down to the same machine code.

8 Likes

This won't help right now, but libs-API has approved cast_signed and cast_unsigned methods as the way forward for this: Explicit signedness casts for integers · Issue #359 · rust-lang/libs-team · GitHub

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.