diff --git a/src/lib.rs b/src/lib.rs index 2348265..1f3ca74 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -111,6 +111,7 @@ macro_rules! implement_common { /// # Panic /// /// This function will panic if `value` is not representable by this type + #[track_caller] pub const fn new(value: $type) -> $name { assert!(value <= $name::MAX.0 && value >= $name::MIN.0); $name(value) @@ -361,6 +362,7 @@ macro_rules! implement_common { impl lib::core::ops::Add<$name> for $name { type Output = $name; #[allow(unused_comparisons)] + #[track_caller] fn add(self, other: $name) -> $name { if self.0 > 0 && other.0 > 0 { debug_assert!(Self::MAX.0 - other.0 >= self.0); @@ -374,6 +376,7 @@ macro_rules! implement_common { impl lib::core::ops::Sub<$name> for $name { type Output = $name; #[allow(unused_comparisons)] + #[track_caller] fn sub(self, other: $name) -> $name { if self > other { debug_assert!(Self::MAX.0 + other.0 >= self.0); @@ -966,4 +969,44 @@ mod tests { _ => (), } } + + /// For manual confirmation: + /// 1. Comment-out the line containing `should_panic` + /// 2. cargo test --features=std test_panic_track_caller + /// 3. Verify line numbers match this call site, NOT `const fn new(...)` + #[cfg(feature = "std")] + #[test] + #[should_panic(expected = "assertion failed: value <= u20::MAX.0 && value >= u20::MIN.0")] + fn test_panic_track_caller_1() { + std::eprintln!( + "Expected:\nthread 'tests::test_panic_track_caller_1' panicked at {}:{}:9", + file!(), + line!() + 2 + ); + u20::new(u32::MAX); + } + + #[cfg(feature = "std")] + #[test] + #[should_panic(expected = "assertion failed: Self::MAX.0 - other.0 >= self.0")] + fn test_panic_track_caller_2() { + std::eprintln!( + "Expected:\nthread 'tests::test_panic_track_caller_2' panicked at {}:{}:26", + file!(), + line!() + 2 + ); + let _overflows = u20::new(u20::MAX.0) + u20::new(1); + } + + #[cfg(feature = "std")] + #[test] + #[should_panic(expected = "assertion failed: Self::MIN.0 + other.0 <= self.0")] + fn test_panic_track_caller_3() { + std::eprintln!( + "Expected:\nthread 'tests::test_panic_track_caller_3' panicked at {}:{}:27", + file!(), + line!() + 2 + ); + let _underflows = u20::new(1) - u20::new(u20::MAX.0); + } }