Skip to content

std::i32::MIN % -1 and related #20

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

Open
rcseacord opened this issue Mar 26, 2025 · 5 comments
Open

std::i32::MIN % -1 and related #20

rcseacord opened this issue Mar 26, 2025 · 5 comments
Labels
coding-guideline An issue related to a suggestion for a coding guideline enhancement New feature or request

Comments

@rcseacord
Copy link

do you want to a rule that says used check remainder or make sure that your inputs are not std::i32::MIN % -1
probably std::i32::MIN / -1 and divide by zero as well divide by zero as well

use std::io;
fn main() {
    // Define `i` as the minimum value for a 32-bit signed integer
    let i = std::i32::MIN;
    // Prompt the user for input
    println!("Please enter an integer value for j:");
    // Read input from stdin
    let mut input = String::new();
    io::stdin().read_line(&mut input)
        .expect("Failed to read line");
    // Parse the input as an integer
    let j: i32 = match input.trim().parse() {
        Ok(num) => num,
        Err(_) => {
            eprintln!("Error: Please provide a valid integer for j.");
            std::process::exit(1);
        }
    };
    // Calculate and print the modulus
    println!("i % j = {}", i % j);
}
Exited with status 101
Standard Error
   Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.68s
     Running `target/debug/playground`

thread 'main' panicked at src/main.rs:25:28:
attempt to calculate the remainder with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Standard Output
Please enter an integer value for j:  -1

Lot's of devs don't know about std::i32::MIN % -1, because mathematically it should be zero but faults on Intel processors.

If I ran this on a processor that doesn't fault, would it compile differently?

Compliant solution:

fn main() {
    let i = std::i32::MIN;
    let j = -1;
    match i.checked_rem(j) {
        Some(result) => println!("i % j = {}", result),
        None => println!("i % j = 0"), // This is mathematically correct
    }
}
@x0rw
Copy link

x0rw commented Mar 29, 2025

Hey Robert, for safety-critical systems, unexpected runtime failures are unacceptable. Enforcing these checks aligns with guidelines like MISRA and ensures deterministic behavior, so the use of checked arithmetic functions should be mandatory. However, I think for a safety-critical guideline to be general, there should be a section about when unchecked operations can be used (in performance-critical real-time systems), along with guarantees (formal and manual verifications).

@PLeVasseur
Copy link
Collaborator

If I ran this on a processor that doesn't fault, would it compile differently?

This is a good question I don't know the answer to -- anyone know?

@x0rw
Copy link

x0rw commented Mar 29, 2025

In ARM SDIV manual, the signed division of min::i32 by -1 returns min::i32 instead of producing a hardware exception

If the signed integer division 0x80000000 / 0xFFFFFFFF is performed, the pseudocode produces the intermediate integer result +231, that overflows the 32-bit signed integer range. No indication of this overflow case is produced, and the 32-bit result written to must be the bottom 32 bits of the binary representation of +231. So the result of the division is 0x80000000.

@Veykril
Copy link

Veykril commented Apr 2, 2025

If I ran this on a processor that doesn't fault, would it compile differently?

To my knowledge (and skimming the std docs), the behavior here is the same as any other overflow (irrespective of the platform). This will wrap in release, overflow in debug, that is it adheres to -Coverflow-checks.

@PLeVasseur PLeVasseur added enhancement New feature or request coding-guideline An issue related to a suggestion for a coding guideline labels Apr 3, 2025
@PLeVasseur
Copy link
Collaborator

Thanks for sharing @Veykril!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
coding-guideline An issue related to a suggestion for a coding guideline enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants