Skip to content

Commit

Permalink
Make overflowing integer add fail rather than wrap around (#350)
Browse files Browse the repository at this point in the history
  • Loading branch information
mitsuhiko authored Sep 16, 2023
1 parent 0573e87 commit 27413fb
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ All notable changes to MiniJinja are documented here.

## 1.0.8

- Relatex the trait bounds of `Value::downcast_object_ref` /
- Relax the trait bounds of `Value::downcast_object_ref` /
`Object::downcast_ref` / `Object::is` and added support for downcasting
of types that were directly created with `Value::from_seq_object`
and `Value::from_struct_object`. #349
- Overflowing additions on very large integers now fails rather than
silently wrapping around. #350
- Fixed a few overflow panics: dividing integers with an overflow and
related overflows in the `abs` and `neg` filter. #347

Expand Down
11 changes: 10 additions & 1 deletion minijinja/src/value/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,10 @@ macro_rules! math_binop {

pub fn add(lhs: &Value, rhs: &Value) -> Result<Value, Error> {
match coerce(lhs, rhs) {
Some(CoerceResult::I128(a, b)) => Ok(int_as_value(a.wrapping_add(b))),
Some(CoerceResult::I128(a, b)) => a
.checked_add(b)
.ok_or_else(|| failed_op("+", lhs, rhs))
.map(int_as_value),
Some(CoerceResult::F64(a, b)) => Ok((a + b).into()),
Some(CoerceResult::Str(a, b)) => Ok(Value::from([a, b].concat())),
_ => Err(impossible_op("+", lhs, rhs)),
Expand Down Expand Up @@ -309,6 +312,12 @@ mod tests {
add(&Value::from("foo"), &Value::from("bar")).unwrap(),
Value::from("foobar")
);

let err = add(&Value::from(i128::MAX), &Value::from(1)).unwrap_err();
assert_eq!(
err.to_string(),
"invalid operation: unable to calculate 170141183460469231731687303715884105727 + 1"
);
}

#[test]
Expand Down

0 comments on commit 27413fb

Please sign in to comment.