FAQ - Help and questions

How do C integer types, casts and overflow map to Rust?

#porting#c-language#integerspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Rust integer types have fixed widths (i32, u64, usize) instead of int and long. The as operator converts like a C cast and never fails, so it can truncate silently. Prefer try_from when a value might not fit, and choose checked, wrapping or saturating arithmetic where C overflowed.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

C's int, long and size_t have widths that depend on the platform. Rust names the width: i8 to i128 (signed), u8 to u128 (unsigned), isize and usize (pointer size, used for lengths and indexes). When a Rust function must match a C signature exactly, std::ffi::c_int, c_long and the other c_* aliases give the width of the C type on the target.

CRust
int, unsignedi32, u32 (or c_int, c_uint at a C boundary)
size_tusize
ssize_t, ptrdiff_tisize
uint8_t, int64_tu8, i64
char as a small numberu8 or i8 (a Rust char is a Unicode scalar value, 4 bytes, not a C char)
_Boolbool

Conversions and overflow are where ports go wrong. The as operator does what a C cast does: it truncates or saturates and never reports an error. The checked forms say when information would be lost. All results below come from rustc 1.93.0 on Windows 11:

src/main.rsrust
use std::ffi::c_int;

fn main() {
    println!("c_int is {} bits; usize is {} bits here", std::mem::size_of::<c_int>() * 8, usize::BITS);

    // `as` never fails: it truncates or saturates, like a C cast.
    println!("{}", -1i32 as u32);
    println!("{}", 300i32 as u8);
    println!("{}", 3.99f64 as i32);
    println!("{}", -5.0f64 as u8);
    println!("{}", f64::NAN as i32);
    println!("{}", 1e20f64 as i32);

    // the checked conversions say when information would be lost
    println!("{:?} {:?}", u8::try_from(300i32), u8::try_from(200i32));
    println!("{:?}", i32::MAX.checked_add(1));
    println!("{}", i32::MAX.wrapping_add(1));
    println!("{}", i32::MAX.saturating_add(1));
    println!("{:?}", i32::MAX.overflowing_add(1));
    println!("{}", (-7i32).rem_euclid(3));
    println!("{} {}", -7 / 2, -7 % 2);
}
text
c_int is 32 bits; usize is 64 bits here
4294967295
44
3
0
0
2147483647
Err(TryFromIntError(())) Ok(200)
None
-2147483648
2147483647
(-2147483648, true)
2
-3 -1

Reading the output: -1 as u32 is the bit pattern 4294967295; 300 as u8 keeps the low 8 bits (44); a float converts by truncating toward zero, and out-of-range floats saturate to the type's limits (-5.0 as u8 is 0, 1e20 as i32 is 2147483647) while NaN becomes 0. Division truncates toward zero and % keeps the sign of the left side, as in C99 and later; rem_euclid gives the always-non-negative remainder.

How to do it#

  1. Replace each C type with a fixed-width Rust type, using the table. Use usize for lengths and indexes, as size_t was.
  2. For every cast in the C code, decide what you want when the value does not fit: an error (try_from), a clamp (.clamp() or saturating arithmetic), or an intended wrap (as, wrapping_*).
  3. For every arithmetic operation that could overflow, choose checked_*, wrapping_* or saturating_* on purpose. Plain + panics in a debug build and wraps in a release build (see the thread on which bugs Rust prevents).
  4. Port bit-twiddling code with unsigned types; a shift by the type's width or more counts as overflow in Rust (it panics in a debug build and masks the shift amount in a release build), and it is not undefined behaviour as in C.

Common mistakes#

  • Using as for every conversion because it never complains. A wrong as silently changes values.
  • Assuming a signed overflow in the C code "just wraps". In C it is undefined behaviour, so the original program may have worked only by luck; choose the intended behaviour explicitly in Rust.
  • Mixing i32 and usize in index arithmetic. Convert once, at the edge, with usize::try_from(x)?.

What replaces unsigned loop counters that count down to zero?#

for i in (0..n).rev() counts down without the "unsigned never below zero" trap that for (i = n - 1; i >= 0; i--) has in C.

Why does Rust not convert i32 to i64 automatically?#

It does not convert between integer types implicitly, even when no information would be lost. Write i64::from(x) (lossless) or x as i64. The explicitness is the point: every place where a width changes is visible.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet