bitvec/
vec.rs

1#![doc = include_str!("../doc/vec.md")]
2#![cfg(feature = "alloc")]
3
4#[cfg(not(feature = "std"))]
5use alloc::vec;
6use alloc::vec::Vec;
7use core::{
8	mem::{
9		self,
10		ManuallyDrop,
11	},
12	ptr,
13	slice,
14};
15
16use tap::Pipe;
17use wyz::comu::{
18	Const,
19	Mut,
20};
21
22pub use self::iter::{
23	Drain,
24	Splice,
25};
26pub use crate::boxed::IntoIter;
27use crate::{
28	boxed::BitBox,
29	index::BitIdx,
30	mem::bits_of,
31	order::{
32		BitOrder,
33		Lsb0,
34	},
35	ptr::{
36		AddressExt,
37		BitPtr,
38		BitSpan,
39		BitSpanError,
40	},
41	slice::BitSlice,
42	store::BitStore,
43	view::BitView,
44};
45
46mod api;
47mod iter;
48mod ops;
49mod tests;
50mod traits;
51
52#[repr(C)]
53#[doc = include_str!("../doc/vec/BitVec.md")]
54pub struct BitVec<T = usize, O = Lsb0>
55where
56	T: BitStore,
57	O: BitOrder,
58{
59	/// Span description of the live bits in the allocation.
60	bitspan:  BitSpan<Mut, T, O>,
61	/// Allocation capacity, measured in `T` elements.
62	capacity: usize,
63}
64
65/// Constructors.
66impl<T, O> BitVec<T, O>
67where
68	T: BitStore,
69	O: BitOrder,
70{
71	/// An empty bit-vector with no backing allocation.
72	pub const EMPTY: Self = Self {
73		bitspan:  BitSpan::EMPTY,
74		capacity: 0,
75	};
76
77	/// Creates a new bit-vector by repeating a bit for the desired length.
78	///
79	/// ## Examples
80	///
81	/// ```rust
82	/// use bitvec::prelude::*;
83	///
84	/// let zeros = BitVec::<u8, Msb0>::repeat(false, 50);
85	/// let ones = BitVec::<u16, Lsb0>::repeat(true, 50);
86	/// ```
87	#[inline]
88	pub fn repeat(bit: bool, len: usize) -> Self {
89		let mut out = Self::with_capacity(len);
90		unsafe {
91			out.set_len(len);
92			out.as_raw_mut_slice().fill_with(|| {
93				BitStore::new(if bit { !<T::Mem>::ZERO } else { <T::Mem>::ZERO })
94			});
95		}
96		out
97	}
98
99	/// Copies the contents of a bit-slice into a new heap allocation.
100	///
101	/// This copies the raw underlying elements into a new allocation, and sets
102	/// the produced bit-vector to use the same memory layout as the originating
103	/// bit-slice. This means that it may begin at any bit in the first element,
104	/// not just the zeroth bit. If you require this property, call
105	/// [`.force_align()`].
106	///
107	/// Dead bits in the copied memory elements are guaranteed to be zeroed.
108	///
109	/// ## Examples
110	///
111	/// ```rust
112	/// use bitvec::prelude::*;
113	///
114	/// let bits = bits![0, 1, 0, 0, 1];
115	/// let bv = BitVec::from_bitslice(bits);
116	/// assert_eq!(bv, bits);
117	/// ```
118	///
119	/// [`.force_align()`]: Self::force_align
120	#[inline]
121	pub fn from_bitslice(slice: &BitSlice<T, O>) -> Self {
122		let bitspan = slice.as_bitspan();
123
124		let mut vec = bitspan
125			.elements()
126			.pipe(Vec::with_capacity)
127			.pipe(ManuallyDrop::new);
128		vec.extend(slice.domain());
129
130		let bitspan = unsafe {
131			BitSpan::new_unchecked(
132				vec.as_mut_ptr().cast::<T>().into_address(),
133				bitspan.head(),
134				bitspan.len(),
135			)
136		};
137		let capacity = vec.capacity();
138		Self { bitspan, capacity }
139	}
140
141	/// Constructs a new bit-vector from a single element.
142	///
143	/// This copies `elem` into a new heap allocation, and sets the bit-vector
144	/// to cover it entirely.
145	///
146	/// ## Examples
147	///
148	/// ```rust
149	/// use bitvec::prelude::*;
150	///
151	/// let bv = BitVec::<_, Msb0>::from_element(1u8);
152	/// assert!(bv[7]);
153	/// ```
154	#[inline]
155	pub fn from_element(elem: T) -> Self {
156		Self::from_vec(vec![elem])
157	}
158
159	/// Constructs a new bit-vector from a slice of memory elements.
160	///
161	/// This copies `slice` into a new heap allocation, and sets the bit-vector
162	/// to cover it entirely.
163	///
164	/// ## Panics
165	///
166	/// This panics if `slice` exceeds bit-vector capacity.
167	///
168	/// ## Examples
169	///
170	/// ```rust
171	/// use bitvec::prelude::*;
172	///
173	/// let slice = &[0u8, 1, 2, 3];
174	/// let bv = BitVec::<_, Lsb0>::from_slice(slice);
175	/// assert_eq!(bv.len(), 32);
176	/// ```
177	#[inline]
178	pub fn from_slice(slice: &[T]) -> Self {
179		Self::try_from_slice(slice).unwrap()
180	}
181
182	/// Fallibly constructs a new bit-vector from a slice of memory elements.
183	///
184	/// This fails early if `slice` exceeds bit-vector capacity. If it is not,
185	/// then `slice` is copied into a new heap allocation and fully spanned by
186	/// the returned bit-vector.
187	///
188	/// ## Examples
189	///
190	/// ```rust
191	/// use bitvec::prelude::*;
192	///
193	/// let slice = &[0u8, 1, 2, 3];
194	/// let bv = BitVec::<_, Lsb0>::try_from_slice(slice).unwrap();
195	/// assert_eq!(bv.len(), 32);
196	/// ```
197	#[inline]
198	pub fn try_from_slice(slice: &[T]) -> Result<Self, BitSpanError<T>> {
199		BitSlice::<T, O>::try_from_slice(slice).map(Self::from_bitslice)
200	}
201
202	/// Converts a regular vector in-place into a bit-vector.
203	///
204	/// The produced bit-vector spans every bit in the original vector. No
205	/// reällocation occurs; this is purely a transform of the handle.
206	///
207	/// ## Panics
208	///
209	/// This panics if the source vector is too long to view as a bit-slice.
210	///
211	/// ## Examples
212	///
213	/// ```rust
214	/// use bitvec::prelude::*;
215	///
216	/// let v = vec![0u8, 1, 2, 3];
217	/// let bv = BitVec::<_, Msb0>::from_vec(v);
218	/// assert_eq!(bv.len(), 32);
219	/// ```
220	#[inline]
221	pub fn from_vec(vec: Vec<T>) -> Self {
222		Self::try_from_vec(vec)
223			.expect("vector was too long to be converted into a `BitVec`")
224	}
225
226	/// Attempts to convert a regular vector in-place into a bit-vector.
227	///
228	/// This fails if the source vector is too long to view as a bit-slice. On
229	/// success, the produced bit-vector spans every bit in the original vector.
230	/// No reällocation occurs; this is purely a transform of the handle.
231	///
232	/// ## Examples
233	///
234	/// ```rust
235	/// use bitvec::prelude::*;
236	///
237	/// let v = vec![0u8; 20];
238	/// assert_eq!(BitVec::<_, Msb0>::try_from_vec(v).unwrap().len(), 160);
239	/// ```
240	///
241	/// It is not practical to allocate a vector that will fail this conversion.
242	#[inline]
243	pub fn try_from_vec(vec: Vec<T>) -> Result<Self, Vec<T>> {
244		let mut vec = ManuallyDrop::new(vec);
245		let capacity = vec.capacity();
246
247		BitPtr::from_mut_slice(vec.as_mut_slice())
248			.span(vec.len() * bits_of::<T::Mem>())
249			.map(|bitspan| Self { bitspan, capacity })
250			.map_err(|_| ManuallyDrop::into_inner(vec))
251	}
252
253	/// Appends the contents of a bit-slice to a bit-vector.
254	///
255	/// This can extend from a bit-slice of any type parameters; it is not
256	/// restricted to using the same parameters as `self`. However, when the
257	/// type parameters *do* match, it is possible for this to use a batch-copy
258	/// optimization to go faster than the individual-bit crawl that is
259	/// necessary when they differ.
260	///
261	/// Until Rust provides extensive support for specialization in trait
262	/// implementations, you should use this method whenever you are extending
263	/// from a `BitSlice` proper, and only use the general [`.extend()`]
264	/// implementation if you are required to use a generic `bool` source.
265	///
266	/// ## Original
267	///
268	/// [`Vec::extend_from_slice`](alloc::vec::Vec::extend_from_slice)
269	///
270	/// ## Examples
271	///
272	/// ```rust
273	/// use bitvec::prelude::*;
274	///
275	/// let mut bv = bitvec![0, 1];
276	/// bv.extend_from_bitslice(bits![0, 1, 0, 0, 1]);
277	/// assert_eq!(bv, bits![0, 1, 0, 1, 0, 0, 1]);
278	/// ```
279	///
280	/// [`.extend()`]: https://docs.rs/bitvec/latest/bitvec/vec/struct.Vec.html#impl-Extend
281	#[inline]
282	pub fn extend_from_bitslice<T2, O2>(&mut self, other: &BitSlice<T2, O2>)
283	where
284		T2: BitStore,
285		O2: BitOrder,
286	{
287		let len = self.len();
288		let olen = other.len();
289		self.resize(len + olen, false);
290		unsafe { self.get_unchecked_mut(len ..) }.clone_from_bitslice(other);
291	}
292
293	/// Appends a slice of `T` elements to a bit-vector.
294	///
295	/// The slice is viewed as a `BitSlice<T, O>`, then appended directly to the
296	/// bit-vector.
297	///
298	/// ## Original
299	///
300	/// [`Vec::extend_from_slice`](alloc::vec::Vec::extend_from_slice)
301	#[inline]
302	pub fn extend_from_raw_slice(&mut self, slice: &[T]) {
303		self.extend_from_bitslice(slice.view_bits::<O>());
304	}
305}
306
307/// Converters.
308impl<T, O> BitVec<T, O>
309where
310	T: BitStore,
311	O: BitOrder,
312{
313	/// Explicitly views the bit-vector as a bit-slice.
314	#[inline]
315	pub fn as_bitslice(&self) -> &BitSlice<T, O> {
316		unsafe { self.bitspan.into_bitslice_ref() }
317	}
318
319	/// Explicitly views the bit-vector as a mutable bit-slice.
320	#[inline]
321	pub fn as_mut_bitslice(&mut self) -> &mut BitSlice<T, O> {
322		unsafe { self.bitspan.into_bitslice_mut() }
323	}
324
325	/// Views the bit-vector as a slice of its underlying memory elements.
326	#[inline]
327	pub fn as_raw_slice(&self) -> &[T] {
328		let (data, len) =
329			(self.bitspan.address().to_const(), self.bitspan.elements());
330		unsafe { slice::from_raw_parts(data, len) }
331	}
332
333	/// Views the bit-vector as a mutable slice of its underlying memory
334	/// elements.
335	#[inline]
336	pub fn as_raw_mut_slice(&mut self) -> &mut [T] {
337		let (data, len) =
338			(self.bitspan.address().to_mut(), self.bitspan.elements());
339		unsafe { slice::from_raw_parts_mut(data, len) }
340	}
341
342	/// Creates an unsafe shared bit-pointer to the start of the buffer.
343	///
344	/// ## Original
345	///
346	/// [`Vec::as_ptr`](alloc::vec::Vec::as_ptr)
347	///
348	/// ## Safety
349	///
350	/// You must initialize the contents of the underlying buffer before
351	/// accessing memory through this pointer. See the `BitPtr` documentation
352	/// for more details.
353	#[inline]
354	pub fn as_bitptr(&self) -> BitPtr<Const, T, O> {
355		self.bitspan.to_bitptr().to_const()
356	}
357
358	/// Creates an unsafe writable bit-pointer to the start of the buffer.
359	///
360	/// ## Original
361	///
362	/// [`Vec::as_mut_ptr`](alloc::vec::Vec::as_mut_ptr)
363	///
364	/// ## Safety
365	///
366	/// You must initialize the contents of the underlying buffer before
367	/// accessing memory through this pointer. See the `BitPtr` documentation
368	/// for more details.
369	#[inline]
370	pub fn as_mut_bitptr(&mut self) -> BitPtr<Mut, T, O> {
371		self.bitspan.to_bitptr()
372	}
373
374	/// Converts a bit-vector into a boxed bit-slice.
375	///
376	/// This may cause a reällocation to drop any excess capacity.
377	///
378	/// ## Original
379	///
380	/// [`Vec::into_boxed_slice`](alloc::vec::Vec::into_boxed_slice)
381	///
382	/// ## Examples
383	///
384	/// ```rust
385	/// use bitvec::prelude::*;
386	///
387	/// let bv = bitvec![0, 1, 0, 0, 1];
388	/// let bb = bv.into_boxed_bitslice();
389	/// ```
390	#[inline]
391	pub fn into_boxed_bitslice(self) -> BitBox<T, O> {
392		let mut bitspan = self.bitspan;
393		let mut boxed =
394			self.into_vec().into_boxed_slice().pipe(ManuallyDrop::new);
395		unsafe {
396			bitspan.set_address(boxed.as_mut_ptr().into_address());
397			BitBox::from_raw(bitspan.into_bitslice_ptr_mut())
398		}
399	}
400
401	/// Converts a bit-vector into a `Vec` of its underlying storage.
402	///
403	/// The produced vector contains all elements that contained live bits. Dead
404	/// bits have an unspecified value; you should call [`.set_uninitialized()`]
405	/// before converting into a vector.
406	///
407	/// This does not affect the allocated memory; it is purely a conversion of
408	/// the handle.
409	///
410	/// ## Examples
411	///
412	/// ```rust
413	/// use bitvec::prelude::*;
414	///
415	/// let bv = bitvec![u8, Msb0; 0, 1, 0, 0, 1];
416	/// let v = bv.into_vec();
417	/// assert_eq!(v[0] & 0xF8, 0b01001_000);
418	/// ```
419	///
420	/// [`.set_uninitialized()`]: Self::set_uninitialized
421	#[inline]
422	pub fn into_vec(self) -> Vec<T> {
423		let (bitspan, capacity) = (self.bitspan, self.capacity);
424		mem::forget(self);
425		unsafe {
426			Vec::from_raw_parts(
427				bitspan.address().to_mut(),
428				bitspan.elements(),
429				capacity,
430			)
431		}
432	}
433}
434
435/// Utilities.
436impl<T, O> BitVec<T, O>
437where
438	T: BitStore,
439	O: BitOrder,
440{
441	/// Overwrites each element (visible in [`.as_raw_mut_slice()`]) with a new
442	/// bit-pattern.
443	///
444	/// This unconditionally writes `element` into each element in the backing
445	/// slice, without altering the bit-vector’s length or capacity.
446	///
447	/// This guarantees that dead bits visible in [`.as_raw_slice()`] but not
448	/// [`.as_bitslice()`] are initialized according to the bit-pattern of
449	/// `element.` The elements not visible in the raw slice, but present in the
450	/// allocation, do *not* specify a value. You may not rely on them being
451	/// zeroed *or* being set to the `element` bit-pattern.
452	///
453	/// ## Parameters
454	///
455	/// - `&mut self`
456	/// - `element`: The bit-pattern with which each live element in the backing
457	///   store is initialized.
458	///
459	/// ## Examples
460	///
461	/// ```rust
462	/// use bitvec::prelude::*;
463	///
464	/// let mut bv = bitvec![u8, Msb0; 0; 20];
465	/// assert_eq!(bv.as_raw_slice(), [0; 3]);
466	/// bv.set_elements(0xA5);
467	/// assert_eq!(bv.as_raw_slice(), [0xA5; 3]);
468	/// ```
469	///
470	/// [`.as_bitslice()`]: Self::as_bitslice
471	/// [`.as_raw_mut_slice()`]: Self::as_raw_mut_slice
472	/// [`.as_raw_slice()`]: Self::as_raw_slice
473	#[inline]
474	pub fn set_elements(&mut self, element: T::Mem) {
475		self.as_raw_mut_slice()
476			.iter_mut()
477			.for_each(|elt| elt.store_value(element));
478	}
479
480	/// Sets the uninitialized bits of a bit-vector to a known value.
481	///
482	/// This method modifies all bits that are observable in [`.as_raw_slice()`]
483	/// but *not* observable in [`.as_bitslice()`] to a known value.
484	/// Memory beyond the raw-slice view, but still within the allocation, is
485	/// considered fully dead and will never be seen.
486	///
487	/// This can be used to zero the unused memory so that when viewed as a raw
488	/// slice, unused bits have a consistent and predictable value.
489	///
490	/// ## Examples
491	///
492	/// ```rust
493	/// use bitvec::prelude::*;
494	///
495	/// let mut bv = 0b1101_1100u8.view_bits::<Lsb0>().to_bitvec();
496	/// assert_eq!(bv.as_raw_slice()[0], 0b1101_1100u8);
497	///
498	/// bv.truncate(4);
499	/// assert_eq!(bv.count_ones(), 2);
500	/// assert_eq!(bv.as_raw_slice()[0], 0b1101_1100u8);
501	///
502	/// bv.set_uninitialized(false);
503	/// assert_eq!(bv.as_raw_slice()[0], 0b0000_1100u8);
504	///
505	/// bv.set_uninitialized(true);
506	/// assert_eq!(bv.as_raw_slice()[0], 0b1111_1100u8);
507	/// ```
508	///
509	/// [`.as_bitslice()`]: Self::as_bitslice
510	/// [`.as_raw_slice()`]: Self::as_raw_slice
511	#[inline]
512	pub fn set_uninitialized(&mut self, value: bool) {
513		let head = self.bitspan.head().into_inner() as usize;
514		let last = head + self.len();
515		let all = self.as_raw_mut_slice().view_bits_mut::<O>();
516		unsafe {
517			all.get_unchecked_mut(.. head).fill(value);
518			all.get_unchecked_mut(last ..).fill(value);
519		}
520	}
521
522	/// Ensures that the live region of the bit-vector’s contents begin at the
523	/// front edge of the buffer.
524	///
525	/// `BitVec` has performance optimizations where it moves its view of its
526	/// buffer contents in order to avoid needless moves of its data within the
527	/// buffer. This can lead to unexpected contents of the raw memory values,
528	/// so this method ensures that the semantic contents of the bit-vector
529	/// match its in-memory storage.
530	///
531	/// ## Examples
532	///
533	/// ```rust
534	/// use bitvec::prelude::*;
535	///
536	/// let data = 0b00_1111_00u8;
537	/// let bits = data.view_bits::<Msb0>();
538	///
539	/// let mut bv = bits[2 .. 6].to_bitvec();
540	/// assert_eq!(bv, bits![1; 4]);
541	/// assert_eq!(bv.as_raw_slice()[0], data);
542	///
543	/// bv.force_align();
544	/// assert_eq!(bv, bits![1; 4]);
545	/// // BitVec does not specify the value of dead bits in its buffer.
546	/// assert_eq!(bv.as_raw_slice()[0] & 0xF0, 0xF0);
547	/// ```
548	#[inline]
549	pub fn force_align(&mut self) {
550		let mut bitspan = self.bitspan;
551		let len = bitspan.len();
552		let head = self.bitspan.head();
553		if head == BitIdx::MIN {
554			return;
555		}
556		let head = head.into_inner() as usize;
557		let last = head + len;
558		unsafe {
559			bitspan.set_head(BitIdx::MIN);
560			bitspan.set_len(last);
561			bitspan
562				.into_bitslice_mut()
563				.copy_within_unchecked(head .., 0);
564			bitspan.set_len(len);
565		}
566		self.bitspan = bitspan;
567	}
568
569	/// Sets the starting-bit index of the span descriptor.
570	///
571	/// ## Safety
572	///
573	/// The new `head` value must not cause the final bits of the bit-vector to
574	/// depart allocated memory.
575	pub(crate) unsafe fn set_head(&mut self, new_head: BitIdx<T::Mem>) {
576		self.bitspan.set_head(new_head);
577	}
578
579	/// Sets a bit-vector’s length without checking that it fits in the
580	/// allocated capacity.
581	///
582	/// ## Safety
583	///
584	/// `new_len` must not exceed `self.capacity()`.
585	pub(crate) unsafe fn set_len_unchecked(&mut self, new_len: usize) {
586		self.bitspan.set_len(new_len);
587	}
588
589	/// Asserts that a length can be encoded into the bit-vector handle.
590	///
591	/// ## Panics
592	///
593	/// This panics if `len` is too large to encode into a `BitSpan`.
594	#[inline]
595	fn assert_len_encodable(len: usize) {
596		assert!(
597			BitSpan::<Const, T, O>::len_encodable(len),
598			"bit-vector capacity exceeded: {} > {}",
599			len,
600			BitSlice::<T, O>::MAX_BITS,
601		);
602	}
603
604	/// Reserves some memory through the underlying vector.
605	///
606	/// ## Parameters
607	///
608	/// - `&mut self`
609	/// - `additional`: The amount of additional space required after
610	///   `self.len()` in the allocation.
611	/// - `func`: A function that manipulates the memory reservation of the
612	///   underlying vector.
613	///
614	/// ## Behavior
615	///
616	/// `func` should perform the appropriate action to allocate space for at
617	/// least `additional` more bits. After it returns, the underlying vector is
618	/// extended with zero-initialized elements until `self.len() + additional`
619	/// bits have been given initialized memory.
620	#[inline]
621	fn do_reservation(
622		&mut self,
623		additional: usize,
624		func: impl FnOnce(&mut Vec<T>, usize),
625	) {
626		let len = self.len();
627		let new_len = len.saturating_add(additional);
628		Self::assert_len_encodable(new_len);
629
630		let (head, elts) = (self.bitspan.head(), self.bitspan.elements());
631		let new_elts =
632			crate::mem::elts::<T>(head.into_inner() as usize + new_len);
633
634		let extra_elts = new_elts - elts;
635		self.with_vec(|vec| {
636			func(&mut **vec, extra_elts);
637			//  Ensure that any new elements are initialized.
638			vec.resize_with(new_elts, || <T as BitStore>::ZERO);
639		});
640	}
641
642	/// Briefly constructs an ordinary `Vec` controlling the buffer, allowing
643	/// operations to be applied to the memory allocation.
644	///
645	/// ## Parameters
646	///
647	/// - `&mut self`
648	/// - `func`: A function which may interact with the memory allocation.
649	///
650	/// After `func` runs, `self` is updated with the temporary `Vec`’s address
651	/// and capacity.
652	#[inline]
653	fn with_vec<F, R>(&mut self, func: F) -> R
654	where F: FnOnce(&mut ManuallyDrop<Vec<T>>) -> R {
655		let mut vec = unsafe { ptr::read(self) }
656			.into_vec()
657			.pipe(ManuallyDrop::new);
658		let out = func(&mut vec);
659
660		unsafe {
661			self.bitspan.set_address(vec.as_mut_ptr().into_address());
662		}
663		self.capacity = vec.capacity();
664		out
665	}
666}