Guest User

Untitled

a guest
Apr 26th, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. type RectSide = f64;
  2.  
  3. const SIDE_BOUND: RectSide = 1_000_000_000.0;
  4.  
  5. #[derive(Debug, PartialEq)]
  6. enum MaxSquareSideError {
  7. NonPositive(RectSide),
  8. OutOfBound(RectSide),
  9. Malformed(RectSide),
  10. }
  11.  
  12. fn max_square_side(a: RectSide, b: RectSide) -> Result<RectSide, MaxSquareSideError> {
  13. fn check_side(x: RectSide) -> Result<RectSide, MaxSquareSideError> {
  14. use MaxSquareSideError::*;
  15. if x.is_nan() || x.is_infinite() {
  16. return Err(Malformed(x));
  17. }
  18. if x <= 0.0 {
  19. return Err(NonPositive(x));
  20. }
  21. if x > SIDE_BOUND {
  22. return Err(OutOfBound(x));
  23. }
  24. Ok(x)
  25. }
  26.  
  27. check_side(a)?;
  28. check_side(b)?;
  29.  
  30. let (bigger, smaller) = if a > b { (a, b) } else { (b, a) };
  31. let max1 = smaller / 2.0;
  32. let max2 = smaller.min(bigger / 3.0);
  33. Ok(max1.max(max2))
  34. }
  35.  
  36. #[test]
  37. fn ensure_bound_correctness() {
  38. assert!(!SIDE_BOUND.is_nan() && !SIDE_BOUND.is_infinite() && SIDE_BOUND > 0.0);
  39.  
  40. assert!(!(SIDE_BOUND * SIDE_BOUND).is_infinite());
  41. }
  42.  
  43. #[test]
  44. fn some_variants() {
  45. assert_eq!(max_square_side(210.0, 297.0), Ok(105.0));
  46. assert_eq!(max_square_side(250.0, 100.0), Ok(83.33333333333333));
  47. assert_eq!(max_square_side(400.0, 404.0), Ok(200.0));
  48. assert_eq!(max_square_side(1.0, 100.0), Ok(1.0));
  49. assert_eq!(max_square_side(870.0, 300.0), Ok(290.0));
  50. }
  51.  
  52. #[test]
  53. fn check_bound() {
  54. use MaxSquareSideError::*;
  55. let (a, b) = (SIDE_BOUND + 1.0, 3.14);
  56. assert_eq!(max_square_side(a, b), Err(OutOfBound(a)));
  57. }
  58.  
  59. #[test]
  60. fn check_nonpositive() {
  61. use MaxSquareSideError::*;
  62.  
  63. let (a, b) = (0.0, 3.14);
  64. assert_eq!(max_square_side(a, b), Err(NonPositive(a)));
  65.  
  66. let (a, b) = (3.14, -42.0);
  67. assert_eq!(max_square_side(a, b), Err(NonPositive(b)));
  68. }
  69.  
  70. #[test]
  71. fn check_malformed() {
  72. use MaxSquareSideError::*;
  73.  
  74. let (a, b) = (0.0 / 0.0, 3.14);
  75. match max_square_side(a, b) {
  76. Err(Malformed(val)) => assert!(val.is_nan()),
  77. _ => unreachable!(),
  78. }
  79.  
  80. let (a, b) = (1.0 / 0.0, 666.9);
  81. assert_eq!(max_square_side(a, b), Err(Malformed(a)));
  82.  
  83. let (a, b) = (-1.0 / 0.0, 123.4);
  84. assert_eq!(max_square_side(a, b), Err(Malformed(a)));
  85. }
Add Comment
Please, Sign In to add comment