From c45624e3c29de5bbcfb8e24a525073f5ee67a287 Mon Sep 17 00:00:00 2001 From: Jacob Lifshay Date: Tue, 26 Nov 2024 16:26:29 -0800 Subject: [PATCH] Fix SInt::for_value not accounting for sign bit for positive values Fixes: #4 --- crates/fayalite/src/int.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/fayalite/src/int.rs b/crates/fayalite/src/int.rs index 03b2c88..4dd7696 100644 --- a/crates/fayalite/src/int.rs +++ b/crates/fayalite/src/int.rs @@ -453,7 +453,10 @@ impl SInt { v.not().bits().checked_add(1).expect("too big") } Sign::NoSign => 0, - Sign::Plus => v.bits(), + Sign::Plus => { + // account for sign bit + v.bits().checked_add(1).expect("too big") + } } .try_into() .expect("too big"), @@ -693,3 +696,31 @@ impl ToLiteralBits for bool { Ok(interned_bit(*self)) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_uint_for_value() { + assert_eq!(UInt::for_value(0u8).width, 0); + assert_eq!(UInt::for_value(1u8).width, 1); + assert_eq!(UInt::for_value(2u8).width, 2); + assert_eq!(UInt::for_value(3u8).width, 2); + assert_eq!(UInt::for_value(4u8).width, 3); + } + + #[test] + fn test_sint_for_value() { + assert_eq!(SInt::for_value(-5).width, 4); + assert_eq!(SInt::for_value(-4).width, 3); + assert_eq!(SInt::for_value(-3).width, 3); + assert_eq!(SInt::for_value(-2).width, 2); + assert_eq!(SInt::for_value(-1).width, 1); + assert_eq!(SInt::for_value(0).width, 0); + assert_eq!(SInt::for_value(1).width, 2); + assert_eq!(SInt::for_value(2).width, 3); + assert_eq!(SInt::for_value(3).width, 3); + assert_eq!(SInt::for_value(4).width, 4); + } +}