Skip to content

Cannot round trip parsing -1 as non-decimal #115545

Open
@Shadow53

Description

@Shadow53

I tried this code:

let value: i32 = -1;
let s = format!("{value:b}");
let parsed = i32::from_str_radix(&s, 2).unwrap();
assert_eq!(parsed, value);

Playground Link

I expected to see this happen: I should be able to parse the i32 from its base-2 string representation. (Edit: this seems to happen with any non-base-10 base).

Instead, this happened: A positive overflow occurs.

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: PosOverflow }', src/main.rs:4:45

Meta

rustc --version --verbose:

1.72.0

This also occurs with 1.74.0-nightly (2023-09-03 58e967a9cc3bd39122e8).

Backtrace

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: PosOverflow }', src/main.rs:4:45
stack backtrace:
   0: rust_begin_unwind
             at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/std/src/panicking.rs:593:5
   1: core::panicking::panic_fmt
             at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/core/src/panicking.rs:67:14
   2: core::result::unwrap_failed
             at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/core/src/result.rs:1651:5
   3: core::result::Result<T,E>::unwrap
             at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/core/src/result.rs:1076:23
   4: playground::main
             at ./[src/main.rs:4](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=8366c7214eda6a198f50f8805b9edb5b#):18
   5: core::ops::function::FnOnce::call_once
             at /rustc/5680fa18feaa87f3ff04063800aec256c3d4b4be/library/core/src/ops/function.rs:250:5

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-fmtArea: `core::fmt`C-bugCategory: This is a bug.C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API 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