From 27413fbaeaeb218f081e4a39bc60e60bf6dc1902 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Sat, 16 Sep 2023 17:49:32 +0200 Subject: [PATCH] Make overflowing integer add fail rather than wrap around (#350) --- CHANGELOG.md | 4 +++- minijinja/src/value/ops.rs | 11 ++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 36af23bb..b7f32573 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/minijinja/src/value/ops.rs b/minijinja/src/value/ops.rs index 9610d959..05fb56ea 100644 --- a/minijinja/src/value/ops.rs +++ b/minijinja/src/value/ops.rs @@ -180,7 +180,10 @@ macro_rules! math_binop { pub fn add(lhs: &Value, rhs: &Value) -> Result { 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)), @@ -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]