Skip to content

from_str_radix panics when the first char is encoded with multiple bytes #125

@197g

Description

@197g

play.

fn main() {
    let _ = f32::from_str_radix("™0.2", 10);
}

Expected behaviour

Nothing hapens. The method returns an error with kind Invalid which is ignored.

Observed behaviour

The code panics.

thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside '™' (bytes 0..3) of `™0.2`', src/libcore/str/mod.rs:2034:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

Cause analysis

The underlying cause is that slice_shift_char splits the string at a hardcode byte offset of 1 instead of the byte-length of the first character. This panics when it is not a UTF-8 byte boundary.

num-traits/src/lib.rs

Lines 218 to 220 in 58f02a8

fn slice_shift_char(src: &str) -> Option<(char, &str)> {
src.chars().nth(0).map(|ch| (ch, &src[1..]))
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions