Skip to content

Commit a4091ad

Browse files
committed
iterators3: Add IntegerOverflow error variant
1 parent a7a8818 commit a4091ad

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

exercises/18_iterators/iterators3.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
#[derive(Debug, PartialEq, Eq)]
22
enum DivisionError {
3+
// Example: 42 / 0
34
DivideByZero,
5+
// Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1`
6+
IntegerOverflow,
7+
// Example: 5 / 2 = 2.5
48
NotDivisible,
59
}
610

711
// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
812
// Otherwise, return a suitable error.
9-
fn divide(a: i32, b: i32) -> Result<i32, DivisionError> {
13+
fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
1014
todo!();
1115
}
1216

@@ -42,6 +46,11 @@ mod tests {
4246
assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero));
4347
}
4448

49+
#[test]
50+
fn test_integer_overflow() {
51+
assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow));
52+
}
53+
4554
#[test]
4655
fn test_not_divisible() {
4756
assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible));

solutions/18_iterators/iterators3.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
#[derive(Debug, PartialEq, Eq)]
22
enum DivisionError {
3+
// Example: 42 / 0
34
DivideByZero,
5+
// Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1`
6+
IntegerOverflow,
7+
// Example: 5 / 2 = 2.5
48
NotDivisible,
59
}
610

@@ -9,6 +13,10 @@ fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
913
return Err(DivisionError::DivideByZero);
1014
}
1115

16+
if a == i64::MIN && b == -1 {
17+
return Err(DivisionError::IntegerOverflow);
18+
}
19+
1220
if a % b != 0 {
1321
return Err(DivisionError::NotDivisible);
1422
}
@@ -51,6 +59,11 @@ mod tests {
5159
assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero));
5260
}
5361

62+
#[test]
63+
fn test_integer_overflow() {
64+
assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow));
65+
}
66+
5467
#[test]
5568
fn test_not_divisible() {
5669
assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible));

0 commit comments

Comments
 (0)