| 1 |
#![doc = include_str!("../doc/slice.md")] |
| 2 |
|
| 3 |
#[cfg(feature = "alloc")] |
| 4 |
use alloc::vec::Vec; |
| 5 |
use core::{ |
| 6 |
marker::PhantomData, |
| 7 |
ops::RangeBounds, |
| 8 |
}; |
| 9 |
|
| 10 |
use funty::Integral; |
| 11 |
use tap::Pipe; |
| 12 |
#[cfg(feature = "alloc")] |
| 13 |
use tap::Tap; |
| 14 |
use wyz::{ |
| 15 |
bidi::BidiIterator, |
| 16 |
comu::{ |
| 17 |
Const, |
| 18 |
Mut, |
| 19 |
}, |
| 20 |
range::RangeExt, |
| 21 |
}; |
| 22 |
|
| 23 |
#[cfg(feature = "alloc")] |
| 24 |
use crate::vec::BitVec; |
| 25 |
use crate::{ |
| 26 |
domain::{ |
| 27 |
BitDomain, |
| 28 |
Domain, |
| 29 |
}, |
| 30 |
mem, |
| 31 |
order::{ |
| 32 |
BitOrder, |
| 33 |
Lsb0, |
| 34 |
Msb0, |
| 35 |
}, |
| 36 |
ptr::{ |
| 37 |
self as bv_ptr, |
| 38 |
BitPtr, |
| 39 |
BitPtrRange, |
| 40 |
BitSpan, |
| 41 |
BitSpanError, |
| 42 |
}, |
| 43 |
store::BitStore, |
| 44 |
}; |
| 45 |
|
| 46 |
mod api; |
| 47 |
mod iter; |
| 48 |
mod ops; |
| 49 |
mod specialization; |
| 50 |
mod tests; |
| 51 |
mod traits; |
| 52 |
|
| 53 |
pub use self::{ |
| 54 |
api::*, |
| 55 |
iter::*, |
| 56 |
}; |
| 57 |
|
| 58 |
#[repr(transparent)] |
| 59 |
#[doc = include_str!("../doc/slice/BitSlice.md")] |
| 60 |
pub struct BitSlice<T = usize, O = Lsb0> |
| 61 |
where |
| 62 |
T: BitStore, |
| 63 |
O: BitOrder, |
| 64 |
{ |
| 65 |
/// The ordering of bits within a `T` register. |
| 66 |
_ord: PhantomData<O>, |
| 67 |
/// The register type used for storage. |
| 68 |
_typ: PhantomData<[T]>, |
| 69 |
/// Indicate that this is a newtype wrapper over a wholly-untyped slice. |
| 70 |
/// |
| 71 |
/// This is necessary in order for the Rust compiler to remove restrictions |
| 72 |
/// on the possible values of reference handles to this type. Any other |
| 73 |
/// slice type here (such as `[u8]` or `[T]`) would require that `&/mut |
| 74 |
/// BitSlice` handles have values that correctly describe the region, and |
| 75 |
/// the encoding *does not* do this. As such, reference handles to |
| 76 |
/// `BitSlice` must not be even implicitly dereferenceäble to real memory, |
| 77 |
/// and the slice must be a ZST. |
| 78 |
/// |
| 79 |
/// References to a ZST have no restrictions about what the values can be, |
| 80 |
/// as they are never able to dereference real memory and thus both |
| 81 |
/// addresses and lengths are meaningless to the memory inspector. |
| 82 |
/// |
| 83 |
/// See `ptr::span` for more information on the encoding scheme used in |
| 84 |
/// references to `BitSlice`. |
| 85 |
_mem: [()], |
| 86 |
} |
| 87 |
|
| 88 |
/// Constructors. |
| 89 |
impl<T, O> BitSlice<T, O> |
| 90 |
where |
| 91 |
T: BitStore, |
| 92 |
O: BitOrder, |
| 93 |
{ |
| 94 |
/// Produces an empty bit-slice with an arbitrary lifetime. |
| 95 |
/// |
| 96 |
/// ## Original |
| 97 |
/// |
| 98 |
/// This is equivalent to the `&[]` literal. |
| 99 |
/// |
| 100 |
/// ## Examples |
| 101 |
/// |
| 102 |
/// ```rust |
| 103 |
/// use bitvec::prelude::*; |
| 104 |
/// |
| 105 |
/// assert!(BitSlice::<u16, LocalBits>::empty().is_empty()); |
| 106 |
/// assert_eq!(bits![], BitSlice::<u8, Msb0>::empty()); |
| 107 |
/// ``` |
| 108 |
#[inline] |
| 109 |
pub fn empty<'a>() -> &'a Self { |
| 110 |
unsafe { BitSpan::<Const, T, O>::EMPTY.into_bitslice_ref() } |
| 111 |
} |
| 112 |
|
| 113 |
/// Produces an empty bit-slice with an arbitrary lifetime. |
| 114 |
/// |
| 115 |
/// ## Original |
| 116 |
/// |
| 117 |
/// This is equivalent to the `&mut []` literal. |
| 118 |
/// |
| 119 |
/// ## Examples |
| 120 |
/// |
| 121 |
/// ```rust |
| 122 |
/// use bitvec::prelude::*; |
| 123 |
/// |
| 124 |
/// assert!(BitSlice::<u16, LocalBits>::empty_mut().is_empty()); |
| 125 |
/// assert_eq!(bits![mut], BitSlice::<u8, Msb0>::empty_mut()); |
| 126 |
/// ``` |
| 127 |
#[inline] |
| 128 |
pub fn empty_mut<'a>() -> &'a mut Self { |
| 129 |
unsafe { BitSpan::<Mut, T, O>::EMPTY.into_bitslice_mut() } |
| 130 |
} |
| 131 |
|
| 132 |
/// Constructs a shared `&BitSlice` reference over a shared element. |
| 133 |
/// |
| 134 |
/// The [`BitView`] trait, implemented on all [`BitStore`] implementors, |
| 135 |
/// provides a [`.view_bits::<O>()`] method which delegates to this function |
| 136 |
/// and may be more convenient for you to write. |
| 137 |
/// |
| 138 |
/// ## Parameters |
| 139 |
/// |
| 140 |
/// - `elem`: A shared reference to a memory element. |
| 141 |
/// |
| 142 |
/// ## Returns |
| 143 |
/// |
| 144 |
/// A shared `&BitSlice` over `elem`. |
| 145 |
/// |
| 146 |
/// ## Examples |
| 147 |
/// |
| 148 |
/// ```rust |
| 149 |
/// use bitvec::prelude::*; |
| 150 |
/// |
| 151 |
/// let elem = 0u8; |
| 152 |
/// let bits = BitSlice::<_, Lsb0>::from_element(&elem); |
| 153 |
/// assert_eq!(bits.len(), 8); |
| 154 |
/// |
| 155 |
/// let bits = elem.view_bits::<Lsb0>(); |
| 156 |
/// ``` |
| 157 |
/// |
| 158 |
/// [`BitStore`]: crate::store::BitStore |
| 159 |
/// [`BitView`]: crate::view::BitView |
| 160 |
/// [`.view_bits::<O>()`]: crate::view::BitView::view_bits |
| 161 |
#[inline] |
| 162 |
pub fn from_element(elem: &T) -> &Self { |
| 163 |
unsafe { |
| 164 |
BitPtr::from_ref(elem) |
| 165 |
.span_unchecked(mem::bits_of::<T::Mem>()) |
| 166 |
.into_bitslice_ref() |
| 167 |
} |
| 168 |
} |
| 169 |
|
| 170 |
/// Constructs an exclusive `&mut BitSlice` reference over an element. |
| 171 |
/// |
| 172 |
/// The [`BitView`] trait, implemented on all [`BitStore`] implementors, |
| 173 |
/// provides a [`.view_bits_mut::<O>()`] method which delegates to this |
| 174 |
/// function and may be more convenient for you to write. |
| 175 |
/// |
| 176 |
/// ## Parameters |
| 177 |
/// |
| 178 |
/// - `elem`: An exclusive reference to a memory element. |
| 179 |
/// |
| 180 |
/// ## Returns |
| 181 |
/// |
| 182 |
/// An exclusive `&mut BitSlice` over `elem`. |
| 183 |
/// |
| 184 |
/// Note that the original `elem` reference will be inaccessible for the |
| 185 |
/// duration of the returned bit-slice handle’s lifetime. |
| 186 |
/// |
| 187 |
/// ## Examples |
| 188 |
/// |
| 189 |
/// ```rust |
| 190 |
/// use bitvec::prelude::*; |
| 191 |
/// |
| 192 |
/// let mut elem = 0u8; |
| 193 |
/// let bits = BitSlice::<_, Lsb0>::from_element_mut(&mut elem); |
| 194 |
/// bits.set(1, true); |
| 195 |
/// assert!(bits[1]); |
| 196 |
/// assert_eq!(elem, 2); |
| 197 |
/// |
| 198 |
/// let bits = elem.view_bits_mut::<Lsb0>(); |
| 199 |
/// ``` |
| 200 |
/// |
| 201 |
/// [`BitStore`]: crate::store::BitStore |
| 202 |
/// [`BitView`]: crate::view::BitView |
| 203 |
/// [`.view_bits_mut::<O>()`]: crate::view::BitView::view_bits_mut |
| 204 |
#[inline] |
| 205 |
pub fn from_element_mut(elem: &mut T) -> &mut Self { |
| 206 |
unsafe { |
| 207 |
BitPtr::from_mut(elem) |
| 208 |
.span_unchecked(mem::bits_of::<T::Mem>()) |
| 209 |
.into_bitslice_mut() |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
/// Constructs a shared `&BitSlice` reference over a slice of elements. |
| 214 |
/// |
| 215 |
/// The [`BitView`] trait, implemented on all `[T]` slices, provides a |
| 216 |
/// [`.view_bits::<O>()`] method which delegates to this function and may be |
| 217 |
/// more convenient for you to write. |
| 218 |
/// |
| 219 |
/// ## Parameters |
| 220 |
/// |
| 221 |
/// - `slice`: A shared reference to a slice of memory elements. |
| 222 |
/// |
| 223 |
/// ## Returns |
| 224 |
/// |
| 225 |
/// A shared `BitSlice` reference over all of `slice`. |
| 226 |
/// |
| 227 |
/// ## Panics |
| 228 |
/// |
| 229 |
/// This will panic if `slice` is too long to encode as a bit-slice view. |
| 230 |
/// |
| 231 |
/// ## Examples |
| 232 |
/// |
| 233 |
/// ```rust |
| 234 |
/// use bitvec::prelude::*; |
| 235 |
/// |
| 236 |
/// let data = [0u16, 1]; |
| 237 |
/// let bits = BitSlice::<_, Lsb0>::from_slice(&data); |
| 238 |
/// assert!(bits[16]); |
| 239 |
/// |
| 240 |
/// let bits = data.view_bits::<Lsb0>(); |
| 241 |
/// ``` |
| 242 |
/// |
| 243 |
/// [`BitView`]: crate::view::BitView |
| 244 |
/// [`.view_bits::<O>()`]: crate::view::BitView::view_bits |
| 245 |
#[inline] |
| 246 |
pub fn from_slice(slice: &[T]) -> &Self { |
| 247 |
Self::try_from_slice(slice).unwrap() |
| 248 |
} |
| 249 |
|
| 250 |
/// Attempts to construct a shared `&BitSlice` reference over a slice of |
| 251 |
/// elements. |
| 252 |
/// |
| 253 |
/// The [`BitView`], implemented on all `[T]` slices, provides a |
| 254 |
/// [`.try_view_bits::<O>()`] method which delegates to this function and |
| 255 |
/// may be more convenient for you to write. |
| 256 |
/// |
| 257 |
/// This is *very hard*, if not impossible, to cause to fail. Rust will not |
| 258 |
/// create excessive arrays on 64-bit architectures. |
| 259 |
/// |
| 260 |
/// ## Parameters |
| 261 |
/// |
| 262 |
/// - `slice`: A shared reference to a slice of memory elements. |
| 263 |
/// |
| 264 |
/// ## Returns |
| 265 |
/// |
| 266 |
/// A shared `&BitSlice` over `slice`. If `slice` is longer than can be |
| 267 |
/// encoded into a `&BitSlice` (see [`MAX_ELTS`]), this will fail and return |
| 268 |
/// the original `slice` as an error. |
| 269 |
/// |
| 270 |
/// ## Examples |
| 271 |
/// |
| 272 |
/// ```rust |
| 273 |
/// use bitvec::prelude::*; |
| 274 |
/// |
| 275 |
/// let data = [0u8, 1]; |
| 276 |
/// let bits = BitSlice::<_, Msb0>::try_from_slice(&data).unwrap(); |
| 277 |
/// assert!(bits[15]); |
| 278 |
/// |
| 279 |
/// let bits = data.try_view_bits::<Msb0>().unwrap(); |
| 280 |
/// ``` |
| 281 |
/// |
| 282 |
/// [`BitView`]: crate::view::BitView |
| 283 |
/// [`MAX_ELTS`]: Self::MAX_ELTS |
| 284 |
/// [`.try_view_bits::<O>()`]: crate::view::BitView::try_view_bits |
| 285 |
#[inline] |
| 286 |
pub fn try_from_slice(slice: &[T]) -> Result<&Self, BitSpanError<T>> { |
| 287 |
let elts = slice.len(); |
| 288 |
if elts >= Self::MAX_ELTS { |
| 289 |
elts.saturating_mul(mem::bits_of::<T::Mem>()) |
| 290 |
.pipe(BitSpanError::TooLong) |
| 291 |
.pipe(Err) |
| 292 |
} |
| 293 |
else { |
| 294 |
Ok(unsafe { Self::from_slice_unchecked(slice) }) |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
/// Constructs an exclusive `&mut BitSlice` reference over a slice of |
| 299 |
/// elements. |
| 300 |
/// |
| 301 |
/// The [`BitView`] trait, implemented on all `[T]` slices, provides a |
| 302 |
/// [`.view_bits_mut::<O>()`] method which delegates to this function and |
| 303 |
/// may be more convenient for you to write. |
| 304 |
/// |
| 305 |
/// ## Parameters |
| 306 |
/// |
| 307 |
/// - `slice`: An exclusive reference to a slice of memory elements. |
| 308 |
/// |
| 309 |
/// ## Returns |
| 310 |
/// |
| 311 |
/// An exclusive `&mut BitSlice` over all of `slice`. |
| 312 |
/// |
| 313 |
/// ## Panics |
| 314 |
/// |
| 315 |
/// This panics if `slice` is too long to encode as a bit-slice view. |
| 316 |
/// |
| 317 |
/// ## Examples |
| 318 |
/// |
| 319 |
/// ```rust |
| 320 |
/// use bitvec::prelude::*; |
| 321 |
/// |
| 322 |
/// let mut data = [0u16; 2]; |
| 323 |
/// let bits = BitSlice::<_, Lsb0>::from_slice_mut(&mut data); |
| 324 |
/// bits.set(0, true); |
| 325 |
/// bits.set(17, true); |
| 326 |
/// assert_eq!(data, [1, 2]); |
| 327 |
/// |
| 328 |
/// let bits = data.view_bits_mut::<Lsb0>(); |
| 329 |
/// ``` |
| 330 |
/// |
| 331 |
/// [`BitView`]: crate::view::BitView |
| 332 |
/// [`.view_bits_mut::<O>()`]: crate::view::BitView::view_bits_mut |
| 333 |
#[inline] |
| 334 |
pub fn from_slice_mut(slice: &mut [T]) -> &mut Self { |
| 335 |
Self::try_from_slice_mut(slice).unwrap() |
| 336 |
} |
| 337 |
|
| 338 |
/// Attempts to construct an exclusive `&mut BitSlice` reference over a |
| 339 |
/// slice of elements. |
| 340 |
/// |
| 341 |
/// The [`BitView`] trait, implemented on all `[T]` slices, provides a |
| 342 |
/// [`.try_view_bits_mut::<O>()`] method which delegates to this function |
| 343 |
/// and may be more convenient for you to write. |
| 344 |
/// |
| 345 |
/// ## Parameters |
| 346 |
/// |
| 347 |
/// - `slice`: An exclusive reference to a slice of memory elements. |
| 348 |
/// |
| 349 |
/// ## Returns |
| 350 |
/// |
| 351 |
/// An exclusive `&mut BitSlice` over `slice`. If `slice` is longer than can |
| 352 |
/// be encoded into a `&mut BitSlice` (see [`MAX_ELTS`]), this will fail and |
| 353 |
/// return the original `slice` as an error. |
| 354 |
/// |
| 355 |
/// ## Examples |
| 356 |
/// |
| 357 |
/// ```rust |
| 358 |
/// use bitvec::prelude::*; |
| 359 |
/// |
| 360 |
/// let mut data = [0u8; 2]; |
| 361 |
/// let bits = BitSlice::<_, Msb0>::try_from_slice_mut(&mut data).unwrap(); |
| 362 |
/// bits.set(7, true); |
| 363 |
/// bits.set(15, true); |
| 364 |
/// assert_eq!(data, [1; 2]); |
| 365 |
/// |
| 366 |
/// let bits = data.try_view_bits_mut::<Msb0>().unwrap(); |
| 367 |
/// ``` |
| 368 |
/// |
| 369 |
/// [`BitView`]: crate::view::BitView |
| 370 |
/// [`MAX_ELTS`]: Self::MAX_ELTS |
| 371 |
/// [`.try_view_bits_mut::<O>()`]: crate::view::BitView::try_view_bits_mut |
| 372 |
#[inline] |
| 373 |
pub fn try_from_slice_mut( |
| 374 |
slice: &mut [T], |
| 375 |
) -> Result<&mut Self, BitSpanError<T>> { |
| 376 |
let elts = slice.len(); |
| 377 |
if elts >= Self::MAX_ELTS { |
| 378 |
elts.saturating_mul(mem::bits_of::<T::Mem>()) |
| 379 |
.pipe(BitSpanError::TooLong) |
| 380 |
.pipe(Err) |
| 381 |
} |
| 382 |
else { |
| 383 |
Ok(unsafe { Self::from_slice_unchecked_mut(slice) }) |
| 384 |
} |
| 385 |
} |
| 386 |
|
| 387 |
/// Constructs a shared `&BitSlice` over an element slice, without checking |
| 388 |
/// its length. |
| 389 |
/// |
| 390 |
/// If `slice` is too long to encode into a `&BitSlice`, then the produced |
| 391 |
/// bit-slice’s length is unspecified. |
| 392 |
/// |
| 393 |
/// ## Safety |
| 394 |
/// |
| 395 |
/// You must ensure that `slice.len() < BitSlice::MAX_ELTS`. |
| 396 |
/// |
| 397 |
/// Calling this function with an over-long slice is **library-level** |
| 398 |
/// undefined behavior. You may not assume anything about its implementation |
| 399 |
/// or behavior, and must conservatively assume that over-long slices cause |
| 400 |
/// compiler UB. |
| 401 |
#[inline] |
| 402 |
pub unsafe fn from_slice_unchecked(slice: &[T]) -> &Self { |
| 403 |
let bits = slice.len().wrapping_mul(mem::bits_of::<T::Mem>()); |
| 404 |
BitPtr::from_slice(slice) |
| 405 |
.span_unchecked(bits) |
| 406 |
.into_bitslice_ref() |
| 407 |
} |
| 408 |
|
| 409 |
/// Constructs an exclusive `&mut BitSlice` over an element slice, without |
| 410 |
/// checking its length. |
| 411 |
/// |
| 412 |
/// If `slice` is too long to encode into a `&mut BitSlice`, then the |
| 413 |
/// produced bit-slice’s length is unspecified. |
| 414 |
/// |
| 415 |
/// ## Safety |
| 416 |
/// |
| 417 |
/// You must ensure that `slice.len() < BitSlice::MAX_ELTS`. |
| 418 |
/// |
| 419 |
/// Calling this function with an over-long slice is **library-level** |
| 420 |
/// undefined behavior. You may not assume anything about its implementation |
| 421 |
/// or behavior, and must conservatively assume that over-long slices cause |
| 422 |
/// compiler UB. |
| 423 |
#[inline] |
| 424 |
pub unsafe fn from_slice_unchecked_mut(slice: &mut [T]) -> &mut Self { |
| 425 |
let bits = slice.len().wrapping_mul(mem::bits_of::<T::Mem>()); |
| 426 |
BitPtr::from_slice_mut(slice) |
| 427 |
.span_unchecked(bits) |
| 428 |
.into_bitslice_mut() |
| 429 |
} |
| 430 |
} |
| 431 |
|
| 432 |
/// Alternates of standard APIs. |
| 433 |
impl<T, O> BitSlice<T, O> |
| 434 |
where |
| 435 |
T: BitStore, |
| 436 |
O: BitOrder, |
| 437 |
{ |
| 438 |
/// Gets a raw pointer to the zeroth bit of the bit-slice. |
| 439 |
/// |
| 440 |
/// ## Original |
| 441 |
/// |
| 442 |
/// [`slice::as_ptr`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_ptr) |
| 443 |
/// |
| 444 |
/// ## API Differences |
| 445 |
/// |
| 446 |
/// This is renamed in order to indicate that it is returning a `bitvec` |
| 447 |
/// structure, not a raw pointer. |
| 448 |
#[inline] |
| 449 |
pub fn as_bitptr(&self) -> BitPtr<Const, T, O> { |
| 450 |
self.as_bitspan().to_bitptr() |
| 451 |
} |
| 452 |
|
| 453 |
/// Gets a raw, write-capable pointer to the zeroth bit of the bit-slice. |
| 454 |
/// |
| 455 |
/// ## Original |
| 456 |
/// |
| 457 |
/// [`slice::as_mut_ptr`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_mut_ptr) |
| 458 |
/// |
| 459 |
/// ## API Differences |
| 460 |
/// |
| 461 |
/// This is renamed in order to indicate that it is returning a `bitvec` |
| 462 |
/// structure, not a raw pointer. |
| 463 |
#[inline] |
| 464 |
pub fn as_mut_bitptr(&mut self) -> BitPtr<Mut, T, O> { |
| 465 |
self.as_mut_bitspan().to_bitptr() |
| 466 |
} |
| 467 |
|
| 468 |
/// Views the bit-slice as a half-open range of bit-pointers, to its first |
| 469 |
/// bit *in* the bit-slice and first bit *beyond* it. |
| 470 |
/// |
| 471 |
/// ## Original |
| 472 |
/// |
| 473 |
/// [`slice::as_ptr_range`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_ptr_range) |
| 474 |
/// |
| 475 |
/// ## API Differences |
| 476 |
/// |
| 477 |
/// This is renamed to indicate that it returns a `bitvec` structure, rather |
| 478 |
/// than an ordinary `Range`. |
| 479 |
/// |
| 480 |
/// ## Notes |
| 481 |
/// |
| 482 |
/// `BitSlice` does define a [`.as_ptr_range()`], which returns a |
| 483 |
/// `Range<BitPtr>`. `BitPtrRange` has additional capabilities that |
| 484 |
/// `Range<*const T>` and `Range<BitPtr>` do not. |
| 485 |
/// |
| 486 |
/// [`.as_ptr_range()`]: Self::as_ptr_range |
| 487 |
#[inline] |
| 488 |
pub fn as_bitptr_range(&self) -> BitPtrRange<Const, T, O> { |
| 489 |
self.as_bitspan().to_bitptr_range() |
| 490 |
} |
| 491 |
|
| 492 |
/// Views the bit-slice as a half-open range of write-capable bit-pointers, |
| 493 |
/// to its first bit *in* the bit-slice and the first bit *beyond* it. |
| 494 |
/// |
| 495 |
/// ## Original |
| 496 |
/// |
| 497 |
/// [`slice::as_mut_ptr_range`](https://doc.rust-lang.org/std/primitive.slice.html#method.as_mut_ptr_range) |
| 498 |
/// |
| 499 |
/// ## API Differences |
| 500 |
/// |
| 501 |
/// This is renamed to indicate that it returns a `bitvec` structure, rather |
| 502 |
/// than an ordinary `Range`. |
| 503 |
/// |
| 504 |
/// ## Notes |
| 505 |
/// |
| 506 |
/// `BitSlice` does define a [`.as_mut_ptr_range()`], which returns a |
| 507 |
/// `Range<BitPtr>`. `BitPtrRange` has additional capabilities that |
| 508 |
/// `Range<*mut T>` and `Range<BitPtr>` do not. |
| 509 |
#[inline] |
| 510 |
pub fn as_mut_bitptr_range(&mut self) -> BitPtrRange<Mut, T, O> { |
| 511 |
self.as_mut_bitspan().to_bitptr_range() |
| 512 |
} |
| 513 |
|
| 514 |
/// Copies the bits from `src` into `self`. |
| 515 |
/// |
| 516 |
/// `self` and `src` must have the same length. |
| 517 |
/// |
| 518 |
/// ## Performance |
| 519 |
/// |
| 520 |
/// If `src` has the same type arguments as `self`, it will use the same |
| 521 |
/// implementation as [`.copy_from_bitslice()`]; if you know that this will |
| 522 |
/// always be the case, you should prefer to use that method directly. |
| 523 |
/// |
| 524 |
/// Only `.copy_from_bitslice()` is *able* to perform acceleration; this |
| 525 |
/// method is *always* required to perform a bit-by-bit crawl over both |
| 526 |
/// bit-slices. |
| 527 |
/// |
| 528 |
/// ## Original |
| 529 |
/// |
| 530 |
/// [`slice::clone_from_slice`](https://doc.rust-lang.org/std/primitive.slice.html#method.clone_from_slice) |
| 531 |
/// |
| 532 |
/// ## API Differences |
| 533 |
/// |
| 534 |
/// This is renamed to reflect that it copies from another bit-slice, not |
| 535 |
/// from an element slice. |
| 536 |
/// |
| 537 |
/// In order to support general usage, it allows `src` to have different |
| 538 |
/// type parameters than `self`, at the cost of performance optimizations. |
| 539 |
/// |
| 540 |
/// ## Panics |
| 541 |
/// |
| 542 |
/// This panics if the two bit-slices have different lengths. |
| 543 |
/// |
| 544 |
/// ## Examples |
| 545 |
/// |
| 546 |
/// ```rust |
| 547 |
/// use bitvec::prelude::*; |
| 548 |
/// ``` |
| 549 |
/// |
| 550 |
/// [`.copy_from_bitslice()`]: Self::copy_from_bitslice |
| 551 |
#[inline] |
| 552 |
pub fn clone_from_bitslice<T2, O2>(&mut self, src: &BitSlice<T2, O2>) |
| 553 |
where |
| 554 |
T2: BitStore, |
| 555 |
O2: BitOrder, |
| 556 |
{ |
| 557 |
assert_eq!( |
| 558 |
self.len(), |
| 559 |
src.len(), |
| 560 |
"cloning between bit-slices requires equal lengths", |
| 561 |
); |
| 562 |
|
| 563 |
if let Some(that) = src.coerce::<T, O>() { |
| 564 |
self.copy_from_bitslice(that); |
| 565 |
} |
| 566 |
// TODO(myrrlyn): Test if `<T::Mem, O>` matches `<T2::Mem, O>` and |
| 567 |
// specialize cloning. |
| 568 |
else { |
| 569 |
for (to, bit) in self.as_mut_bitptr_range().zip(src.iter().by_vals()) |
| 570 |
{ |
| 571 |
unsafe { |
| 572 |
to.write(bit); |
| 573 |
} |
| 574 |
} |
| 575 |
} |
| 576 |
} |
| 577 |
|
| 578 |
/// Copies all bits from `src` into `self`, using batched acceleration when |
| 579 |
/// possible. |
| 580 |
/// |
| 581 |
/// `self` and `src` must have the same length. |
| 582 |
/// |
| 583 |
/// ## Original |
| 584 |
/// |
| 585 |
/// [`slice::copy_from_slice`](https://doc.rust-lang.org/std/primitive.slice.html#method.copy_from_slice) |
| 586 |
/// |
| 587 |
/// ## Panics |
| 588 |
/// |
| 589 |
/// This panics if the two bit-slices have different lengths. |
| 590 |
/// |
| 591 |
/// ## Examples |
| 592 |
/// |
| 593 |
/// ```rust |
| 594 |
/// use bitvec::prelude::*; |
| 595 |
/// ``` |
| 596 |
#[inline] |
| 597 |
pub fn copy_from_bitslice(&mut self, src: &Self) { |
| 598 |
assert_eq!( |
| 599 |
self.len(), |
| 600 |
src.len(), |
| 601 |
"copying between bit-slices requires equal lengths", |
| 602 |
); |
| 603 |
|
| 604 |
let (to_head, from_head) = |
| 605 |
(self.as_bitspan().head(), src.as_bitspan().head()); |
| 606 |
if to_head == from_head { |
| 607 |
match (self.domain_mut(), src.domain()) { |
| 608 |
(Domain::Enclave(mut to), Domain::Enclave(from)) => { |
| 609 |
to.store_value(from.load_value()); |
| 610 |
}, |
| 611 |
( |
| 612 |
Domain::Region { |
| 613 |
head: to_head, |
| 614 |
body: to_body, |
| 615 |
tail: to_tail, |
| 616 |
}, |
| 617 |
Domain::Region { |
| 618 |
head: from_head, |
| 619 |
body: from_body, |
| 620 |
tail: from_tail, |
| 621 |
}, |
| 622 |
) => { |
| 623 |
if let (Some(mut to), Some(from)) = (to_head, from_head) { |
| 624 |
to.store_value(from.load_value()); |
| 625 |
} |
| 626 |
for (to, from) in to_body.iter_mut().zip(from_body) { |
| 627 |
to.store_value(from.load_value()); |
| 628 |
} |
| 629 |
if let (Some(mut to), Some(from)) = (to_tail, from_tail) { |
| 630 |
to.store_value(from.load_value()); |
| 631 |
} |
| 632 |
}, |
| 633 |
_ => unreachable!( |
| 634 |
"bit-slices with equal type parameters, lengths, and heads \ |
| 635 |
will always have equal domains" |
| 636 |
), |
| 637 |
} |
| 638 |
} |
| 639 |
if let (Some(this), Some(that)) = |
| 640 |
(self.coerce_mut::<T, Lsb0>(), src.coerce::<T, Lsb0>()) |
| 641 |
{ |
| 642 |
return this.sp_copy_from_bitslice(that); |
| 643 |
} |
| 644 |
if let (Some(this), Some(that)) = |
| 645 |
(self.coerce_mut::<T, Msb0>(), src.coerce::<T, Msb0>()) |
| 646 |
{ |
| 647 |
return this.sp_copy_from_bitslice(that); |
| 648 |
} |
| 649 |
for (to, bit) in self.as_mut_bitptr_range().zip(src.iter().by_vals()) { |
| 650 |
unsafe { |
| 651 |
to.write(bit); |
| 652 |
} |
| 653 |
} |
| 654 |
} |
| 655 |
|
| 656 |
/// Swaps the contents of two bit-slices. |
| 657 |
/// |
| 658 |
/// `self` and `other` must have the same length. |
| 659 |
/// |
| 660 |
/// ## Original |
| 661 |
/// |
| 662 |
/// [`slice::swap_with_slice`](https://doc.rust-lang.org/std/primitive.slice.html#method.swap_with_slice) |
| 663 |
/// |
| 664 |
/// ## API Differences |
| 665 |
/// |
| 666 |
/// This method is renamed, as it takes a bit-slice rather than an element |
| 667 |
/// slice. |
| 668 |
/// |
| 669 |
/// ## Panics |
| 670 |
/// |
| 671 |
/// This panics if the two bit-slices have different lengths. |
| 672 |
/// |
| 673 |
/// ## Examples |
| 674 |
/// |
| 675 |
/// ```rust |
| 676 |
/// use bitvec::prelude::*; |
| 677 |
/// |
| 678 |
/// let mut one = [0xA5u8, 0x69]; |
| 679 |
/// let mut two = 0x1234u16; |
| 680 |
/// let one_bits = one.view_bits_mut::<Msb0>(); |
| 681 |
/// let two_bits = two.view_bits_mut::<Lsb0>(); |
| 682 |
/// |
| 683 |
/// one_bits.swap_with_bitslice(two_bits); |
| 684 |
/// |
| 685 |
/// assert_eq!(one, [0x2C, 0x48]); |
| 686 |
/// # if cfg!(target_endian = "little") { |
| 687 |
/// assert_eq!(two, 0x96A5); |
| 688 |
/// # } |
| 689 |
/// ``` |
| 690 |
#[inline] |
| 691 |
pub fn swap_with_bitslice<T2, O2>(&mut self, other: &mut BitSlice<T2, O2>) |
| 692 |
where |
| 693 |
T2: BitStore, |
| 694 |
O2: BitOrder, |
| 695 |
{ |
| 696 |
assert_eq!( |
| 697 |
self.len(), |
| 698 |
other.len(), |
| 699 |
"swapping between bit-slices requires equal lengths", |
| 700 |
); |
| 701 |
|
| 702 |
if let (Some(this), Some(that)) = |
| 703 |
(self.coerce_mut::<T, Lsb0>(), other.coerce_mut::<T, Lsb0>()) |
| 704 |
{ |
| 705 |
return this.sp_swap_with_bitslice(that); |
| 706 |
} |
| 707 |
if let (Some(this), Some(that)) = |
| 708 |
(self.coerce_mut::<T, Msb0>(), other.coerce_mut::<T, Msb0>()) |
| 709 |
{ |
| 710 |
return this.sp_swap_with_bitslice(that); |
| 711 |
} |
| 712 |
self.as_mut_bitptr_range() |
| 713 |
.zip(other.as_mut_bitptr_range()) |
| 714 |
.for_each(|(a, b)| unsafe { |
| 715 |
bv_ptr::swap(a, b); |
| 716 |
}); |
| 717 |
} |
| 718 |
} |
| 719 |
|
| 720 |
/// Extensions of standard APIs. |
| 721 |
impl<T, O> BitSlice<T, O> |
| 722 |
where |
| 723 |
T: BitStore, |
| 724 |
O: BitOrder, |
| 725 |
{ |
| 726 |
/// Writes a new value into a single bit. |
| 727 |
/// |
| 728 |
/// This is the replacement for `*slice[index] = value;`, as `bitvec` is not |
| 729 |
/// able to express that under the current `IndexMut` API signature. |
| 730 |
/// |
| 731 |
/// ## Parameters |
| 732 |
/// |
| 733 |
/// - `&mut self` |
| 734 |
/// - `index`: The bit-index to set. It must be in `0 .. self.len()`. |
| 735 |
/// - `value`: The new bit-value to write into the bit at `index`. |
| 736 |
/// |
| 737 |
/// ## Panics |
| 738 |
/// |
| 739 |
/// This panics if `index` is out of bounds. |
| 740 |
/// |
| 741 |
/// ## Examples |
| 742 |
/// |
| 743 |
/// ```rust |
| 744 |
/// use bitvec::prelude::*; |
| 745 |
/// |
| 746 |
/// let bits = bits![mut 0, 1]; |
| 747 |
/// bits.set(0, true); |
| 748 |
/// bits.set(1, false); |
| 749 |
/// |
| 750 |
/// assert_eq!(bits, bits![1, 0]); |
| 751 |
/// ``` |
| 752 |
#[inline] |
| 753 |
pub fn set(&mut self, index: usize, value: bool) { |
| 754 |
self.replace(index, value); |
| 755 |
} |
| 756 |
|
| 757 |
/// Writes a new value into a single bit, without bounds checking. |
| 758 |
/// |
| 759 |
/// ## Parameters |
| 760 |
/// |
| 761 |
/// - `&mut self` |
| 762 |
/// - `index`: The bit-index to set. It must be in `0 .. self.len()`. |
| 763 |
/// - `value`: The new bit-value to write into the bit at `index`. |
| 764 |
/// |
| 765 |
/// ## Safety |
| 766 |
/// |
| 767 |
/// You must ensure that `index` is in the range `0 .. self.len()`. |
| 768 |
/// |
| 769 |
/// This performs bit-pointer offset arithmetic without doing any bounds |
| 770 |
/// checks. If `index` is out of bounds, then this will issue an |
| 771 |
/// out-of-bounds access and will trigger memory unsafety. |
| 772 |
/// |
| 773 |
/// ## Examples |
| 774 |
/// |
| 775 |
/// ```rust |
| 776 |
/// use bitvec::prelude::*; |
| 777 |
/// |
| 778 |
/// let mut data = 0u8; |
| 779 |
/// let bits = &mut data.view_bits_mut::<Lsb0>()[.. 2]; |
| 780 |
/// assert_eq!(bits.len(), 2); |
| 781 |
/// unsafe { |
| 782 |
/// bits.set_unchecked(3, true); |
| 783 |
/// } |
| 784 |
/// assert_eq!(data, 8); |
| 785 |
/// ``` |
| 786 |
#[inline] |
| 787 |
pub unsafe fn set_unchecked(&mut self, index: usize, value: bool) { |
| 788 |
self.replace_unchecked(index, value); |
| 789 |
} |
| 790 |
|
| 791 |
/// Writes a new value into a bit, and returns its previous value. |
| 792 |
/// |
| 793 |
/// ## Panics |
| 794 |
/// |
| 795 |
/// This panics if `index` is not less than `self.len()`. |
| 796 |
/// |
| 797 |
/// ## Examples |
| 798 |
/// |
| 799 |
/// ```rust |
| 800 |
/// use bitvec::prelude::*; |
| 801 |
/// |
| 802 |
/// let bits = bits![mut 0]; |
| 803 |
/// assert!(!bits.replace(0, true)); |
| 804 |
/// assert!(bits[0]); |
| 805 |
/// ``` |
| 806 |
#[inline] |
| 807 |
pub fn replace(&mut self, index: usize, value: bool) -> bool { |
| 808 |
self.assert_in_bounds(index, 0 .. self.len()); |
| 809 |
unsafe { self.replace_unchecked(index, value) } |
| 810 |
} |
| 811 |
|
| 812 |
/// Writes a new value into a bit, returning the previous value, without |
| 813 |
/// bounds checking. |
| 814 |
/// |
| 815 |
/// ## Safety |
| 816 |
/// |
| 817 |
/// `index` must be less than `self.len()`. |
| 818 |
/// |
| 819 |
/// ## Examples |
| 820 |
/// |
| 821 |
/// ```rust |
| 822 |
/// use bitvec::prelude::*; |
| 823 |
/// |
| 824 |
/// let bits = bits![mut 0, 0]; |
| 825 |
/// let old = unsafe { |
| 826 |
/// let a = &mut bits[.. 1]; |
| 827 |
/// a.replace_unchecked(1, true) |
| 828 |
/// }; |
| 829 |
/// assert!(!old); |
| 830 |
/// assert!(bits[1]); |
| 831 |
/// ``` |
| 832 |
#[inline] |
| 833 |
pub unsafe fn replace_unchecked( |
| 834 |
&mut self, |
| 835 |
index: usize, |
| 836 |
value: bool, |
| 837 |
) -> bool { |
| 838 |
self.as_mut_bitptr().add(index).replace(value) |
| 839 |
} |
| 840 |
|
| 841 |
/// Swaps two bits in a bit-slice, without bounds checking. |
| 842 |
/// |
| 843 |
/// See [`.swap()`] for documentation. |
| 844 |
/// |
| 845 |
/// ## Safety |
| 846 |
/// |
| 847 |
/// You must ensure that `a` and `b` are both in the range `0 .. |
| 848 |
/// self.len()`. |
| 849 |
/// |
| 850 |
/// This method performs bit-pointer offset arithmetic without doing any |
| 851 |
/// bounds checks. If `a` or `b` are out of bounds, then this will issue an |
| 852 |
/// out-of-bounds access and will trigger memory unsafety. |
| 853 |
/// |
| 854 |
/// [`.swap()`]: Self::swap |
| 855 |
#[inline] |
| 856 |
pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize) { |
| 857 |
let a = self.as_mut_bitptr().add(a); |
| 858 |
let b = self.as_mut_bitptr().add(b); |
| 859 |
bv_ptr::swap(a, b); |
| 860 |
} |
| 861 |
|
| 862 |
/// Splits a bit-slice at an index, without bounds checking. |
| 863 |
/// |
| 864 |
/// See [`.split_at()`] for documentation. |
| 865 |
/// |
| 866 |
/// ## Safety |
| 867 |
/// |
| 868 |
/// You must ensure that `mid` is in the range `0 ..= self.len()`. |
| 869 |
/// |
| 870 |
/// This method produces new bit-slice references. If `mid` is out of |
| 871 |
/// bounds, its behavior is **library-level** undefined. You must |
| 872 |
/// conservatively assume that an out-of-bounds split point produces |
| 873 |
/// compiler-level UB. |
| 874 |
/// |
| 875 |
/// [`.split_at()`]: Self::split_at |
| 876 |
#[inline] |
| 877 |
pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&Self, &Self) { |
| 878 |
let len = self.len(); |
| 879 |
let left = self.as_bitptr(); |
| 880 |
let right = left.add(mid); |
| 881 |
let left = left.span_unchecked(mid); |
| 882 |
let right = right.span_unchecked(len - mid); |
| 883 |
let left = left.into_bitslice_ref(); |
| 884 |
let right = right.into_bitslice_ref(); |
| 885 |
(left, right) |
| 886 |
} |
| 887 |
|
| 888 |
/// Splits a mutable bit-slice at an index, without bounds checking. |
| 889 |
/// |
| 890 |
/// See [`.split_at_mut()`] for documentation. |
| 891 |
/// |
| 892 |
/// ## Safety |
| 893 |
/// |
| 894 |
/// You must ensure that `mid` is in the range `0 ..= self.len()`. |
| 895 |
/// |
| 896 |
/// This method produces new bit-slice references. If `mid` is out of |
| 897 |
/// bounds, its behavior is **library-level** undefined. You must |
| 898 |
/// conservatively assume that an out-of-bounds split point produces |
| 899 |
/// compiler-level UB. |
| 900 |
/// |
| 901 |
/// [`.split_at_mut()`]: Self::split_at_mut |
| 902 |
#[inline] |
| 903 |
pub unsafe fn split_at_unchecked_mut( |
| 904 |
&mut self, |
| 905 |
mid: usize, |
| 906 |
) -> (&mut BitSlice<T::Alias, O>, &mut BitSlice<T::Alias, O>) { |
| 907 |
let len = self.len(); |
| 908 |
let left = self.alias_mut().as_mut_bitptr(); |
| 909 |
let right = left.add(mid); |
| 910 |
( |
| 911 |
left.span_unchecked(mid).into_bitslice_mut(), |
| 912 |
right.span_unchecked(len - mid).into_bitslice_mut(), |
| 913 |
) |
| 914 |
} |
| 915 |
|
| 916 |
/// Copies bits from one region of the bit-slice to another region of |
| 917 |
/// itself, without doing bounds checks. |
| 918 |
/// |
| 919 |
/// The regions are allowed to overlap. |
| 920 |
/// |
| 921 |
/// ## Parameters |
| 922 |
/// |
| 923 |
/// - `&mut self` |
| 924 |
/// - `src`: The range within `self` from which to copy. |
| 925 |
/// - `dst`: The starting index within `self` at which to paste. |
| 926 |
/// |
| 927 |
/// ## Effects |
| 928 |
/// |
| 929 |
/// `self[src]` is copied to `self[dest .. dest + src.len()]`. The bits of |
| 930 |
/// `self[src]` are in an unspecified, but initialized, state. |
| 931 |
/// |
| 932 |
/// ## Safety |
| 933 |
/// |
| 934 |
/// `src.end()` and `dest + src.len()` must be entirely within bounds. |
| 935 |
/// |
| 936 |
/// ## Examples |
| 937 |
/// |
| 938 |
/// ```rust |
| 939 |
/// use bitvec::prelude::*; |
| 940 |
/// |
| 941 |
/// let mut data = 0b1011_0000u8; |
| 942 |
/// let bits = data.view_bits_mut::<Msb0>(); |
| 943 |
/// |
| 944 |
/// unsafe { |
| 945 |
/// bits.copy_within_unchecked(.. 4, 2); |
| 946 |
/// } |
| 947 |
/// assert_eq!(data, 0b1010_1100); |
| 948 |
/// ``` |
| 949 |
#[inline] |
| 950 |
pub unsafe fn copy_within_unchecked<R>(&mut self, src: R, dest: usize) |
| 951 |
where R: RangeExt<usize> { |
| 952 |
if let Some(this) = self.coerce_mut::<T, Lsb0>() { |
| 953 |
return this.sp_copy_within_unchecked(src, dest); |
| 954 |
} |
| 955 |
if let Some(this) = self.coerce_mut::<T, Msb0>() { |
| 956 |
return this.sp_copy_within_unchecked(src, dest); |
| 957 |
} |
| 958 |
let source = src.normalize(0, self.len()); |
| 959 |
let source_len = source.len(); |
| 960 |
let rev = source.contains(&dest); |
| 961 |
let dest = dest .. dest + source_len; |
| 962 |
for (from, to) in self |
| 963 |
.get_unchecked(source) |
| 964 |
.as_bitptr_range() |
| 965 |
.zip(self.get_unchecked_mut(dest).as_mut_bitptr_range()) |
| 966 |
.bidi(rev) |
| 967 |
{ |
| 968 |
to.write(from.read()); |
| 969 |
} |
| 970 |
} |
| 971 |
|
| 972 |
#[inline] |
| 973 |
#[doc(hidden)] |
| 974 |
#[cfg(not(tarpaulin_include))] |
| 975 |
#[deprecated = "use `.iter_mut().enumerate()`"] |
| 976 |
pub fn for_each(&mut self, mut func: impl FnMut(usize, bool) -> bool) { |
| 977 |
for (idx, ptr) in self.as_mut_bitptr_range().enumerate() { |
| 978 |
unsafe { |
| 979 |
ptr.write(func(idx, ptr.read())); |
| 980 |
} |
| 981 |
} |
| 982 |
} |
| 983 |
} |
| 984 |
|
| 985 |
/// Views of underlying memory. |
| 986 |
impl<T, O> BitSlice<T, O> |
| 987 |
where |
| 988 |
T: BitStore, |
| 989 |
O: BitOrder, |
| 990 |
{ |
| 991 |
/// Partitions a bit-slice into maybe-contended and known-uncontended parts. |
| 992 |
/// |
| 993 |
/// The documentation of `BitDomain` goes into this in more detail. In |
| 994 |
/// short, this produces a `&BitSlice` that is as large as possible without |
| 995 |
/// requiring alias protection, as well as any bits that were not able to be |
| 996 |
/// included in the unaliased bit-slice. |
| 997 |
#[inline] |
| 998 |
#[cfg(not(tarpaulin_include))] |
| 999 |
pub fn bit_domain(&self) -> BitDomain<Const, T, O> { |
| 1000 |
self.domain().into_bit_domain() |
| 1001 |
} |
| 1002 |
|
| 1003 |
/// Partitions a mutable bit-slice into maybe-contended and |
| 1004 |
/// known-uncontended parts. |
| 1005 |
/// |
| 1006 |
/// The documentation of `BitDomain` goes into this in more detail. In |
| 1007 |
/// short, this produces a `&mut BitSlice` that is as large as possible |
| 1008 |
/// without requiring alias protection, as well as any bits that were not |
| 1009 |
/// able to be included in the unaliased bit-slice. |
| 1010 |
#[inline] |
| 1011 |
#[cfg(not(tarpaulin_include))] |
| 1012 |
pub fn bit_domain_mut(&mut self) -> BitDomain<Mut, T, O> { |
| 1013 |
self.domain_mut().into_bit_domain() |
| 1014 |
} |
| 1015 |
|
| 1016 |
/// Views the underlying memory of a bit-slice, removing alias protections |
| 1017 |
/// where possible. |
| 1018 |
/// |
| 1019 |
/// The documentation of `Domain` goes into this in more detail. In short, |
| 1020 |
/// this produces a `&[T]` slice with alias protections removed, covering |
| 1021 |
/// all elements that `self` completely fills. Partially-used elements on |
| 1022 |
/// either the front or back edge of the slice are returned separately. |
| 1023 |
#[inline] |
| 1024 |
#[cfg(not(tarpaulin_include))] |
| 1025 |
pub fn domain(&self) -> Domain<Const, T, O> { |
| 1026 |
Domain::new(self) |
| 1027 |
} |
| 1028 |
|
| 1029 |
/// Views the underlying memory of a bit-slice, removing alias protections |
| 1030 |
/// where possible. |
| 1031 |
/// |
| 1032 |
/// The documentation of `Domain` goes into this in more detail. In short, |
| 1033 |
/// this produces a `&mut [T]` slice with alias protections removed, |
| 1034 |
/// covering all elements that `self` completely fills. Partially-used |
| 1035 |
/// elements on the front or back edge of the slice are returned separately. |
| 1036 |
#[inline] |
| 1037 |
#[cfg(not(tarpaulin_include))] |
| 1038 |
pub fn domain_mut(&mut self) -> Domain<Mut, T, O> { |
| 1039 |
Domain::new(self) |
| 1040 |
} |
| 1041 |
} |
| 1042 |
|
| 1043 |
/// Bit-value queries. |
| 1044 |
impl<T, O> BitSlice<T, O> |
| 1045 |
where |
| 1046 |
T: BitStore, |
| 1047 |
O: BitOrder, |
| 1048 |
{ |
| 1049 |
/// Counts the number of bits set to `1` in the bit-slice contents. |
| 1050 |
/// |
| 1051 |
/// ## Examples |
| 1052 |
/// |
| 1053 |
/// ```rust |
| 1054 |
/// use bitvec::prelude::*; |
| 1055 |
/// |
| 1056 |
/// let bits = bits![1, 1, 0, 0]; |
| 1057 |
/// assert_eq!(bits[.. 2].count_ones(), 2); |
| 1058 |
/// assert_eq!(bits[2 ..].count_ones(), 0); |
| 1059 |
/// assert_eq!(bits![].count_ones(), 0); |
| 1060 |
/// ``` |
| 1061 |
#[inline] |
| 1062 |
pub fn count_ones(&self) -> usize { |
| 1063 |
match self.domain() { |
| 1064 |
Domain::Enclave(elem) => elem.load_value().count_ones() as usize, |
| 1065 |
Domain::Region { head, body, tail } => { |
| 1066 |
head.map_or(0, |elem| elem.load_value().count_ones() as usize) |
| 1067 |
+ body |
| 1068 |
.iter() |
| 1069 |
.map(BitStore::load_value) |
| 1070 |
.map(|elem| elem.count_ones() as usize) |
| 1071 |
.sum::<usize>() + tail |
| 1072 |
.map_or(0, |elem| elem.load_value().count_ones() as usize) |
| 1073 |
}, |
| 1074 |
} |
| 1075 |
} |
| 1076 |
|
| 1077 |
/// Counts the number of bits cleared to `0` in the bit-slice contents. |
| 1078 |
/// |
| 1079 |
/// ## Examples |
| 1080 |
/// |
| 1081 |
/// ```rust |
| 1082 |
/// use bitvec::prelude::*; |
| 1083 |
/// |
| 1084 |
/// let bits = bits![1, 1, 0, 0]; |
| 1085 |
/// assert_eq!(bits[.. 2].count_zeros(), 0); |
| 1086 |
/// assert_eq!(bits[2 ..].count_zeros(), 2); |
| 1087 |
/// assert_eq!(bits![].count_zeros(), 0); |
| 1088 |
/// ``` |
| 1089 |
#[inline] |
| 1090 |
pub fn count_zeros(&self) -> usize { |
| 1091 |
match self.domain() { |
| 1092 |
Domain::Enclave(elem) => (elem.load_value() |
| 1093 |
| !elem.mask().into_inner()) |
| 1094 |
.count_zeros() as usize, |
| 1095 |
Domain::Region { head, body, tail } => { |
| 1096 |
head.map_or(0, |elem| { |
| 1097 |
(elem.load_value() | !elem.mask().into_inner()).count_zeros() |
| 1098 |
as usize |
| 1099 |
}) + body |
| 1100 |
.iter() |
| 1101 |
.map(BitStore::load_value) |
| 1102 |
.map(|elem| elem.count_zeros() as usize) |
| 1103 |
.sum::<usize>() + tail.map_or(0, |elem| { |
| 1104 |
(elem.load_value() | !elem.mask().into_inner()).count_zeros() |
| 1105 |
as usize |
| 1106 |
}) |
| 1107 |
}, |
| 1108 |
} |
| 1109 |
} |
| 1110 |
|
| 1111 |
/// Enumerates the index of each bit in a bit-slice set to `1`. |
| 1112 |
/// |
| 1113 |
/// This is a shorthand for a `.enumerate().filter_map()` iterator that |
| 1114 |
/// selects the index of each `true` bit; however, its implementation is |
| 1115 |
/// eligible for optimizations that the individual-bit iterator is not. |
| 1116 |
/// |
| 1117 |
/// Specializations for the `Lsb0` and `Msb0` orderings allow processors |
| 1118 |
/// with instructions that seek particular bits within an element to operate |
| 1119 |
/// on whole elements, rather than on each bit individually. |
| 1120 |
/// |
| 1121 |
/// ## Examples |
| 1122 |
/// |
| 1123 |
/// This example uses `.iter_ones()`, a `.filter_map()` that finds the index |
| 1124 |
/// of each set bit, and the known indices, in order to show that they have |
| 1125 |
/// equivalent behavior. |
| 1126 |
/// |
| 1127 |
/// ```rust |
| 1128 |
/// use bitvec::prelude::*; |
| 1129 |
/// |
| 1130 |
/// let bits = bits![0, 1, 0, 0, 1, 0, 0, 0, 1]; |
| 1131 |
/// |
| 1132 |
/// let iter_ones = bits.iter_ones(); |
| 1133 |
/// let known_indices = [1, 4, 8].iter().copied(); |
| 1134 |
/// let filter = bits.iter() |
| 1135 |
/// .by_vals() |
| 1136 |
/// .enumerate() |
| 1137 |
/// .filter_map(|(idx, bit)| if bit { Some(idx) } else { None }); |
| 1138 |
/// let all = iter_ones.zip(known_indices).zip(filter); |
| 1139 |
/// |
| 1140 |
/// for ((iter_one, known), filtered) in all { |
| 1141 |
/// assert_eq!(iter_one, known); |
| 1142 |
/// assert_eq!(known, filtered); |
| 1143 |
/// } |
| 1144 |
/// ``` |
| 1145 |
#[inline] |
| 1146 |
pub fn iter_ones(&self) -> IterOnes<T, O> { |
| 1147 |
IterOnes::new(self) |
| 1148 |
} |
| 1149 |
|
| 1150 |
/// Enumerates the index of each bit in a bit-slice cleared to `0`. |
| 1151 |
/// |
| 1152 |
/// This is a shorthand for a `.enumerate().filter_map()` iterator that |
| 1153 |
/// selects the index of each `false` bit; however, its implementation is |
| 1154 |
/// eligible for optimizations that the individual-bit iterator is not. |
| 1155 |
/// |
| 1156 |
/// Specializations for the `Lsb0` and `Msb0` orderings allow processors |
| 1157 |
/// with instructions that seek particular bits within an element to operate |
| 1158 |
/// on whole elements, rather than on each bit individually. |
| 1159 |
/// |
| 1160 |
/// ## Examples |
| 1161 |
/// |
| 1162 |
/// This example uses `.iter_zeros()`, a `.filter_map()` that finds the |
| 1163 |
/// index of each cleared bit, and the known indices, in order to show that |
| 1164 |
/// they have equivalent behavior. |
| 1165 |
/// |
| 1166 |
/// ```rust |
| 1167 |
/// use bitvec::prelude::*; |
| 1168 |
/// |
| 1169 |
/// let bits = bits![1, 0, 1, 1, 0, 1, 1, 1, 0]; |
| 1170 |
/// |
| 1171 |
/// let iter_zeros = bits.iter_zeros(); |
| 1172 |
/// let known_indices = [1, 4, 8].iter().copied(); |
| 1173 |
/// let filter = bits.iter() |
| 1174 |
/// .by_vals() |
| 1175 |
/// .enumerate() |
| 1176 |
/// .filter_map(|(idx, bit)| if !bit { Some(idx) } else { None }); |
| 1177 |
/// let all = iter_zeros.zip(known_indices).zip(filter); |
| 1178 |
/// |
| 1179 |
/// for ((iter_zero, known), filtered) in all { |
| 1180 |
/// assert_eq!(iter_zero, known); |
| 1181 |
/// assert_eq!(known, filtered); |
| 1182 |
/// } |
| 1183 |
/// ``` |
| 1184 |
#[inline] |
| 1185 |
pub fn iter_zeros(&self) -> IterZeros<T, O> { |
| 1186 |
IterZeros::new(self) |
| 1187 |
} |
| 1188 |
|
| 1189 |
/// Finds the index of the first bit in the bit-slice set to `1`. |
| 1190 |
/// |
| 1191 |
/// Returns `None` if there is no `true` bit in the bit-slice. |
| 1192 |
/// |
| 1193 |
/// ## Examples |
| 1194 |
/// |
| 1195 |
/// ```rust |
| 1196 |
/// use bitvec::prelude::*; |
| 1197 |
/// |
| 1198 |
/// assert!(bits![].first_one().is_none()); |
| 1199 |
/// assert!(bits![0].first_one().is_none()); |
| 1200 |
/// assert_eq!(bits![0, 1].first_one(), Some(1)); |
| 1201 |
/// ``` |
| 1202 |
#[inline] |
| 1203 |
pub fn first_one(&self) -> Option<usize> { |
| 1204 |
self.iter_ones().next() |
| 1205 |
} |
| 1206 |
|
| 1207 |
/// Finds the index of the first bit in the bit-slice cleared to `0`. |
| 1208 |
/// |
| 1209 |
/// Returns `None` if there is no `false` bit in the bit-slice. |
| 1210 |
/// |
| 1211 |
/// ## Examples |
| 1212 |
/// |
| 1213 |
/// ```rust |
| 1214 |
/// use bitvec::prelude::*; |
| 1215 |
/// |
| 1216 |
/// assert!(bits![].first_zero().is_none()); |
| 1217 |
/// assert!(bits![1].first_zero().is_none()); |
| 1218 |
/// assert_eq!(bits![1, 0].first_zero(), Some(1)); |
| 1219 |
/// ``` |
| 1220 |
#[inline] |
| 1221 |
pub fn first_zero(&self) -> Option<usize> { |
| 1222 |
self.iter_zeros().next() |
| 1223 |
} |
| 1224 |
|
| 1225 |
/// Finds the index of the last bit in the bit-slice set to `1`. |
| 1226 |
/// |
| 1227 |
/// Returns `None` if there is no `true` bit in the bit-slice. |
| 1228 |
/// |
| 1229 |
/// ## Examples |
| 1230 |
/// |
| 1231 |
/// ```rust |
| 1232 |
/// use bitvec::prelude::*; |
| 1233 |
/// |
| 1234 |
/// assert!(bits![].last_one().is_none()); |
| 1235 |
/// assert!(bits![0].last_one().is_none()); |
| 1236 |
/// assert_eq!(bits![1, 0].last_one(), Some(0)); |
| 1237 |
/// ``` |
| 1238 |
#[inline] |
| 1239 |
pub fn last_one(&self) -> Option<usize> { |
| 1240 |
self.iter_ones().next_back() |
| 1241 |
} |
| 1242 |
|
| 1243 |
/// Finds the index of the last bit in the bit-slice cleared to `0`. |
| 1244 |
/// |
| 1245 |
/// Returns `None` if there is no `false` bit in the bit-slice. |
| 1246 |
/// |
| 1247 |
/// ## Examples |
| 1248 |
/// |
| 1249 |
/// ```rust |
| 1250 |
/// use bitvec::prelude::*; |
| 1251 |
/// |
| 1252 |
/// assert!(bits![].last_zero().is_none()); |
| 1253 |
/// assert!(bits![1].last_zero().is_none()); |
| 1254 |
/// assert_eq!(bits![0, 1].last_zero(), Some(0)); |
| 1255 |
/// ``` |
| 1256 |
#[inline] |
| 1257 |
pub fn last_zero(&self) -> Option<usize> { |
| 1258 |
self.iter_zeros().next_back() |
| 1259 |
} |
| 1260 |
|
| 1261 |
/// Counts the number of bits from the start of the bit-slice to the first |
| 1262 |
/// bit set to `0`. |
| 1263 |
/// |
| 1264 |
/// This returns `0` if the bit-slice is empty. |
| 1265 |
/// |
| 1266 |
/// ## Examples |
| 1267 |
/// |
| 1268 |
/// ```rust |
| 1269 |
/// use bitvec::prelude::*; |
| 1270 |
/// |
| 1271 |
/// assert_eq!(bits![].leading_ones(), 0); |
| 1272 |
/// assert_eq!(bits![0].leading_ones(), 0); |
| 1273 |
/// assert_eq!(bits![1, 0].leading_ones(), 1); |
| 1274 |
/// ``` |
| 1275 |
#[inline] |
| 1276 |
pub fn leading_ones(&self) -> usize { |
| 1277 |
self.first_zero().unwrap_or_else(|| self.len()) |
| 1278 |
} |
| 1279 |
|
| 1280 |
/// Counts the number of bits from the start of the bit-slice to the first |
| 1281 |
/// bit set to `1`. |
| 1282 |
/// |
| 1283 |
/// This returns `0` if the bit-slice is empty. |
| 1284 |
/// |
| 1285 |
/// ## Examples |
| 1286 |
/// |
| 1287 |
/// ```rust |
| 1288 |
/// use bitvec::prelude::*; |
| 1289 |
/// |
| 1290 |
/// assert_eq!(bits![].leading_zeros(), 0); |
| 1291 |
/// assert_eq!(bits![1].leading_zeros(), 0); |
| 1292 |
/// assert_eq!(bits![0, 1].leading_zeros(), 1); |
| 1293 |
/// ``` |
| 1294 |
#[inline] |
| 1295 |
pub fn leading_zeros(&self) -> usize { |
| 1296 |
self.first_one().unwrap_or_else(|| self.len()) |
| 1297 |
} |
| 1298 |
|
| 1299 |
/// Counts the number of bits from the end of the bit-slice to the last bit |
| 1300 |
/// set to `0`. |
| 1301 |
/// |
| 1302 |
/// This returns `0` if the bit-slice is empty. |
| 1303 |
/// |
| 1304 |
/// ## Examples |
| 1305 |
/// |
| 1306 |
/// ```rust |
| 1307 |
/// use bitvec::prelude::*; |
| 1308 |
/// |
| 1309 |
/// assert_eq!(bits![].trailing_ones(), 0); |
| 1310 |
/// assert_eq!(bits![0].trailing_ones(), 0); |
| 1311 |
/// assert_eq!(bits![0, 1].trailing_ones(), 1); |
| 1312 |
/// ``` |
| 1313 |
#[inline] |
| 1314 |
pub fn trailing_ones(&self) -> usize { |
| 1315 |
let len = self.len(); |
| 1316 |
self.last_zero().map(|idx| len - 1 - idx).unwrap_or(len) |
| 1317 |
} |
| 1318 |
|
| 1319 |
/// Counts the number of bits from the end of the bit-slice to the last bit |
| 1320 |
/// set to `1`. |
| 1321 |
/// |
| 1322 |
/// This returns `0` if the bit-slice is empty. |
| 1323 |
/// |
| 1324 |
/// ## Examples |
| 1325 |
/// |
| 1326 |
/// ```rust |
| 1327 |
/// use bitvec::prelude::*; |
| 1328 |
/// |
| 1329 |
/// assert_eq!(bits![].trailing_zeros(), 0); |
| 1330 |
/// assert_eq!(bits![1].trailing_zeros(), 0); |
| 1331 |
/// assert_eq!(bits![1, 0].trailing_zeros(), 1); |
| 1332 |
/// ``` |
| 1333 |
#[inline] |
| 1334 |
pub fn trailing_zeros(&self) -> usize { |
| 1335 |
let len = self.len(); |
| 1336 |
self.last_one().map(|idx| len - 1 - idx).unwrap_or(len) |
| 1337 |
} |
| 1338 |
|
| 1339 |
/// Tests if there is at least one bit set to `1` in the bit-slice. |
| 1340 |
/// |
| 1341 |
/// Returns `false` when `self` is empty. |
| 1342 |
/// |
| 1343 |
/// ## Examples |
| 1344 |
/// |
| 1345 |
/// ```rust |
| 1346 |
/// use bitvec::prelude::*; |
| 1347 |
/// |
| 1348 |
/// assert!(!bits![].any()); |
| 1349 |
/// assert!(!bits![0].any()); |
| 1350 |
/// assert!(bits![0, 1].any()); |
| 1351 |
/// ``` |
| 1352 |
#[inline] |
| 1353 |
pub fn any(&self) -> bool { |
| 1354 |
self.count_ones() > 0 |
| 1355 |
} |
| 1356 |
|
| 1357 |
/// Tests if every bit is set to `1` in the bit-slice. |
| 1358 |
/// |
| 1359 |
/// Returns `true` when `self` is empty. |
| 1360 |
/// |
| 1361 |
/// ## Examples |
| 1362 |
/// |
| 1363 |
/// ```rust |
| 1364 |
/// use bitvec::prelude::*; |
| 1365 |
/// |
| 1366 |
/// assert!( bits![].all()); |
| 1367 |
/// assert!(!bits![0].all()); |
| 1368 |
/// assert!( bits![1].all()); |
| 1369 |
/// ``` |
| 1370 |
#[inline] |
| 1371 |
pub fn all(&self) -> bool { |
| 1372 |
self.count_zeros() == 0 |
| 1373 |
} |
| 1374 |
|
| 1375 |
/// Tests if every bit is cleared to `0` in the bit-slice. |
| 1376 |
/// |
| 1377 |
/// Returns `true` when `self` is empty. |
| 1378 |
/// |
| 1379 |
/// ## Examples |
| 1380 |
/// |
| 1381 |
/// ```rust |
| 1382 |
/// use bitvec::prelude::*; |
| 1383 |
/// |
| 1384 |
/// assert!( bits![].not_any()); |
| 1385 |
/// assert!(!bits![1].not_any()); |
| 1386 |
/// assert!( bits![0].not_any()); |
| 1387 |
/// ``` |
| 1388 |
#[inline] |
| 1389 |
pub fn not_any(&self) -> bool { |
| 1390 |
self.count_ones() == 0 |
| 1391 |
} |
| 1392 |
|
| 1393 |
/// Tests if at least one bit is cleared to `0` in the bit-slice. |
| 1394 |
/// |
| 1395 |
/// Returns `false` when `self` is empty. |
| 1396 |
/// |
| 1397 |
/// ## Examples |
| 1398 |
/// |
| 1399 |
/// ```rust |
| 1400 |
/// use bitvec::prelude::*; |
| 1401 |
/// |
| 1402 |
/// assert!(!bits![].not_all()); |
| 1403 |
/// assert!(!bits![1].not_all()); |
| 1404 |
/// assert!( bits![0].not_all()); |
| 1405 |
/// ``` |
| 1406 |
#[inline] |
| 1407 |
pub fn not_all(&self) -> bool { |
| 1408 |
self.count_zeros() > 0 |
| 1409 |
} |
| 1410 |
|
| 1411 |
/// Tests if at least one bit is set to `1`, and at least one bit is cleared |
| 1412 |
/// to `0`, in the bit-slice. |
| 1413 |
/// |
| 1414 |
/// Returns `false` when `self` is empty. |
| 1415 |
/// |
| 1416 |
/// ## Examples |
| 1417 |
/// |
| 1418 |
/// ```rust |
| 1419 |
/// use bitvec::prelude::*; |
| 1420 |
/// |
| 1421 |
/// assert!(!bits![].some()); |
| 1422 |
/// assert!(!bits![0].some()); |
| 1423 |
/// assert!(!bits![1].some()); |
| 1424 |
/// assert!( bits![0, 1].some()); |
| 1425 |
/// ``` |
| 1426 |
#[inline] |
| 1427 |
pub fn some(&self) -> bool { |
| 1428 |
self.any() && self.not_all() |
| 1429 |
} |
| 1430 |
} |
| 1431 |
|
| 1432 |
/// Buffer manipulation. |
| 1433 |
impl<T, O> BitSlice<T, O> |
| 1434 |
where |
| 1435 |
T: BitStore, |
| 1436 |
O: BitOrder, |
| 1437 |
{ |
| 1438 |
/// Shifts the contents of a bit-slice “left” (towards the zero-index), |
| 1439 |
/// clearing the “right” bits to `0`. |
| 1440 |
/// |
| 1441 |
/// This is a strictly-worse analogue to taking `bits = &bits[by ..]`: it |
| 1442 |
/// has to modify the entire memory region that `bits` governs, and destroys |
| 1443 |
/// contained information. Unless the actual memory layout and contents of |
| 1444 |
/// your bit-slice matters to your program, you should *probably* prefer to |
| 1445 |
/// munch your way forward through a bit-slice handle. |
| 1446 |
/// |
| 1447 |
/// Note also that the “left” here is semantic only, and **does not** |
| 1448 |
/// necessarily correspond to a left-shift instruction applied to the |
| 1449 |
/// underlying integer storage. |
| 1450 |
/// |
| 1451 |
/// This has no effect when `by` is `0`. When `by` is `self.len()`, the |
| 1452 |
/// bit-slice is entirely cleared to `0`. |
| 1453 |
/// |
| 1454 |
/// ## Panics |
| 1455 |
/// |
| 1456 |
/// This panics if `by` is not less than `self.len()`. |
| 1457 |
/// |
| 1458 |
/// ## Examples |
| 1459 |
/// |
| 1460 |
/// ```rust |
| 1461 |
/// use bitvec::prelude::*; |
| 1462 |
/// |
| 1463 |
/// let bits = bits![mut 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1]; |
| 1464 |
/// // these bits are retained ^--------------------------^ |
| 1465 |
/// bits.shift_left(2); |
| 1466 |
/// assert_eq!(bits, bits![1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0]); |
| 1467 |
/// // and move here ^--------------------------^ |
| 1468 |
/// |
| 1469 |
/// let bits = bits![mut 1; 2]; |
| 1470 |
/// bits.shift_left(2); |
| 1471 |
/// assert_eq!(bits, bits![0; 2]); |
| 1472 |
/// ``` |
| 1473 |
#[inline] |
| 1474 |
pub fn shift_start(&mut self, by: usize) { |
| 1475 |
if by == 0 { |
| 1476 |
return; |
| 1477 |
} |
| 1478 |
|
| 1479 |
let len = self.len(); |
| 1480 |
if by == len { |
| 1481 |
return self.fill(false); |
| 1482 |
} |
| 1483 |
assert!( |
| 1484 |
by <= len, |
| 1485 |
"shift must be less than the length of the bit-slice: {} >= {}", |
| 1486 |
by, |
| 1487 |
len, |
| 1488 |
); |
| 1489 |
|
| 1490 |
unsafe { |
| 1491 |
self.copy_within_unchecked(by .., 0); |
| 1492 |
self.get_unchecked_mut(len - by ..).fill(false); |
| 1493 |
} |
| 1494 |
} |
| 1495 |
|
| 1496 |
#[inline] |
| 1497 |
#[doc(hidden)] |
| 1498 |
#[allow(deprecated)] |
| 1499 |
#[deprecated(note = "Use `.shift_start()` instead", since = "1.1.0")] |
| 1500 |
pub fn shift_left(&mut self, by: usize) { |
| 1501 |
self.shift_start(by); |
| 1502 |
} |
| 1503 |
|
| 1504 |
/// Shifts the contents of a bit-slice “right” (away from the zero-index), |
| 1505 |
/// clearing the “left” bits to `0`. |
| 1506 |
/// |
| 1507 |
/// This is a strictly-worse analogue to taking `bits = &bits[.. bits.len() |
| 1508 |
/// - by]`: it must modify the entire memory region that `bits` governs, and |
| 1509 |
/// destroys contained information. Unless the actual memory layout and |
| 1510 |
/// contents of your bit-slice matters to your program, you should |
| 1511 |
/// *probably* prefer to munch your way backward through a bit-slice handle. |
| 1512 |
/// |
| 1513 |
/// Note also that the “right” here is semantic only, and **does not** |
| 1514 |
/// necessarily correspond to a right-shift instruction applied to the |
| 1515 |
/// underlying integer storage. |
| 1516 |
/// |
| 1517 |
/// This has no effect when `by` is `0`. When `by` is `self.len()`, the |
| 1518 |
/// bit-slice is entirely cleared to `0`. |
| 1519 |
/// |
| 1520 |
/// ## Panics |
| 1521 |
/// |
| 1522 |
/// This panics if `by` is not less than `self.len()`. |
| 1523 |
/// |
| 1524 |
/// ## Examples |
| 1525 |
/// |
| 1526 |
/// ```rust |
| 1527 |
/// use bitvec::prelude::*; |
| 1528 |
/// |
| 1529 |
/// let bits = bits![mut 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1]; |
| 1530 |
/// // these bits stay ^--------------------------^ |
| 1531 |
/// bits.shift_right(2); |
| 1532 |
/// assert_eq!(bits, bits![0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1]); |
| 1533 |
/// // and move here ^--------------------------^ |
| 1534 |
/// |
| 1535 |
/// let bits = bits![mut 1; 2]; |
| 1536 |
/// bits.shift_right(2); |
| 1537 |
/// assert_eq!(bits, bits![0; 2]); |
| 1538 |
/// ``` |
| 1539 |
#[inline] |
| 1540 |
pub fn shift_end(&mut self, by: usize) { |
| 1541 |
if by == 0 { |
| 1542 |
return; |
| 1543 |
} |
| 1544 |
|
| 1545 |
let len = self.len(); |
| 1546 |
if by == len { |
| 1547 |
return self.fill(false); |
| 1548 |
} |
| 1549 |
assert!( |
| 1550 |
by <= len, |
| 1551 |
"shift must be less than the length of the bit-slice: {} >= {}", |
| 1552 |
by, |
| 1553 |
len, |
| 1554 |
); |
| 1555 |
|
| 1556 |
unsafe { |
| 1557 |
self.copy_within_unchecked(.. len - by, by); |
| 1558 |
self.get_unchecked_mut(.. by).fill(false); |
| 1559 |
} |
| 1560 |
} |
| 1561 |
|
| 1562 |
#[inline] |
| 1563 |
#[doc(hidden)] |
| 1564 |
#[allow(deprecated)] |
| 1565 |
#[deprecated(note = "Use `.shift_end() instead", since = "1.1.0")] |
| 1566 |
pub fn shift_right(&mut self, by: usize) { |
| 1567 |
self.shift_end(by); |
| 1568 |
} |
| 1569 |
} |
| 1570 |
|
| 1571 |
/// Crate internals. |
| 1572 |
impl<T, O> BitSlice<T, O> |
| 1573 |
where |
| 1574 |
T: BitStore, |
| 1575 |
O: BitOrder, |
| 1576 |
{ |
| 1577 |
/// Gets the structural form of the encoded reference. |
| 1578 |
pub(crate) fn as_bitspan(&self) -> BitSpan<Const, T, O> { |
| 1579 |
BitSpan::from_bitslice_ptr(self) |
| 1580 |
} |
| 1581 |
|
| 1582 |
/// Gets the structural form of the encoded reference. |
| 1583 |
pub(crate) fn as_mut_bitspan(&mut self) -> BitSpan<Mut, T, O> { |
| 1584 |
BitSpan::from_bitslice_ptr_mut(self) |
| 1585 |
} |
| 1586 |
|
| 1587 |
/// Asserts that `index` is within the given bounds. |
| 1588 |
/// |
| 1589 |
/// ## Parameters |
| 1590 |
/// |
| 1591 |
/// - `&self` |
| 1592 |
/// - `index`: The bit index to test against the bit-slice. |
| 1593 |
/// - `bounds`: The bounds to check. cannot exceed `0 ..= self.len()`. |
| 1594 |
/// |
| 1595 |
/// ## Panics |
| 1596 |
/// |
| 1597 |
/// This panics if `bounds` is outside `index`. |
| 1598 |
pub(crate) fn assert_in_bounds<R>(&self, index: usize, bounds: R) |
| 1599 |
where R: RangeExt<usize> { |
| 1600 |
let bounds = bounds.normalize(0, self.len()); |
| 1601 |
assert!( |
| 1602 |
bounds.contains(&index), |
| 1603 |
"index {} out of range: {:?}", |
| 1604 |
index, |
| 1605 |
bounds.end_bound() |
| 1606 |
); |
| 1607 |
} |
| 1608 |
|
| 1609 |
/// Marks an exclusive bit-slice as covering an aliased memory region. |
| 1610 |
pub(crate) fn alias_mut(&mut self) -> &mut BitSlice<T::Alias, O> { |
| 1611 |
unsafe { self.as_mut_bitspan().cast::<T::Alias>().into_bitslice_mut() } |
| 1612 |
} |
| 1613 |
|
| 1614 |
/// Removes an aliasing marker from an exclusive bit-slice handle. |
| 1615 |
/// |
| 1616 |
/// ## Safety |
| 1617 |
/// |
| 1618 |
/// This may only be used when the bit-slice is either known to be |
| 1619 |
/// unaliased, or this call is combined with an operation that adds an |
| 1620 |
/// aliasing marker and the total number of aliasing markers remains |
| 1621 |
/// unchanged. |
| 1622 |
pub(crate) unsafe fn unalias_mut( |
| 1623 |
this: &mut BitSlice<T::Alias, O>, |
| 1624 |
) -> &mut Self { |
| 1625 |
this.as_mut_bitspan().cast::<T>().into_bitslice_mut() |
| 1626 |
} |
| 1627 |
|
| 1628 |
/// Splits a mutable bit-slice at a midpoint, without either doing bounds |
| 1629 |
/// checks or adding an alias marker to the returned sections. |
| 1630 |
/// |
| 1631 |
/// This method has the same behavior as [`.split_at_unchecked_mut()`], |
| 1632 |
/// except that it does not apply an aliasing marker to the partitioned |
| 1633 |
/// subslices. |
| 1634 |
/// |
| 1635 |
/// ## Safety |
| 1636 |
/// |
| 1637 |
/// See `split_at_unchecked_mut`. Additionally, this is only safe when `T` |
| 1638 |
/// is alias-safe. |
| 1639 |
/// |
| 1640 |
/// [`.split_at_unchecked_mut()`]: Self::split_at_unchecked_mut |
| 1641 |
pub(crate) unsafe fn split_at_unchecked_mut_noalias( |
| 1642 |
&mut self, |
| 1643 |
mid: usize, |
| 1644 |
) -> (&mut Self, &mut Self) { |
| 1645 |
// Split the slice at the requested midpoint, adding an alias layer |
| 1646 |
let (head, tail) = self.split_at_unchecked_mut(mid); |
| 1647 |
// Remove the new alias layer. |
| 1648 |
(Self::unalias_mut(head), Self::unalias_mut(tail)) |
| 1649 |
} |
| 1650 |
} |
| 1651 |
|
| 1652 |
/// Methods available only when `T` allows shared mutability. |
| 1653 |
impl<T, O> BitSlice<T, O> |
| 1654 |
where |
| 1655 |
T: BitStore + radium::Radium, |
| 1656 |
O: BitOrder, |
| 1657 |
{ |
| 1658 |
/// Writes a new value into a single bit, using alias-safe operations. |
| 1659 |
/// |
| 1660 |
/// This is equivalent to [`.set()`], except that it does not require an |
| 1661 |
/// `&mut` reference, and allows bit-slices with alias-safe storage to share |
| 1662 |
/// write permissions. |
| 1663 |
/// |
| 1664 |
/// ## Parameters |
| 1665 |
/// |
| 1666 |
/// - `&self`: This method only exists on bit-slices with alias-safe |
| 1667 |
/// storage, and so does not require exclusive access. |
| 1668 |
/// - `index`: The bit index to set. It must be in `0 .. self.len()`. |
| 1669 |
/// - `value`: The new bit-value to write into the bit at `index`. |
| 1670 |
/// |
| 1671 |
/// ## Panics |
| 1672 |
/// |
| 1673 |
/// This panics if `index` is out of bounds. |
| 1674 |
/// |
| 1675 |
/// ## Examples |
| 1676 |
/// |
| 1677 |
/// ```rust |
| 1678 |
/// use bitvec::prelude::*; |
| 1679 |
/// use core::cell::Cell; |
| 1680 |
/// |
| 1681 |
/// let bits: &BitSlice<_, _> = bits![Cell<usize>, Lsb0; 0, 1]; |
| 1682 |
/// bits.set_aliased(0, true); |
| 1683 |
/// bits.set_aliased(1, false); |
| 1684 |
/// |
| 1685 |
/// assert_eq!(bits, bits![1, 0]); |
| 1686 |
/// ``` |
| 1687 |
/// |
| 1688 |
/// [`.set()`]: Self::set |
| 1689 |
#[inline] |
| 1690 |
pub fn set_aliased(&self, index: usize, value: bool) { |
| 1691 |
self.assert_in_bounds(index, 0 .. self.len()); |
| 1692 |
unsafe { |
| 1693 |
self.set_aliased_unchecked(index, value); |
| 1694 |
} |
| 1695 |
} |
| 1696 |
|
| 1697 |
/// Writes a new value into a single bit, using alias-safe operations and |
| 1698 |
/// without bounds checking. |
| 1699 |
/// |
| 1700 |
/// This is equivalent to [`.set_unchecked()`], except that it does not |
| 1701 |
/// require an `&mut` reference, and allows bit-slices with alias-safe |
| 1702 |
/// storage to share write permissions. |
| 1703 |
/// |
| 1704 |
/// ## Parameters |
| 1705 |
/// |
| 1706 |
/// - `&self`: This method only exists on bit-slices with alias-safe |
| 1707 |
/// storage, and so does not require exclusive access. |
| 1708 |
/// - `index`: The bit index to set. It must be in `0 .. self.len()`. |
| 1709 |
/// - `value`: The new bit-value to write into the bit at `index`. |
| 1710 |
/// |
| 1711 |
/// ## Safety |
| 1712 |
/// |
| 1713 |
/// The caller must ensure that `index` is not out of bounds. |
| 1714 |
/// |
| 1715 |
/// ## Examples |
| 1716 |
/// |
| 1717 |
/// ```rust |
| 1718 |
/// use bitvec::prelude::*; |
| 1719 |
/// use core::cell::Cell; |
| 1720 |
/// |
| 1721 |
/// let data = Cell::new(0u8); |
| 1722 |
/// let bits = &data.view_bits::<Lsb0>()[.. 2]; |
| 1723 |
/// unsafe { |
| 1724 |
/// bits.set_aliased_unchecked(3, true); |
| 1725 |
/// } |
| 1726 |
/// assert_eq!(data.get(), 8); |
| 1727 |
/// ``` |
| 1728 |
/// |
| 1729 |
/// [`.set_unchecked()`]: Self::set_unchecked |
| 1730 |
#[inline] |
| 1731 |
pub unsafe fn set_aliased_unchecked(&self, index: usize, value: bool) { |
| 1732 |
self.as_bitptr().add(index).freeze().frozen_write_bit(value); |
| 1733 |
} |
| 1734 |
} |
| 1735 |
|
| 1736 |
/// Miscellaneous information. |
| 1737 |
impl<T, O> BitSlice<T, O> |
| 1738 |
where |
| 1739 |
T: BitStore, |
| 1740 |
O: BitOrder, |
| 1741 |
{ |
| 1742 |
/// The inclusive maximum length of a `BitSlice<_, T>`. |
| 1743 |
/// |
| 1744 |
/// As `BitSlice` is zero-indexed, the largest possible *index* is one less |
| 1745 |
/// than this value. |
| 1746 |
/// |
| 1747 |
/// |CPU word width| Value | |
| 1748 |
/// |-------------:|----------------------:| |
| 1749 |
/// | 32 bits | `0x1fff_ffff` | |
| 1750 |
/// | 64 bits |`0x1fff_ffff_ffff_ffff`| |
| 1751 |
pub const MAX_BITS: usize = BitSpan::<Const, T, O>::REGION_MAX_BITS; |
| 1752 |
/// The inclusive maximum length that a `[T]` slice can be for |
| 1753 |
/// `BitSlice<_, T>` to cover it. |
| 1754 |
/// |
| 1755 |
/// A `BitSlice<_, T>` that begins in the interior of an element and |
| 1756 |
/// contains the maximum number of bits will extend one element past the |
| 1757 |
/// cutoff that would occur if the bit-slice began at the zeroth bit. Such a |
| 1758 |
/// bit-slice is difficult to manually construct, but would not otherwise |
| 1759 |
/// fail. |
| 1760 |
/// |
| 1761 |
/// |Type Bits|Max Elements (32-bit)| Max Elements (64-bit) | |
| 1762 |
/// |--------:|--------------------:|----------------------:| |
| 1763 |
/// | 8| `0x0400_0001` |`0x0400_0000_0000_0001`| |
| 1764 |
/// | 16| `0x0200_0001` |`0x0200_0000_0000_0001`| |
| 1765 |
/// | 32| `0x0100_0001` |`0x0100_0000_0000_0001`| |
| 1766 |
/// | 64| `0x0080_0001` |`0x0080_0000_0000_0001`| |
| 1767 |
pub const MAX_ELTS: usize = BitSpan::<Const, T, O>::REGION_MAX_ELTS; |
| 1768 |
} |
| 1769 |
|
| 1770 |
#[cfg(feature = "alloc")] |
| 1771 |
impl<T, O> BitSlice<T, O> |
| 1772 |
where |
| 1773 |
T: BitStore, |
| 1774 |
O: BitOrder, |
| 1775 |
{ |
| 1776 |
/// Copies a bit-slice into an owned bit-vector. |
| 1777 |
/// |
| 1778 |
/// Since the new vector is freshly owned, this gets marked as `::Unalias` |
| 1779 |
/// to remove any guards that may have been inserted by the bit-slice’s |
| 1780 |
/// history. |
| 1781 |
/// |
| 1782 |
/// It does *not* use the underlying memory type, so that a `BitSlice<_, |
| 1783 |
/// Cell<_>>` will produce a `BitVec<_, Cell<_>>`. |
| 1784 |
/// |
| 1785 |
/// ## Original |
| 1786 |
/// |
| 1787 |
/// [`slice::to_vec`](https://doc.rust-lang.org/std/primitive.slice.html#method.to_vec) |
| 1788 |
/// |
| 1789 |
/// ## Examples |
| 1790 |
/// |
| 1791 |
/// ```rust |
| 1792 |
/// use bitvec::prelude::*; |
| 1793 |
/// |
| 1794 |
/// let bits = bits![0, 1, 0, 1]; |
| 1795 |
/// let bv = bits.to_bitvec(); |
| 1796 |
/// assert_eq!(bits, bv); |
| 1797 |
/// ``` |
| 1798 |
#[inline] |
| 1799 |
pub fn to_bitvec(&self) -> BitVec<T::Unalias, O> { |
| 1800 |
self.domain() |
| 1801 |
.map(<T::Unalias as BitStore>::new) |
| 1802 |
.collect::<Vec<_>>() |
| 1803 |
.pipe(BitVec::from_vec) |
| 1804 |
.tap_mut(|bv| unsafe { |
| 1805 |
bv.set_head(self.as_bitspan().head()); |
| 1806 |
bv.set_len(self.len()); |
| 1807 |
}) |
| 1808 |
} |
| 1809 |
} |
| 1810 |
|
| 1811 |
#[inline] |
| 1812 |
#[doc = include_str!("../doc/slice/from_raw_parts_unchecked.md")] |
| 1813 |
pub unsafe fn from_raw_parts_unchecked<'a, T, O>( |
| 1814 |
ptr: BitPtr<Const, T, O>, |
| 1815 |
len: usize, |
| 1816 |
) -> &'a BitSlice<T, O> |
| 1817 |
where |
| 1818 |
O: BitOrder, |
| 1819 |
T: 'a + BitStore, |
| 1820 |
{ |
| 1821 |
ptr.span_unchecked(len).into_bitslice_ref() |
| 1822 |
} |
| 1823 |
|
| 1824 |
#[inline] |
| 1825 |
#[doc = include_str!("../doc/slice/from_raw_parts_unchecked_mut.md")] |
| 1826 |
pub unsafe fn from_raw_parts_unchecked_mut<'a, T, O>( |
| 1827 |
ptr: BitPtr<Mut, T, O>, |
| 1828 |
len: usize, |
| 1829 |
) -> &'a mut BitSlice<T, O> |
| 1830 |
where |
| 1831 |
O: BitOrder, |
| 1832 |
T: 'a + BitStore, |
| 1833 |
{ |
| 1834 |
ptr.span_unchecked(len).into_bitslice_mut() |
| 1835 |
} |