Unittests on the stack; fix byte order & round-tripping

This commit is contained in:
Reid 'arrdem' McKenzie 2022-12-18 12:22:06 -07:00
parent 670b656410
commit 518a71d24a

View file

@ -34,7 +34,7 @@ impl Stack {
if self.idx > 254 { if self.idx > 254 {
Err(StackError::StackOverflow) Err(StackError::StackOverflow)
} else { } else {
val.to_le_bytes().map(|x| self.push1(x).ok()); val.to_be_bytes().map(|x| self.push1(x).ok());
Ok(()) Ok(())
} }
} }
@ -63,6 +63,7 @@ impl Stack {
} else { } else {
let high = self.buff[idx as usize] as u16; let high = self.buff[idx as usize] as u16;
let low = self.buff[(idx + 1) 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) Ok((high << 8) + low)
} }
} }
@ -91,3 +92,84 @@ impl Stack {
Ok(()) 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"),
}
}
}