From 3270e0f2ca455e75ac002fefd02efa6ecb284fdc Mon Sep 17 00:00:00 2001 From: Michal Nazarewicz Date: Sat, 2 Dec 2023 19:27:02 +0100 Subject: [PATCH] =?UTF-8?q?Implement=20BitIdx=20=E2=86=92=20BitEnd=20conve?= =?UTF-8?q?rsion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since BitIdx’s inner value is within the domain of BigEnd, it’s possible to infallibly convert the former into the latter. Alas, no function facilitating this exist and conversion through u8 is required. Introduce `From> for BitEnd` implementation which provides such feature. --- src/index.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/index.rs b/src/index.rs index 98f88e4c..061bde46 100644 --- a/src/index.rs +++ b/src/index.rs @@ -106,7 +106,6 @@ where R: BitRegister /// Removes the index wrapper, leaving the internal counter. #[inline] - #[cfg(not(tarpaulin_include))] pub fn into_inner(self) -> u8 { self.idx } @@ -593,6 +592,14 @@ where R: BitRegister } } +impl From> for BitEnd { + fn from(idx: BitIdx) -> Self { + // SAFETY: Maximum allowed value of BitIdx is always smaller + // than maximum allowed value of BitEnd. + unsafe { Self::new_unchecked(idx.into_inner()) } + } +} + #[repr(transparent)] #[doc = include_str!("../doc/index/BitPos.md")] // #[rustc_layout_scalar_valid_range_end(R::BITS)] @@ -1083,6 +1090,12 @@ mod tests { assert!(BitEnd::::new(n).is_some()); } assert!(BitEnd::::new(bits_of::() as u8 + 1).is_none()); + + for n in 0 .. bits_of::() as u8 { + let idx = BitIdx::::new(n).unwrap(); + let end = BitEnd::::new(n).unwrap(); + assert_eq!(end, BitEnd::from(idx)); + } } #[test]