diff options
author | Matthias Beyer <mail@beyermatthias.de> | 2017-09-07 16:28:54 +0200 |
---|---|---|
committer | Matthias Beyer <mail@beyermatthias.de> | 2017-09-07 16:28:54 +0200 |
commit | 26e6beb424faba7bced157048cc98dae4a1c57c9 (patch) | |
tree | 83d2ffc407261bcab463538336a9713b5b3903db | |
parent | b3d25a9208092fe07a382521acf4a86b168a3032 (diff) | |
parent | fdfcfad129fb69b60e9b7a1e12a616b05a8976d7 (diff) |
Merge branch 'impl-add-sub-mixed'
-rw-r--r-- | src/timetype.rs | 56 |
1 files changed, 50 insertions, 6 deletions
diff --git a/src/timetype.rs b/src/timetype.rs index edabb3e..17e173b 100644 --- a/src/timetype.rs +++ b/src/timetype.rs @@ -129,13 +129,17 @@ impl TimeType { } fn calculate(self) -> Result<TimeType> { - use timetype::TimeType as TT; + do_calculate(self) + } +} - match self { - TT::Addition(a, b) => add(a, b), - TT::Subtraction(a, b) => sub(a, b), - x => Ok(x) - } +fn do_calculate(tt: TimeType) -> Result<TimeType> { + use timetype::TimeType as TT; + + match tt { + TT::Addition(a, b) => add(a, b), + TT::Subtraction(a, b) => sub(a, b), + x => Ok(x) } } @@ -150,6 +154,13 @@ fn add(a: Box<TimeType>, b: Box<TimeType>) -> Result<TimeType> { (other, TT::Addition(a, b)) => add(a, b) .map(Box::new) .and_then(|bx| add(Box::new(other), bx)), + (TT::Subtraction(a, b), other) => sub(a, b) + .map(Box::new) + .and_then(|bx| add(Box::new(other), bx)), + (other, TT::Subtraction(a, b)) => do_calculate(*a) + .map(Box::new) + .and_then(|bx| add(Box::new(other), bx)) + .and_then(|rx| sub(Box::new(rx), b)), (thing, TT::Moment(mom)) => Err(KE::from_kind(KEK::CannotAdd(thing, TT::Moment(mom)))), others => unimplemented!(), } @@ -166,6 +177,13 @@ fn sub(a: Box<TimeType>, b: Box<TimeType>) -> Result<TimeType> { (other, TT::Subtraction(a, b)) => sub(a, b) .map(Box::new) .and_then(|bx| sub(Box::new(other), bx)), + (TT::Addition(a, b), other) => add(a, b) + .map(Box::new) + .and_then(|bx| sub(bx, Box::new(other))), + (other, TT::Addition(a, b)) => do_calculate(*a) + .map(Box::new) + .and_then(|bx| sub(Box::new(other), bx)) + .and_then(|rx| add(Box::new(rx), b)), (thing, TT::Moment(mom)) => Err(KE::from_kind(KEK::CannotSub(thing, TT::Moment(mom)))), others => unimplemented!(), } @@ -1042,4 +1060,30 @@ mod tests { } +#[cfg(test)] +mod test_add_and_sub_mixed { + use timetype::TimeType as TT; + + #[test] + fn test_add_then_sub() { + let a = TT::seconds(0); + let b = TT::seconds(1); + let c = TT::seconds(1); + + let d = a + b - c; + + assert_eq!(0, d.calculate().unwrap().get_seconds()); + } + #[test] + fn test_sub_then_add() { + let a = TT::seconds(1); + let b = TT::seconds(1); + let c = TT::seconds(0); + + let d = a - b + c; + + assert_eq!(0, d.calculate().unwrap().get_seconds()); + } +} + |