From 518a71d24a65c0ae173674d9160fccd6181e8901 Mon Sep 17 00:00:00 2001 From: Reid 'arrdem' McKenzie Date: Sun, 18 Dec 2022 12:22:06 -0700 Subject: [PATCH] Unittests on the stack; fix byte order & round-tripping --- src/stack.rs | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/src/stack.rs b/src/stack.rs index d3bfe37..aa37554 100644 --- a/src/stack.rs +++ b/src/stack.rs @@ -34,7 +34,7 @@ impl Stack { if self.idx > 254 { Err(StackError::StackOverflow) } else { - val.to_le_bytes().map(|x| self.push1(x).ok()); + val.to_be_bytes().map(|x| self.push1(x).ok()); Ok(()) } } @@ -63,6 +63,7 @@ impl Stack { } else { let high = self.buff[idx as usize] as u16; let low = self.buff[(idx + 1) as usize] as u16; + println!("idx {}; high {:#02x}; low {:#02x};", idx, high, low); Ok((high << 8) + low) } } @@ -91,3 +92,84 @@ impl Stack { Ok(()) } } + +#[cfg(test)] +mod stack_test { + use super::*; + + #[test] + fn test_push_pop() { + let mut s = Stack::new(); + match s.push1(0xFF) { + Ok(()) => (), + Err(_) => assert!(false, "pushing stack of size 0 errored"), + } + assert_eq!(s.idx, 1); + + match s.peek1() { + Ok(val) => assert_eq!(val, 0xFF), + Err(_) => assert!(false, "popping stack of size 1 errored"), + } + assert_eq!(s.idx, 1); + + match s.pop1() { + Ok(val) => assert_eq!(val, 0xFF), + Err(_) => assert!(false, "popping stack of size 1 errored"), + } + assert_eq!(s.idx, 0); + } + + #[test] + fn test_push2_pop2() { + let mut s = Stack::new(); + match s.push2(0xFF00) { + Ok(()) => (), + Err(_) => assert!(false, "pushing stack of size 0 errored"), + } + assert_eq!(s.idx, 2); + + match s.peek2() { + Ok(val) => assert_eq!(val, 0xFF00), + Err(_) => assert!(false, "peek2 stack of size 2 errored"), + } + assert_eq!(s.idx, 2); + + match s.pop2() { + Ok(val) => assert_eq!(val, 0xFF00), + Err(_) => assert!(false, "peek2 stack of size 2 errored"), + } + assert_eq!(s.idx, 0); + } + + #[test] + fn test_push2_pop1_pop1() { + let mut s = Stack::new(); + match s.push2(0xFF00) { + Ok(()) => (), + Err(_) => assert!(false, "pushing stack of size 0 errored"), + } + assert_eq!(s.idx, 2); + + match s.pop1() { + Ok(val) => assert_eq!(val, 0x00), + Err(_) => assert!(false, "peek1 stack of size 2 errored"), + } + assert_eq!(s.idx, 1); + + match s.pop1() { + Ok(val) => assert_eq!(val, 0xFF), + Err(_) => assert!(false, "peek1 stack of size 2 errored"), + } + assert_eq!(s.idx, 0); + } + + #[test] + fn test_pop_empty() { + let mut s = Stack::new(); + match s.pop1() { + Ok(_) => assert!(false, "popping stack of size 0 succeeded"), + Err(StackError::StackUnderflow) => (), + Err(_) => assert!(false, "poppoing stack of size 0 didn't underflow"), + } + } +}