Skip to content

Commit 322ed1c

Browse files
author
HeroicKatora
authored
Merge pull request #206 from 5225225/sub-with-overflow-coeff
Avoid integer overflow when summing coefficients
2 parents 9fb38ad + 054a7d4 commit 322ed1c

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

src/decoder.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -939,19 +939,21 @@ fn refine_non_zeroes<R: Read>(reader: &mut R,
939939
for i in range {
940940
let index = UNZIGZAG[i as usize] as usize;
941941

942-
if coefficients[index] == 0 {
942+
let coefficient = &mut coefficients[index];
943+
944+
if *coefficient == 0 {
943945
if zero_run_length == 0 {
944946
return Ok(i);
945947
}
946948

947949
zero_run_length -= 1;
948950
}
949-
else if huffman.get_bits(reader, 1)? == 1 && coefficients[index] & bit == 0 {
950-
if coefficients[index] > 0 {
951-
coefficients[index] += bit;
951+
else if huffman.get_bits(reader, 1)? == 1 && *coefficient & bit == 0 {
952+
if *coefficient > 0 {
953+
*coefficient = coefficient.checked_add(bit).ok_or_else(|| Error::Format("Coefficient overflow".to_owned()))?;
952954
}
953955
else {
954-
coefficients[index] -= bit;
956+
*coefficient = coefficient.checked_sub(bit).ok_or_else(|| Error::Format("Coefficient overflow".to_owned()))?;
955957
}
956958
}
957959
}
Loading

0 commit comments

Comments
 (0)