Skip to content

Casting u128::MAX to f32 is undefined #41799

Closed
@est31

Description

@est31

Given this code (playpen):

#![feature(i128_type,i128)]

fn cast(src: f32) -> Result<u128, &'static str> {
    use std::{u128, f32};

    Err(if src != src {
        "NaN"
    } else if src < u128::MIN as f32 {
        "Underflow"
    } else if src > u128::MAX as f32 {
        "Overflow"
    } else {
        return Ok(src as u128);
    })
}
fn main() {
    let f = 2742605.0f32;
    println!("{:?}", cast(f));
}

It should print Ok(2742605). In release mode, that happens, but in debug mode, it prints Err("Overflow").

The value is mostly irrelevant, it would also work for 42.0.

cc @nagisa
cc #35118 tracking issue

Metadata

Metadata

Assignees

No one assigned

    Labels

    B-unstableBlocker: Implemented in the nightly compiler and unstable.C-bugCategory: This is a bug.I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessP-mediumMedium priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions