YorKnEz

Untitled

Oct 25th, 2023
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. enum Error {
  2. AddOverflow,
  3. ProdOverflow,
  4. }
  5.  
  6. fn main() {
  7. let res = tester();
  8.  
  9. match res {
  10. Ok(_) => println!("success"),
  11. Err(e) => {
  12. match e {
  13. Error::AddOverflow => panic!("add_overflow"),
  14. Error::ProdOverflow => panic!("prod_overflow")
  15. }
  16. }
  17. }
  18. }
  19.  
  20. fn tester() -> Result<bool, Error> {
  21. let x: u32 = u32::MAX;
  22. let y: u32 = 1;
  23.  
  24. let mut res: u32;
  25.  
  26. res = add(y, y)?;
  27. println!("{res}");
  28.  
  29. res = prod(x, x)?;
  30. println!("{res}");
  31.  
  32. Ok(true)
  33. }
  34.  
  35. fn add(x: u32, y: u32) -> Result<u32, Error> {
  36. let sum: u64 = (x as u64) + (y as u64);
  37.  
  38. if sum > (u32::MAX as u64) {
  39. return Err(Error::AddOverflow);
  40. }
  41.  
  42. Ok(sum as u32)
  43. }
  44.  
  45. fn prod(x: u32, y: u32) -> Result<u32, Error> {
  46. let prod: u64 = (x as u64) * (y as u64);
  47.  
  48. if prod > (u32::MAX as u64) {
  49. return Err(Error::ProdOverflow);
  50. }
  51.  
  52. Ok(prod as u32)
  53. }
Advertisement
Add Comment
Please, Sign In to add comment