Fix overflows with operators (#904)

This commit is contained in:
HarmoGlace 2023-04-26 11:30:16 +02:00 committed by GitHub
parent a6df909a8d
commit 7cb63d1aae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 4 deletions

View File

@ -53,7 +53,7 @@ pub fn pos(value: Value) -> StrResult<Value> {
/// Compute the negation of a value. /// Compute the negation of a value.
pub fn neg(value: Value) -> StrResult<Value> { pub fn neg(value: Value) -> StrResult<Value> {
Ok(match value { Ok(match value {
Int(v) => Int(-v), Int(v) => Int(v.checked_neg().ok_or("value is too large")?),
Float(v) => Float(-v), Float(v) => Float(-v),
Length(v) => Length(-v), Length(v) => Length(-v),
Angle(v) => Angle(-v), Angle(v) => Angle(-v),
@ -70,7 +70,7 @@ pub fn add(lhs: Value, rhs: Value) -> StrResult<Value> {
(a, None) => a, (a, None) => a,
(None, b) => b, (None, b) => b,
(Int(a), Int(b)) => Int(a + b), (Int(a), Int(b)) => Int(a.checked_add(b).ok_or("value is too large")?),
(Int(a), Float(b)) => Float(a as f64 + b), (Int(a), Float(b)) => Float(a as f64 + b),
(Float(a), Int(b)) => Float(a + b as f64), (Float(a), Int(b)) => Float(a + b as f64),
(Float(a), Float(b)) => Float(a + b), (Float(a), Float(b)) => Float(a + b),
@ -137,7 +137,7 @@ pub fn add(lhs: Value, rhs: Value) -> StrResult<Value> {
/// Compute the difference of two values. /// Compute the difference of two values.
pub fn sub(lhs: Value, rhs: Value) -> StrResult<Value> { pub fn sub(lhs: Value, rhs: Value) -> StrResult<Value> {
Ok(match (lhs, rhs) { Ok(match (lhs, rhs) {
(Int(a), Int(b)) => Int(a - b), (Int(a), Int(b)) => Int(a.checked_sub(b).ok_or("value is too large")?),
(Int(a), Float(b)) => Float(a as f64 - b), (Int(a), Float(b)) => Float(a as f64 - b),
(Float(a), Int(b)) => Float(a - b as f64), (Float(a), Int(b)) => Float(a - b as f64),
(Float(a), Float(b)) => Float(a - b), (Float(a), Float(b)) => Float(a - b),
@ -165,7 +165,7 @@ pub fn sub(lhs: Value, rhs: Value) -> StrResult<Value> {
/// Compute the product of two values. /// Compute the product of two values.
pub fn mul(lhs: Value, rhs: Value) -> StrResult<Value> { pub fn mul(lhs: Value, rhs: Value) -> StrResult<Value> {
Ok(match (lhs, rhs) { Ok(match (lhs, rhs) {
(Int(a), Int(b)) => Int(a * b), (Int(a), Int(b)) => Int(a.checked_mul(b).ok_or("value is too large")?),
(Int(a), Float(b)) => Float(a as f64 * b), (Int(a), Float(b)) => Float(a as f64 * b),
(Float(a), Int(b)) => Float(a * b as f64), (Float(a), Int(b)) => Float(a * b as f64),
(Float(a), Float(b)) => Float(a * b), (Float(a), Float(b)) => Float(a * b),

View File

@ -33,6 +33,11 @@
#test((1, 2) + (3, 4), (1, 2, 3, 4)) #test((1, 2) + (3, 4), (1, 2, 3, 4))
#test((a: 1) + (b: 2, c: 3), (a: 1, b: 2, c: 3)) #test((a: 1) + (b: 2, c: 3), (a: 1, b: 2, c: 3))
---
// Error: 3-26 value is too large
#(9223372036854775807 + 1)
---
// Subtraction. // Subtraction.
#test(1-4, 3*-1) #test(1-4, 3*-1)
#test(4cm - 2cm, 2cm) #test(4cm - 2cm, 2cm)