Skip to content
This repository was archived by the owner on Dec 1, 2023. It is now read-only.

Commit dcd9ad3

Browse files
committed
Fix 'arithmetic operation overflowed' panic in json::Parser::parse_u64
Used checked arithmetic rather than checking for overflow after the fact. Another option is to keep checking after the fact and use wrapping arithmetic.
1 parent f184947 commit dcd9ad3

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

src/json.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1481,7 +1481,6 @@ impl<T: Iterator<Item = char>> Parser<T> {
14811481

14821482
fn parse_u64(&mut self) -> Result<u64, ParserError> {
14831483
let mut accum = 0;
1484-
let mut last_accum = 0; // necessary to detect overflow.
14851484

14861485
match self.ch_or_null() {
14871486
'0' => {
@@ -1497,12 +1496,16 @@ impl<T: Iterator<Item = char>> Parser<T> {
14971496
while !self.eof() {
14981497
match self.ch_or_null() {
14991498
c @ '0' ... '9' => {
1500-
accum *= 10;
1501-
accum += (c as u64) - ('0' as u64);
1502-
1503-
// Detect overflow by comparing to the last value.
1504-
if accum <= last_accum { return self.error(InvalidNumber); }
1505-
last_accum = accum;
1499+
macro_rules! try_or_invalid {
1500+
($e: expr) => {
1501+
match $e {
1502+
Some(v) => v,
1503+
None => return self.error(InvalidNumber)
1504+
}
1505+
}
1506+
}
1507+
accum = try_or_invalid!(accum.checked_mul(10));
1508+
accum = try_or_invalid!(accum.checked_add((c as u64) - ('0' as u64)));
15061509

15071510
self.bump();
15081511
}

0 commit comments

Comments
 (0)