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.
| C | Rust |
|---|---|
int, unsigned | i32, u32 (or c_int, c_uint at a C boundary) |
size_t | usize |
ssize_t, ptrdiff_t | isize |
uint8_t, int64_t | u8, i64 |
char as a small number | u8 or i8 (a Rust char is a Unicode scalar value, 4 bytes, not a C char) |
_Bool | bool |
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:
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);
}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 -1Reading 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#
- Replace each C type with a fixed-width Rust type, using the table. Use
usizefor lengths and indexes, assize_twas. - 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_*). - For every arithmetic operation that could overflow, choose
checked_*,wrapping_*orsaturating_*on purpose. Plain+panics in a debug build and wraps in a release build (see the thread on which bugs Rust prevents). - 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
asfor every conversion because it never complains. A wrongassilently 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
i32andusizein index arithmetic. Convert once, at the edge, withusize::try_from(x)?.
Related questions#
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#
- The Rust Reference, "Type cast expressions": https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
std::ffi::c_intand related aliases: https://doc.rust-lang.org/std/ffi/type.c_int.html