From 192b637c101e41d52d56c7c576ac94a75c6855df Mon Sep 17 00:00:00 2001 From: Andrew Johnson Date: Thu, 24 May 2018 21:50:31 -0600 Subject: [PATCH] debugging asserts --- Chapter09/Cargo.toml | 5 +++++ Chapter09/debugging_assert.rs | 37 +++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 Chapter09/debugging_assert.rs diff --git a/Chapter09/Cargo.toml b/Chapter09/Cargo.toml index fa96ea8..9b7d8b3 100644 --- a/Chapter09/Cargo.toml +++ b/Chapter09/Cargo.toml @@ -79,3 +79,8 @@ path = "debugging_heartbeat.rs" [[bin]] name = "debugging_buggy_worker" path = "debugging_buggy_worker.rs" + +[[bin]] +name = "debugging_assert" +path = "debugging_assert.rs" + diff --git a/Chapter09/debugging_assert.rs b/Chapter09/debugging_assert.rs new file mode 100644 index 0000000..68c7d3a --- /dev/null +++ b/Chapter09/debugging_assert.rs @@ -0,0 +1,37 @@ +use std::io; + +fn debug_precondition(n: u64) -> u64 { + debug_assert!(n < 100); + n * n +} + +fn debug_postcondition(n: u64) -> u64 { + let r = n * n; + debug_assert!(r > 10); + r +} + +fn runtime_precondition(n: u64) -> Result { + if !(n<100) { return Err(()) }; + Ok(n * n) +} + +fn runtime_postcondition(n: u64) -> Result { + let r = n * n; + if !(r>10) { return Err(()) }; + Ok(r) +} + +fn main() { + //inward facing code should assert expectations + debug_precondition(5); + debug_postcondition(5); + + //outward facing code should handle errors + let mut s = String::new(); + println!("Please input a positive integer greater or equal to 4:"); + io::stdin().read_line(&mut s).expect("error reading input"); + let i = s.trim().parse::().expect("error parsing input as integer"); + runtime_precondition(i).expect("runtime precondition violated"); + runtime_postcondition(i).expect("runtime postcondition violated"); +}