From e644d5cef1ebb5426d5b43e0304a43fa1bdc9bc8 Mon Sep 17 00:00:00 2001 From: Michal Nazarewicz Date: Mon, 4 Dec 2023 01:02:38 +0100 Subject: [PATCH] Introduce BitSlice::from_bit{,_mut} methods Introduce BitSlice::from_bit and BitSlice::from_bit_mut methods to easily in an infallible way construct a reference to a single bit of an element. For the most part, this is just a convenience wrapper around calling `.get(n..=n)` on a slice constructed via from_element{,_mut} method however in certain situations it makes it possible to avoid unwrapping of the returned Option. --- src/slice.rs | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/src/slice.rs b/src/slice.rs index f73efc49..c0a09c1e 100644 --- a/src/slice.rs +++ b/src/slice.rs @@ -210,6 +210,84 @@ where } } + /// Constructs a shared `&BitSlice` reference over a single bit a shared + /// element. + /// + /// ## Parameters + /// + /// - `elem`: A shared reference to a memory element. + /// - `index`: the index of the bit. + /// + /// ## Returns + /// + /// A shared `&BitSlice` over a single bit of the `elem` at given + /// `index`. + /// + /// ## Examples + /// + /// ```rust + /// use bitvec::prelude::*; + /// + /// let elem = 0b000_10000_u8; + /// let slice = BitSlice::<_, Msb0>::from_bit( + /// &elem, + /// bitvec::index::BitIdx::new(3).unwrap(), + /// ); + /// assert_eq!(bits![1], slice); + /// ``` + #[inline] + pub fn from_bit( + elem: &T, + index: crate::index::BitIdx, + ) -> &Self { + unsafe { + BitPtr::new_unchecked(elem.into(), index) + .span_unchecked(1) + .into_bitslice_ref() + } + } + + /// Constructs an exclusive `&mut BitSlice` reference over a single bit + /// of an element. + /// + /// ## Parameters + /// + /// - `elem`: An exclusive reference to a memory element. + /// - `index`: the index of the bit. + /// + /// ## Returns + /// + /// An exclusive `&mut BitSlice` over a single bit of the `elem` at given + /// `index`. + /// + /// ## Examples + /// + /// ```rust + /// use bitvec::prelude::*; + /// + /// let mut elem = 0b000_10000_u8; + /// { + /// let slice = BitSlice::<_, Msb0>::from_bit_mut( + /// &mut elem, + /// bitvec::index::BitIdx::new(3).unwrap(), + /// ); + /// assert_eq!(bits![1], slice); + /// slice.set(0, false); + /// } + /// assert_eq!(0, elem); + /// ``` + #[inline] + pub fn from_bit_mut( + elem: &mut T, + index: crate::index::BitIdx, + ) -> &mut Self { + unsafe { + BitPtr::new_unchecked(elem.into(), index) + .span_unchecked(1) + .into_bitslice_mut() + } + } + /// Constructs a shared `&BitSlice` reference over a slice of elements. /// /// The [`BitView`] trait, implemented on all `[T]` slices, provides a