Browse Source

Reworked functions to detect overflows.

Lorenz Bung 8 years ago
parent
commit
c73ce10ddb
1 changed files with 8 additions and 2 deletions
  1. 8
    2
      hw6/task1/src/main.rs

+ 8
- 2
hw6/task1/src/main.rs View File

54
     for x in v {
54
     for x in v {
55
         match x.parse::<i32>() {
55
         match x.parse::<i32>() {
56
             Ok(val) => {
56
             Ok(val) => {
57
-                sum += val;
57
+                match i32::checked_add(sum, val) {
58
+                    Some(y) => {sum = y;}
59
+                    None => return Err("Overflow"),
60
+                }
58
             }
61
             }
59
             Err(_) => return Err("Given String is not a int"),
62
             Err(_) => return Err("Given String is not a int"),
60
         }
63
         }
68
     for x in v {
71
     for x in v {
69
         match x.parse::<i32>() {
72
         match x.parse::<i32>() {
70
             Ok(val) => {
73
             Ok(val) => {
71
-                prod *= val;
74
+                match i32::checked_mul(prod, val) {
75
+                    Some(y) => {prod = y;}
76
+                    None => return Err("Overflow"),
77
+                }
72
             }
78
             }
73
             Err(_) => return Err("Given String is not a int"),
79
             Err(_) => return Err("Given String is not a int"),
74
         }
80
         }

Loading…
Cancel
Save