1use crate::bit_iterator::{BitIndexIterator, BitIterator, BitSliceIterator};
6use crate::bit_util;
7use crate::buffer::BooleanBuffer;
8use crate::{Buffer, MutableBuffer, OverflowError};
9
10#[derive(Debug, Clone, Eq, PartialEq)]
22pub struct NullBuffer {
23 buffer: BooleanBuffer,
24 null_count: usize,
25}
26
27impl NullBuffer {
28 pub fn new(buffer: BooleanBuffer) -> Self {
30 let null_count = buffer.len() - buffer.count_set_bits();
31 Self { buffer, null_count }
32 }
33
34 pub fn new_null(len: usize) -> Self {
36 Self {
37 buffer: BooleanBuffer::new_unset(len),
38 null_count: len,
39 }
40 }
41
42 pub fn new_valid(len: usize) -> Self {
47 Self {
48 buffer: BooleanBuffer::new_set(len),
49 null_count: 0,
50 }
51 }
52
53 pub unsafe fn new_unchecked(buffer: BooleanBuffer, null_count: usize) -> Self {
59 if cfg!(feature = "force_validate") {
60 let expected = buffer.len() - buffer.count_set_bits();
61 assert_eq!(null_count, expected, "null_count does not match buffer");
62 }
63 Self { buffer, null_count }
64 }
65
66 pub fn union(lhs: Option<&NullBuffer>, rhs: Option<&NullBuffer>) -> Option<NullBuffer> {
72 match (lhs, rhs) {
73 (Some(lhs), Some(rhs)) if lhs.null_count() > 0 || rhs.null_count() > 0 => {
74 Some(Self::new(lhs.inner() & rhs.inner()))
75 }
76 (Some(n), None) | (None, Some(n)) if n.null_count() > 0 => Some(n.clone()),
77 (_, _) => None,
78 }
79 }
80
81 pub fn union_many<'a>(
85 nulls: impl IntoIterator<Item = Option<&'a NullBuffer>>,
86 ) -> Option<NullBuffer> {
87 let mut buffers = nulls.into_iter().filter_map(|nb| match nb {
89 Some(nb) if nb.null_count > 0 => Some(nb.inner()),
90 _ => None,
91 });
92 let first = buffers.next()?;
93 let mut result = first.clone();
94 for buf in buffers {
95 result &= buf;
96 }
97 Some(Self::new(result))
98 }
99
100 pub fn contains(&self, other: &NullBuffer) -> bool {
102 if other.null_count == 0 {
103 return true;
104 }
105 let lhs = self.inner().bit_chunks().iter_padded();
106 let rhs = other.inner().bit_chunks().iter_padded();
107 lhs.zip(rhs).all(|(l, r)| (l & !r) == 0)
108 }
109
110 pub fn expand(&self, count: usize) -> Self {
120 self.try_expand(count).unwrap_or_else(|err| panic!("{err}"))
121 }
122
123 pub fn try_expand(&self, count: usize) -> Result<Self, OverflowError> {
132 let capacity = self
133 .buffer
134 .len()
135 .checked_mul(count)
136 .ok_or_else(|| OverflowError::new::<usize>("buffer length"))?;
137 let mut buffer = MutableBuffer::try_from_len_zeroed(bit_util::ceil(capacity, 8))
138 .map_err(|_| OverflowError::new::<usize>("buffer length"))?;
139
140 if count.is_multiple_of(8) {
141 let bytes_per_bit = count / 8;
146 let buf = buffer.as_mut();
147 for (start, end) in BitSliceIterator::new(
148 self.buffer.values(),
149 self.buffer.offset(),
150 self.buffer.len(),
151 ) {
152 let byte_start = start * bytes_per_bit;
153 let byte_end = end * bytes_per_bit;
154 buf[byte_start..byte_end].fill(0xFF);
155 }
156 } else if count.is_multiple_of(4) {
157 let buf = buffer.as_mut();
161 for i in 0..self.buffer.len() {
162 if self.is_null(i) {
163 continue;
164 }
165 let start_bit = i * count;
166 let end_bit = start_bit + count;
167 if start_bit.is_multiple_of(8) {
168 buf[start_bit / 8..end_bit / 8].fill(0xFF);
169 buf[end_bit / 8] |= 0x0F;
170 } else {
171 buf[start_bit / 8] |= 0xF0;
172 buf[start_bit / 8 + 1..end_bit / 8].fill(0xFF);
173 }
174 }
175 } else {
176 let buf = buffer.as_mut();
181 for (start, end) in BitSliceIterator::new(
182 self.buffer.values(),
183 self.buffer.offset(),
184 self.buffer.len(),
185 ) {
186 let start_bit = start * count;
187 let end_bit = end * count;
188 let start_byte = start_bit / 8;
189 let start_offset = (start_bit % 8) as u32; let end_byte = end_bit / 8;
191 let end_offset = (end_bit % 8) as u32; if start_byte == end_byte {
194 buf[start_byte] |= (0xFFu8 << start_offset) & ((1u8 << end_offset) - 1);
199 } else {
200 if start_offset != 0 {
201 buf[start_byte] |= 0xFFu8 << start_offset;
203 }
204 let full_start = start_byte + (start_offset != 0) as usize;
206 buf[full_start..end_byte].fill(0xFF);
207 if end_offset != 0 {
208 buf[end_byte] |= (1u8 << end_offset) - 1;
211 }
212 }
213 }
214 }
215 Ok(Self {
216 buffer: BooleanBuffer::new(buffer.into(), 0, capacity),
217 null_count: self.null_count * count,
218 })
219 }
220
221 #[inline]
223 pub fn len(&self) -> usize {
224 self.buffer.len()
225 }
226
227 #[inline]
229 pub fn offset(&self) -> usize {
230 self.buffer.offset()
231 }
232
233 #[inline]
235 pub fn is_empty(&self) -> bool {
236 self.buffer.is_empty()
237 }
238
239 pub fn shrink_to_fit(&mut self) {
241 self.buffer.shrink_to_fit();
242 }
243
244 #[inline]
246 pub fn null_count(&self) -> usize {
247 self.null_count
248 }
249
250 #[inline]
256 pub fn is_valid(&self, idx: usize) -> bool {
257 self.buffer.value(idx)
258 }
259
260 #[inline]
266 pub fn is_null(&self, idx: usize) -> bool {
267 !self.is_valid(idx)
268 }
269
270 #[inline]
272 pub fn validity(&self) -> &[u8] {
273 self.buffer.values()
274 }
275
276 pub fn slice(&self, offset: usize, len: usize) -> Self {
282 Self::new(self.buffer.slice(offset, len))
283 }
284
285 pub fn iter(&self) -> BitIterator<'_> {
292 self.buffer.iter()
293 }
294
295 pub fn valid_indices(&self) -> BitIndexIterator<'_> {
299 self.buffer.set_indices()
300 }
301
302 pub fn valid_slices(&self) -> BitSliceIterator<'_> {
306 self.buffer.set_slices()
307 }
308
309 #[inline]
311 pub fn try_for_each_valid_idx<E, F: FnMut(usize) -> Result<(), E>>(
312 &self,
313 f: F,
314 ) -> Result<(), E> {
315 if self.null_count == self.len() {
316 return Ok(());
317 }
318 self.valid_indices().try_for_each(f)
319 }
320
321 #[inline]
323 pub fn inner(&self) -> &BooleanBuffer {
324 &self.buffer
325 }
326
327 #[inline]
329 pub fn into_inner(self) -> BooleanBuffer {
330 self.buffer
331 }
332
333 #[inline]
335 pub fn buffer(&self) -> &Buffer {
336 self.buffer.inner()
337 }
338
339 pub fn from_unsliced_buffer(buffer: impl Into<Buffer>, len: usize) -> Option<Self> {
343 let bb = BooleanBuffer::new(buffer.into(), 0, len);
344 let nb = NullBuffer::new(bb);
345 (nb.null_count() > 0).then_some(nb)
346 }
347
348 #[cfg(feature = "pool")]
350 pub fn claim(&self, pool: &dyn crate::MemoryPool) {
351 self.buffer.inner().claim(pool);
353 }
354}
355
356impl<'a> IntoIterator for &'a NullBuffer {
357 type Item = bool;
358 type IntoIter = BitIterator<'a>;
359
360 fn into_iter(self) -> Self::IntoIter {
361 self.buffer.iter()
362 }
363}
364
365impl From<BooleanBuffer> for NullBuffer {
366 fn from(value: BooleanBuffer) -> Self {
367 Self::new(value)
368 }
369}
370
371impl From<&[bool]> for NullBuffer {
372 fn from(value: &[bool]) -> Self {
373 BooleanBuffer::from(value).into()
374 }
375}
376
377impl<const N: usize> From<&[bool; N]> for NullBuffer {
378 fn from(value: &[bool; N]) -> Self {
379 value[..].into()
380 }
381}
382
383impl From<Vec<bool>> for NullBuffer {
384 fn from(value: Vec<bool>) -> Self {
385 BooleanBuffer::from(value).into()
386 }
387}
388
389impl FromIterator<bool> for NullBuffer {
390 fn from_iter<T: IntoIterator<Item = bool>>(iter: T) -> Self {
391 BooleanBuffer::from_iter(iter).into()
392 }
393}
394
395#[cfg(test)]
396mod tests {
397 use super::*;
398
399 #[test]
400 fn test_size() {
401 assert_eq!(
403 std::mem::size_of::<NullBuffer>(),
404 std::mem::size_of::<Option<NullBuffer>>()
405 );
406 }
407
408 #[test]
409 fn test_from_unsliced_buffer_with_nulls() {
410 let buf = Buffer::from([0b10110010u8]);
412 let result = NullBuffer::from_unsliced_buffer(buf, 8);
413 assert!(result.is_some());
414 let nb = result.unwrap();
415 assert_eq!(nb.len(), 8);
416 assert_eq!(nb.null_count(), 4);
417 assert!(nb.is_null(0));
418 assert!(nb.is_valid(1));
419 assert!(nb.is_null(2));
420 assert!(nb.is_null(3));
421 assert!(nb.is_valid(4));
422 assert!(nb.is_valid(5));
423 assert!(nb.is_null(6));
424 assert!(nb.is_valid(7));
425 }
426
427 #[test]
428 fn test_from_unsliced_buffer_all_valid() {
429 let buf = Buffer::from([0b11111111u8]);
431 let result = NullBuffer::from_unsliced_buffer(buf, 8);
432 assert!(result.is_none());
433 }
434
435 #[test]
436 fn test_from_unsliced_buffer_all_null() {
437 let buf = Buffer::from([0b00000000u8]);
439 let result = NullBuffer::from_unsliced_buffer(buf, 8);
440 assert!(result.is_some());
441 let nb = result.unwrap();
442 assert_eq!(nb.len(), 8);
443 assert_eq!(nb.null_count(), 8);
444 }
445
446 #[test]
447 fn test_from_unsliced_buffer_empty() {
448 let buf = Buffer::from([]);
449 let result = NullBuffer::from_unsliced_buffer(buf, 0);
450 assert!(result.is_none());
451 }
452
453 #[test]
454 fn test_union_many_all_none() {
455 let result = NullBuffer::union_many([None, None, None]);
456 assert!(result.is_none());
457 }
458
459 #[test]
460 fn test_union_many_single_some() {
461 let a = NullBuffer::from(&[true, false, true, true]);
462 let result = NullBuffer::union_many([Some(&a)]);
463 assert_eq!(result, Some(a));
464 }
465
466 #[test]
467 fn test_union_many_two_inputs() {
468 let a = NullBuffer::from(&[true, false, true, true]);
469 let b = NullBuffer::from(&[true, true, false, true]);
470 let result = NullBuffer::union_many([Some(&a), Some(&b)]);
471 let expected = NullBuffer::union(Some(&a), Some(&b));
472 assert_eq!(result, expected);
473 }
474
475 #[test]
476 fn test_union_many_three_inputs() {
477 let a = NullBuffer::from(&[true, false, true, true]);
478 let b = NullBuffer::from(&[true, true, false, true]);
479 let c = NullBuffer::from(&[false, true, true, true]);
480 let result = NullBuffer::union_many([Some(&a), Some(&b), Some(&c)]);
481 let expected = NullBuffer::from(&[false, false, false, true]);
482 assert_eq!(result, Some(expected));
483 }
484
485 #[test]
486 fn test_union_many_mixed_none() {
487 let a = NullBuffer::from(&[true, false, true, true]);
488 let b = NullBuffer::from(&[false, true, true, true]);
489 let result = NullBuffer::union_many([Some(&a), None, Some(&b)]);
490 let expected = NullBuffer::union(Some(&a), Some(&b));
491 assert_eq!(result, expected);
492 }
493
494 #[test]
495 fn test_union_many_empty_slice() {
496 let result = NullBuffer::union_many([] as [Option<&NullBuffer>; 0]);
497 assert!(result.is_none());
498 }
499
500 #[test]
501 fn test_union_many_no_nulls() {
502 let a = NullBuffer::from(&[true, true, true, true]);
503
504 let result = NullBuffer::union_many([Some(&a), Some(&a), Some(&a)]);
505 assert_eq!(result, None);
506 }
507
508 #[test]
509 fn test_union_no_nulls() {
510 let a = NullBuffer::from(&[true, true, true, true]);
511
512 let result = NullBuffer::union(Some(&a), Some(&a));
513 assert_eq!(result, None);
514
515 let result = NullBuffer::union(Some(&a), None);
516 assert_eq!(result, None);
517
518 let result = NullBuffer::union(None, Some(&a));
519 assert_eq!(result, None);
520 }
521
522 #[test]
523 fn test_union_nulls_one_side() {
524 let all_valid = NullBuffer::from(&[true, true, true, true]);
525 let all_null = NullBuffer::from(&[false, false, false, false]);
526
527 let result = NullBuffer::union(Some(&all_valid), Some(&all_null));
528 assert_eq!(result, Some(all_null.clone()));
529
530 let result = NullBuffer::union(Some(&all_null), Some(&all_valid));
531 assert_eq!(result, Some(all_null.clone()));
532 }
533
534 #[test]
535 fn test_expand_code_paths() {
536 let source = NullBuffer::from(&[true, false, true] as &[bool]);
537
538 for count in [8, 4, 3] {
539 let expanded = source.expand(count);
540 assert_eq!(expanded.len(), 3 * count);
541 assert_eq!(expanded.null_count(), count);
542 assert!((0..count).all(|i| expanded.is_valid(i)));
543 assert!((count..2 * count).all(|i| expanded.is_null(i)));
544 assert!((2 * count..3 * count).all(|i| expanded.is_valid(i)));
545 }
546 }
547
548 #[test]
549 #[should_panic(expected = "null_count does not match buffer")]
550 #[cfg(feature = "force_validate")]
551 fn new_unchecked_wrong_null_count_force_validate() {
552 let buffer = BooleanBuffer::from(vec![true, false, true]);
553 unsafe { NullBuffer::new_unchecked(buffer, 0) };
554 }
555}