bitvec/
array.rs

1#![doc = include_str!("../doc/array.md")]
2
3use core::marker::PhantomData;
4
5use crate::{
6	mem,
7	order::{
8		BitOrder,
9		Lsb0,
10	},
11	slice::BitSlice,
12	view::BitViewSized,
13};
14
15mod api;
16mod iter;
17mod ops;
18mod tests;
19mod traits;
20
21pub use self::iter::IntoIter;
22
23#[repr(transparent)]
24#[doc = include_str!("../doc/array/BitArray.md")]
25pub struct BitArray<A = [usize; 1], O = Lsb0>
26where
27	A: BitViewSized,
28	O: BitOrder,
29{
30	/// The ordering of bits within an `A::Store` element.
31	pub _ord: PhantomData<O>,
32	/// The wrapped data buffer.
33	pub data: A,
34}
35
36impl<A, O> BitArray<A, O>
37where
38	A: BitViewSized,
39	O: BitOrder,
40{
41	/// A bit-array with all bits initialized to zero.
42	pub const ZERO: Self = Self {
43		_ord: PhantomData,
44		data: A::ZERO,
45	};
46
47	/// Wraps an existing buffer as a bit-array.
48	///
49	/// ## Examples
50	///
51	/// ```rust
52	/// use bitvec::prelude::*;
53	///
54	/// let data = [0u16, 1, 2, 3];
55	/// let bits = BitArray::<_, Msb0>::new(data);
56	/// assert_eq!(bits.len(), 64);
57	/// ```
58	#[inline]
59	pub fn new(data: A) -> Self {
60		Self { data, ..Self::ZERO }
61	}
62
63	/// Removes the bit-array wrapper, returning the contained buffer.
64	///
65	/// ## Examples
66	///
67	/// ```rust
68	/// use bitvec::prelude::*;
69	///
70	/// let bits = bitarr![0; 30];
71	/// let native: [usize; 1] = bits.into_inner();
72	/// ```
73	#[inline]
74	pub fn into_inner(self) -> A {
75		self.data
76	}
77
78	/// Explicitly views the bit-array as a bit-slice.
79	#[inline]
80	pub fn as_bitslice(&self) -> &BitSlice<A::Store, O> {
81		self.data.view_bits::<O>()
82	}
83
84	/// Explicitly views the bit-array as a mutable bit-slice.
85	#[inline]
86	pub fn as_mut_bitslice(&mut self) -> &mut BitSlice<A::Store, O> {
87		self.data.view_bits_mut::<O>()
88	}
89
90	/// Views the bit-array as a slice of its underlying memory elements.
91	#[inline]
92	pub fn as_raw_slice(&self) -> &[A::Store] {
93		self.data.as_raw_slice()
94	}
95
96	/// Views the bit-array as a mutable slice of its underlying memory
97	/// elements.
98	#[inline]
99	pub fn as_raw_mut_slice(&mut self) -> &mut [A::Store] {
100		self.data.as_raw_mut_slice()
101	}
102
103	/// Gets the length (in bits) of the bit-array.
104	///
105	/// This method is a compile-time constant.
106	#[inline]
107	pub fn len(&self) -> usize {
108		mem::bits_of::<A>()
109	}
110
111	/// Tests whether the array is empty.
112	///
113	/// This method is a compile-time constant.
114	#[inline]
115	pub fn is_empty(&self) -> bool {
116		mem::bits_of::<A>() == 0
117	}
118}