1use core::gca;
2use std::{
3 io::{self, Cursor, Write},
4 ops::Range,
5};
6
7use azalea_buf::{AzBuf, AzBufVar, BufReadError};
8
9#[derive(AzBuf, Clone, Debug, Default, Eq, Hash, PartialEq)]
11pub struct JavaBitSet {
12 data: Box<[u64]>,
13}
14
15const LOG2_BITS_PER_WORD: usize = 6;
17
18impl JavaBitSet {
20 #[inline]
21 pub fn new(num_bits: usize) -> Self {
22 JavaBitSet {
23 data: vec![0; num_bits.div_ceil(64)].into(),
24 }
25 }
26
27 #[inline]
34 pub fn index(&self, index: usize) -> bool {
35 self.get(index).unwrap_or_else(|| {
36 let len = self.len();
37 panic!("index out of bounds: the len is {len} but the index is {index}")
38 })
39 }
40
41 #[inline]
42 pub fn get(&self, index: usize) -> Option<bool> {
43 self.data
44 .get(index / 64)
45 .map(|word| (word & (1u64 << (index % 64))) != 0)
46 }
47
48 pub fn clear(&mut self, range: Range<usize>) {
54 assert!(
55 range.start <= range.end,
56 "Range ends before it starts; {} must be less than or equal to {}",
57 range.start,
58 range.end
59 );
60
61 let from_idx = range.start;
62 let mut to_idx = range.end;
63
64 if from_idx == to_idx {
65 return;
66 }
67
68 let start_word_idx = self.word_index(from_idx);
69 if start_word_idx >= self.data.len() {
70 return;
71 }
72
73 let mut end_word_idx = self.word_index(to_idx - 1);
74 if end_word_idx >= self.data.len() {
75 to_idx = self.len();
76 end_word_idx = self.data.len() - 1;
77 }
78
79 let first_word_mask = u64::MAX.wrapping_shl(
80 from_idx
81 .try_into()
82 .expect("from_index shouldn't be larger than u32"),
83 );
84 let last_word_mask = u64::MAX.wrapping_shr((64 - (to_idx % 64)) as u32);
85 if start_word_idx == end_word_idx {
86 self.data[start_word_idx] &= !(first_word_mask & last_word_mask);
88 } else {
89 self.data[start_word_idx] &= !first_word_mask;
91 for i in (start_word_idx + 1)..end_word_idx {
92 self.data[i] = 0;
93 }
94 self.data[end_word_idx] &= !last_word_mask;
95 }
96 }
97
98 pub fn next_clear_bit(&self, from_index: usize) -> usize {
101 let mut u = self.word_index(from_index);
102 if u >= self.data.len() {
103 return from_index;
104 }
105
106 let mut word = !self.data[u] & (u64::MAX.wrapping_shl(from_index.try_into().unwrap()));
107
108 loop {
109 if word != 0 {
110 return (u * 64) + word.trailing_zeros() as usize;
111 }
112 u += 1;
113 if u == self.data.len() {
114 return self.data.len() * 64;
115 }
116 word = !self.data[u];
117 }
118 }
119
120 #[inline]
121 fn word_index(&self, bit_index: usize) -> usize {
122 bit_index >> LOG2_BITS_PER_WORD
123 }
124
125 #[inline]
132 pub fn set(&mut self, bit_index: usize) {
133 self.data[bit_index / 64] |= 1u64 << (bit_index % 64);
134 }
135
136 pub fn iter_ones(&self) -> impl Iterator<Item = usize> {
138 (0..self.len()).filter(|i| self.index(*i))
139 }
140
141 #[inline]
145 pub fn len(&self) -> usize {
146 self.data.len() * 64
147 }
148
149 pub fn is_empty(&self) -> bool {
153 self.len() == 0
154 }
155}
156
157impl From<Vec<u64>> for JavaBitSet {
158 fn from(data: Vec<u64>) -> Self {
159 JavaBitSet { data: data.into() }
160 }
161}
162
163impl From<Vec<u8>> for JavaBitSet {
164 fn from(data: Vec<u8>) -> Self {
165 let mut words = vec![0; data.len().div_ceil(8)];
166 for (i, byte) in data.iter().enumerate() {
167 words[i / 8] |= (*byte as u64) << ((i % 8) * 8);
168 }
169 JavaBitSet { data: words.into() }
170 }
171}
172
173#[derive(Clone, Debug, Eq, Hash, PartialEq)]
183pub struct FixedBitSet<const N: usize> {
184 data: ByteArray<N>,
185}
186
187type ByteArray<const N: usize> = [u8; gca!(BYTESIZE::<N>)];
188const BYTESIZE<const N: usize>: usize = const { N.div_ceil(8) };
189
190impl<const N: usize> FixedBitSet<N> {
191 #[must_use]
193 pub const fn new() -> Self {
194 FixedBitSet { data: [0; _] }
195 }
196
197 #[must_use]
199 pub const fn new_with_data(data: ByteArray<N>) -> Self {
200 FixedBitSet { data }
201 }
202
203 #[inline]
205 #[must_use]
206 pub const fn bit_len(&self) -> usize {
207 N
208 }
209
210 #[inline]
212 #[must_use]
213 pub const fn byte_len(&self) -> usize {
214 BYTESIZE::<N>
215 }
216
217 #[inline]
219 #[must_use]
220 pub fn index(&self, index: usize) -> bool {
221 (self.data[index / 8] & (1u8 << (index % 8))) != 0
222 }
223
224 #[inline]
230 pub fn set(&mut self, bit_index: usize) {
231 assert!(bit_index < N, "Out of bounds write to FixedBitSet!");
232
233 self.data[bit_index / 8] |= 1u8 << (bit_index % 8);
234 }
235 #[inline]
236 pub fn unset(&mut self, bit_index: usize) {
237 let byte = &mut self.data[bit_index / 8];
238 *byte = !((!*byte) | (1u8 << (bit_index % 8)));
239 }
240 #[inline]
241 pub fn set_to(&mut self, bit_index: usize, value: bool) {
242 if value {
243 self.set(bit_index);
244 } else {
245 self.unset(bit_index);
246 }
247 }
248}
249
250impl<const N: usize> AzBuf for FixedBitSet<N> {
251 fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
252 let mut data = [0; _];
253 for item in data.iter_mut() {
254 *item = u8::azalea_read(ctx, buf)?;
255 }
256 Ok(FixedBitSet { data })
257 }
258 #[allow(clippy::needless_range_loop, reason = "Indexing into bitset")]
259 fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
260 for item in self.data {
261 item.azalea_write(ctx, buf)?;
262 }
263 Ok(())
264 }
265}
266impl AzBufVar for FixedBitSet<32>
268where
269 [u8; 8]: Sized,
270{
271 fn azalea_read_var(
272 ctx: azalea_buf::Ctx,
273 buf: &mut Cursor<&[u8]>,
274 ) -> Result<Self, BufReadError> {
275 let data = u32::azalea_read_var(ctx, buf)?;
276 Ok(Self {
277 data: data.to_be_bytes(),
278 })
279 }
280 fn azalea_write_var(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
281 let data = u32::from_be_bytes(self.data);
282 data.azalea_write_var(ctx, buf)
283 }
284}
285
286impl<const N: usize> Default for FixedBitSet<N> {
287 #[inline]
288 fn default() -> Self {
289 Self::new()
290 }
291}
292
293#[derive(Clone, Debug, Eq, Hash, PartialEq)]
301pub struct FastFixedBitSet<const N: usize> {
302 data: LongArray<N>,
303}
304
305type LongArray<const N: usize> = [u64; gca!(LONGSIZE::<N>)];
306const LONGSIZE<const N: usize>: usize = const { N.div_ceil(64) };
307
308impl<const N: usize> FastFixedBitSet<N> {
309 #[must_use]
311 pub const fn new() -> Self {
312 FastFixedBitSet { data: [0; _] }
313 }
314
315 #[inline]
317 #[must_use]
318 pub const fn bit_len(&self) -> usize {
319 N
320 }
321
322 #[inline]
324 #[must_use]
325 pub const fn long_len(&self) -> usize {
326 LONGSIZE::<N>
327 }
328
329 #[inline]
331 #[must_use]
332 pub fn index(&self, index: usize) -> bool {
333 (self.data[index / 64] & (1u64 << (index % 64))) != 0
334 }
335
336 #[inline]
342 pub fn set(&mut self, bit_index: usize) {
343 assert!(bit_index < N, "Out of bounds write to FastFixedBitSet!");
344
345 self.data[bit_index / 64] |= 1u64 << (bit_index % 64);
346 }
347}
348impl<const N: usize> Default for FastFixedBitSet<N> {
349 #[inline]
350 fn default() -> Self {
351 Self::new()
352 }
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358
359 #[test]
360 fn test_bitset() {
361 let mut bitset = JavaBitSet::new(64);
362 assert!(!bitset.index(0));
363 assert!(!bitset.index(1));
364 assert!(!bitset.index(2));
365 bitset.set(1);
366 assert!(!bitset.index(0));
367 assert!(bitset.index(1));
368 assert!(!bitset.index(2));
369 }
370
371 #[test]
372 fn test_clear() {
373 let mut bitset = JavaBitSet::new(128);
374 bitset.set(62);
375 bitset.set(63);
376 bitset.set(64);
377 bitset.set(65);
378 bitset.set(66);
379
380 bitset.clear(63..65);
381
382 assert!(bitset.index(62));
383 assert!(!bitset.index(63));
384 assert!(!bitset.index(64));
385 assert!(bitset.index(65));
386 assert!(bitset.index(66));
387 }
388
389 #[test]
390 fn test_clear_2() {
391 let mut bitset = JavaBitSet::new(128);
392 bitset.set(64);
393 bitset.set(65);
394 bitset.set(66);
395 bitset.set(67);
396 bitset.set(68);
397
398 bitset.clear(65..67);
399
400 assert!(bitset.index(64));
401 assert!(!bitset.index(65));
402 assert!(!bitset.index(66));
403 assert!(bitset.index(67));
404 assert!(bitset.index(68));
405 }
406}