Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code supporting both 32-bit and 64-bit platforms #20

Closed
sunfishcode opened this issue Jan 23, 2019 · 2 comments
Closed

Code supporting both 32-bit and 64-bit platforms #20

sunfishcode opened this issue Jan 23, 2019 · 2 comments

Comments

@sunfishcode
Copy link
Contributor

The following code compiles on 64-bit targets:

fn main() {
    let a: usize = 2;
    let b: u32 = cast::u32(a).unwrap();
    let c: u64 = cast::u64(a);
    let _d: usize = cast::usize(b);
    let _e: usize = cast::usize(c);
}

However, it doesn't compile on a 32-bit target:

error[E0599]: no method named `unwrap` found for type `u32` in the current scope
 --> src/main.rs:3:31
  |
3 |     let b: u32 = cast::u32(a).unwrap();
  |                               ^^^^^^

error[E0308]: mismatched types
 --> src/main.rs:6:21
  |
6 |     let _e: usize = cast::usize(c);
  |                     ^^^^^^^^^^^^^^ expected usize, found enum `std::result::Result`
  |
  = note: expected type `usize`
             found type `std::result::Result<usize, cast::Error>`

because the Output types use Result or not depending on the target's usize size.

Is there a way to write code that does checked (when needed) casts between fixed-sized types and usize that works on both 32-bit and 64-bit platforms?

I might be looking for something returning a Result on both, relying on inlining and optimization to eliminate the overhead in cases where the conversion turns out to be trivial.

@japaric
Copy link
Owner

japaric commented Feb 8, 2019

Is there a way to write code that does checked (when needed) casts between fixed-sized types and usize that works on both 32-bit and 64-bit platforms?

Yes, using conditional compilation: #[cfg(target_pointer_width = "32")].

I might be looking for something returning a Result on both

Then you might want to use usize::try_from instead.

@sunfishcode
Copy link
Contributor Author

And now, TryFrom is stable in Rust 1.34, so that covers the need here!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants