iterators3: Add IntegerOverflow error variant

This commit is contained in:
mo8it 2024-07-08 14:40:35 +02:00
parent a7a881809f
commit a4091ade5c
2 changed files with 23 additions and 1 deletions

View file

@ -1,12 +1,16 @@
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
enum DivisionError { enum DivisionError {
// Example: 42 / 0
DivideByZero, DivideByZero,
// Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1`
IntegerOverflow,
// Example: 5 / 2 = 2.5
NotDivisible, NotDivisible,
} }
// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`. // TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`.
// Otherwise, return a suitable error. // Otherwise, return a suitable error.
fn divide(a: i32, b: i32) -> Result<i32, DivisionError> { fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
todo!(); todo!();
} }
@ -42,6 +46,11 @@ mod tests {
assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero));
} }
#[test]
fn test_integer_overflow() {
assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow));
}
#[test] #[test]
fn test_not_divisible() { fn test_not_divisible() {
assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible)); assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible));

View file

@ -1,6 +1,10 @@
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
enum DivisionError { enum DivisionError {
// Example: 42 / 0
DivideByZero, DivideByZero,
// Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1`
IntegerOverflow,
// Example: 5 / 2 = 2.5
NotDivisible, NotDivisible,
} }
@ -9,6 +13,10 @@ fn divide(a: i64, b: i64) -> Result<i64, DivisionError> {
return Err(DivisionError::DivideByZero); return Err(DivisionError::DivideByZero);
} }
if a == i64::MIN && b == -1 {
return Err(DivisionError::IntegerOverflow);
}
if a % b != 0 { if a % b != 0 {
return Err(DivisionError::NotDivisible); return Err(DivisionError::NotDivisible);
} }
@ -51,6 +59,11 @@ mod tests {
assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero));
} }
#[test]
fn test_integer_overflow() {
assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow));
}
#[test] #[test]
fn test_not_divisible() { fn test_not_divisible() {
assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible)); assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible));