Skip to content

Commit

Permalink
Fix parsing negative hexadecimal integers
Browse files Browse the repository at this point in the history
Rust's from_str_radix() method doesn't support negative hexadecimal
integer values such as "-0xA". This commit fixes this by special-casing
such inputs.

Changelog: fixed
  • Loading branch information
yorickpeterse committed Oct 17, 2022
1 parent 4325ed9 commit 8b670e6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
11 changes: 9 additions & 2 deletions compiler/src/hir.rs
Expand Up @@ -1617,8 +1617,15 @@ impl<'a> LowerToHir<'a> {
input = input.replace('_', "");
}

let result = if let Some(slice) = input.strip_prefix("0x") {
i64::from_str_radix(slice, 16)
let hex_prefix = if input.starts_with("-") { "-0x" } else { "0x" };
let result = if let Some(slice) = input.strip_prefix(hex_prefix) {
i64::from_str_radix(slice, 16).map(|v| {
if input.starts_with("-") {
0_i64.wrapping_sub(v)
} else {
v
}
})
} else {
i64::from_str(&input)
};
Expand Down
3 changes: 3 additions & 0 deletions libstd/test/std/test_int.inko
Expand Up @@ -34,6 +34,9 @@ fn pub tests(t: mut Tests) {
t.equal(Int.from_base16(' 11'), Option.None)
t.equal(Int.from_base16('11 '), Option.None)
t.equal(Int.from_base16('zz'), Option.None)
t.equal(
Int.from_base16('-0x4a3f043013b2c4d1'), Option.Some(-5349999486874862801)
)
}

t.test('Int.to_base2') fn (t) {
Expand Down
14 changes: 13 additions & 1 deletion vm/src/builtin_functions/string.rs
Expand Up @@ -94,7 +94,19 @@ pub(crate) fn string_to_int(
string
};

let res = i64::from_str_radix(slice, radix as u32)
// Rust doesn't handle parsing strings like "-0x4a3f043013b2c4d1" out of the
// box.
let parsed = if radix == 16 {
if let Some(tail) = string.strip_prefix("-0x") {
i64::from_str_radix(tail, 16).map(|v| 0_i64.wrapping_sub(v))
} else {
i64::from_str_radix(slice, 16)
}
} else {
i64::from_str_radix(slice, radix as u32)
};

let res = parsed
.map(|val| Int::alloc(state.permanent_space.int_class(), val))
.unwrap_or_else(|_| Pointer::undefined_singleton());

Expand Down

0 comments on commit 8b670e6

Please sign in to comment.