arrow_array/array/
boolean_array.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::array::print_long_array;
19use crate::builder::BooleanBuilder;
20use crate::iterator::BooleanIter;
21use crate::{Array, ArrayAccessor, ArrayRef, Scalar};
22use arrow_buffer::{BooleanBuffer, Buffer, MutableBuffer, NullBuffer, bit_util};
23use arrow_data::{ArrayData, ArrayDataBuilder};
24use arrow_schema::DataType;
25use std::any::Any;
26use std::sync::Arc;
27
28/// An array of [boolean values](https://arrow.apache.org/docs/format/Columnar.html#fixed-size-primitive-layout)
29///
30/// # Example: From a Vec
31///
32/// ```
33/// # use arrow_array::{Array, BooleanArray};
34/// let arr: BooleanArray = vec![true, true, false].into();
35/// ```
36///
37/// # Example: From an optional Vec
38///
39/// ```
40/// # use arrow_array::{Array, BooleanArray};
41/// let arr: BooleanArray = vec![Some(true), None, Some(false)].into();
42/// ```
43///
44/// # Example: From an iterator
45///
46/// ```
47/// # use arrow_array::{Array, BooleanArray};
48/// let arr: BooleanArray = (0..5).map(|x| (x % 2 == 0).then(|| x % 3 == 0)).collect();
49/// let values: Vec<_> = arr.iter().collect();
50/// assert_eq!(&values, &[Some(true), None, Some(false), None, Some(false)])
51/// ```
52///
53/// # Example: Using Builder
54///
55/// ```
56/// # use arrow_array::Array;
57/// # use arrow_array::builder::BooleanBuilder;
58/// let mut builder = BooleanBuilder::new();
59/// builder.append_value(true);
60/// builder.append_null();
61/// builder.append_value(false);
62/// let array = builder.finish();
63/// let values: Vec<_> = array.iter().collect();
64/// assert_eq!(&values, &[Some(true), None, Some(false)])
65/// ```
66///
67#[derive(Clone)]
68pub struct BooleanArray {
69    values: BooleanBuffer,
70    nulls: Option<NullBuffer>,
71}
72
73impl std::fmt::Debug for BooleanArray {
74    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
75        write!(f, "BooleanArray\n[\n")?;
76        print_long_array(self, f, |array, index, f| {
77            std::fmt::Debug::fmt(&array.value(index), f)
78        })?;
79        write!(f, "]")
80    }
81}
82
83impl BooleanArray {
84    /// Create a new [`BooleanArray`] from the provided values and nulls
85    ///
86    /// # Panics
87    ///
88    /// Panics if `values.len() != nulls.len()`
89    pub fn new(values: BooleanBuffer, nulls: Option<NullBuffer>) -> Self {
90        if let Some(n) = nulls.as_ref() {
91            assert_eq!(values.len(), n.len());
92        }
93        Self { values, nulls }
94    }
95
96    /// Create a new [`BooleanArray`] with length `len` consisting only of nulls
97    pub fn new_null(len: usize) -> Self {
98        Self {
99            values: BooleanBuffer::new_unset(len),
100            nulls: Some(NullBuffer::new_null(len)),
101        }
102    }
103
104    /// Create a new [`Scalar`] from `value`
105    pub fn new_scalar(value: bool) -> Scalar<Self> {
106        let values = match value {
107            true => BooleanBuffer::new_set(1),
108            false => BooleanBuffer::new_unset(1),
109        };
110        Scalar::new(Self::new(values, None))
111    }
112
113    /// Create a new [`BooleanArray`] from a [`Buffer`] specified by `offset` and `len`, the `offset` and `len` in bits
114    /// Logically convert each bit in [`Buffer`] to boolean and use it to build [`BooleanArray`].
115    /// using this method will make the following points self-evident:
116    /// * there is no `null` in the constructed [`BooleanArray`];
117    /// * without considering `buffer.into()`, this method is efficient because there is no need to perform pack and unpack operations on boolean;
118    pub fn new_from_packed(buffer: impl Into<Buffer>, offset: usize, len: usize) -> Self {
119        BooleanBuffer::new(buffer.into(), offset, len).into()
120    }
121
122    /// Create a new [`BooleanArray`] from `&[u8]`
123    /// This method uses `new_from_packed` and constructs a [`Buffer`] using `value`, and offset is set to 0 and len is set to `value.len() * 8`
124    /// using this method will make the following points self-evident:
125    /// * there is no `null` in the constructed [`BooleanArray`];
126    /// * the length of the constructed [`BooleanArray`] is always a multiple of 8;
127    pub fn new_from_u8(value: &[u8]) -> Self {
128        BooleanBuffer::new(Buffer::from(value), 0, value.len() * 8).into()
129    }
130
131    /// Returns the length of this array.
132    pub fn len(&self) -> usize {
133        self.values.len()
134    }
135
136    /// Returns whether this array is empty.
137    pub fn is_empty(&self) -> bool {
138        self.values.is_empty()
139    }
140
141    /// Returns a zero-copy slice of this array with the indicated offset and length.
142    pub fn slice(&self, offset: usize, length: usize) -> Self {
143        Self {
144            values: self.values.slice(offset, length),
145            nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
146        }
147    }
148
149    /// Returns a new boolean array builder
150    pub fn builder(capacity: usize) -> BooleanBuilder {
151        BooleanBuilder::with_capacity(capacity)
152    }
153
154    /// Returns the underlying [`BooleanBuffer`] holding all the values of this array
155    pub fn values(&self) -> &BooleanBuffer {
156        &self.values
157    }
158
159    /// Returns the number of non null, true values within this array
160    pub fn true_count(&self) -> usize {
161        match self.nulls() {
162            Some(nulls) => {
163                let null_chunks = nulls.inner().bit_chunks().iter_padded();
164                let value_chunks = self.values().bit_chunks().iter_padded();
165                null_chunks
166                    .zip(value_chunks)
167                    .map(|(a, b)| (a & b).count_ones() as usize)
168                    .sum()
169            }
170            None => self.values().count_set_bits(),
171        }
172    }
173
174    /// Returns the number of non null, false values within this array
175    pub fn false_count(&self) -> usize {
176        self.len() - self.null_count() - self.true_count()
177    }
178
179    /// Returns the boolean value at index `i`.
180    ///
181    /// Note: This method does not check for nulls and the value is arbitrary
182    /// if [`is_null`](Self::is_null) returns true for the index.
183    ///
184    /// # Safety
185    /// This doesn't check bounds, the caller must ensure that index < self.len()
186    pub unsafe fn value_unchecked(&self, i: usize) -> bool {
187        unsafe { self.values.value_unchecked(i) }
188    }
189
190    /// Returns the boolean value at index `i`.
191    ///
192    /// Note: This method does not check for nulls and the value is arbitrary
193    /// if [`is_null`](Self::is_null) returns true for the index.
194    ///
195    /// # Panics
196    /// Panics if index `i` is out of bounds
197    pub fn value(&self, i: usize) -> bool {
198        assert!(
199            i < self.len(),
200            "Trying to access an element at index {} from a BooleanArray of length {}",
201            i,
202            self.len()
203        );
204        // Safety:
205        // `i < self.len()
206        unsafe { self.value_unchecked(i) }
207    }
208
209    /// Returns an iterator that returns the values of `array.value(i)` for an iterator with each element `i`
210    pub fn take_iter<'a>(
211        &'a self,
212        indexes: impl Iterator<Item = Option<usize>> + 'a,
213    ) -> impl Iterator<Item = Option<bool>> + 'a {
214        indexes.map(|opt_index| opt_index.map(|index| self.value(index)))
215    }
216
217    /// Returns an iterator that returns the values of `array.value(i)` for an iterator with each element `i`
218    /// # Safety
219    ///
220    /// caller must ensure that the offsets in the iterator are less than the array len()
221    pub unsafe fn take_iter_unchecked<'a>(
222        &'a self,
223        indexes: impl Iterator<Item = Option<usize>> + 'a,
224    ) -> impl Iterator<Item = Option<bool>> + 'a {
225        indexes.map(|opt_index| opt_index.map(|index| unsafe { self.value_unchecked(index) }))
226    }
227
228    /// Create a [`BooleanArray`] by evaluating the operation for
229    /// each element of the provided array
230    ///
231    /// ```
232    /// # use arrow_array::{BooleanArray, Int32Array};
233    ///
234    /// let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
235    /// let r = BooleanArray::from_unary(&array, |x| x > 2);
236    /// assert_eq!(&r, &BooleanArray::from(vec![false, false, true, true, true]));
237    /// ```
238    pub fn from_unary<T: ArrayAccessor, F>(left: T, mut op: F) -> Self
239    where
240        F: FnMut(T::Item) -> bool,
241    {
242        let nulls = left.logical_nulls();
243        let values = BooleanBuffer::collect_bool(left.len(), |i| unsafe {
244            // SAFETY: i in range 0..len
245            op(left.value_unchecked(i))
246        });
247        Self::new(values, nulls)
248    }
249
250    /// Create a [`BooleanArray`] by evaluating the binary operation for
251    /// each element of the provided arrays
252    ///
253    /// ```
254    /// # use arrow_array::{BooleanArray, Int32Array};
255    ///
256    /// let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
257    /// let b = Int32Array::from(vec![1, 2, 0, 2, 5]);
258    /// let r = BooleanArray::from_binary(&a, &b, |a, b| a == b);
259    /// assert_eq!(&r, &BooleanArray::from(vec![true, true, false, false, true]));
260    /// ```
261    ///
262    /// # Panics
263    ///
264    /// This function panics if left and right are not the same length
265    ///
266    pub fn from_binary<T: ArrayAccessor, S: ArrayAccessor, F>(left: T, right: S, mut op: F) -> Self
267    where
268        F: FnMut(T::Item, S::Item) -> bool,
269    {
270        assert_eq!(left.len(), right.len());
271
272        let nulls = NullBuffer::union(
273            left.logical_nulls().as_ref(),
274            right.logical_nulls().as_ref(),
275        );
276        let values = BooleanBuffer::collect_bool(left.len(), |i| unsafe {
277            // SAFETY: i in range 0..len
278            op(left.value_unchecked(i), right.value_unchecked(i))
279        });
280        Self::new(values, nulls)
281    }
282
283    /// Deconstruct this array into its constituent parts
284    pub fn into_parts(self) -> (BooleanBuffer, Option<NullBuffer>) {
285        (self.values, self.nulls)
286    }
287}
288
289impl super::private::Sealed for BooleanArray {}
290
291impl Array for BooleanArray {
292    fn as_any(&self) -> &dyn Any {
293        self
294    }
295
296    fn to_data(&self) -> ArrayData {
297        self.clone().into()
298    }
299
300    fn into_data(self) -> ArrayData {
301        self.into()
302    }
303
304    fn data_type(&self) -> &DataType {
305        &DataType::Boolean
306    }
307
308    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
309        Arc::new(self.slice(offset, length))
310    }
311
312    fn len(&self) -> usize {
313        self.values.len()
314    }
315
316    fn is_empty(&self) -> bool {
317        self.values.is_empty()
318    }
319
320    fn shrink_to_fit(&mut self) {
321        self.values.shrink_to_fit();
322        if let Some(nulls) = &mut self.nulls {
323            nulls.shrink_to_fit();
324        }
325    }
326
327    fn offset(&self) -> usize {
328        self.values.offset()
329    }
330
331    fn nulls(&self) -> Option<&NullBuffer> {
332        self.nulls.as_ref()
333    }
334
335    fn logical_null_count(&self) -> usize {
336        self.null_count()
337    }
338
339    fn get_buffer_memory_size(&self) -> usize {
340        let mut sum = self.values.inner().capacity();
341        if let Some(x) = &self.nulls {
342            sum += x.buffer().capacity()
343        }
344        sum
345    }
346
347    fn get_array_memory_size(&self) -> usize {
348        std::mem::size_of::<Self>() + self.get_buffer_memory_size()
349    }
350}
351
352impl ArrayAccessor for &BooleanArray {
353    type Item = bool;
354
355    fn value(&self, index: usize) -> Self::Item {
356        BooleanArray::value(self, index)
357    }
358
359    unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
360        unsafe { BooleanArray::value_unchecked(self, index) }
361    }
362}
363
364impl From<Vec<bool>> for BooleanArray {
365    fn from(data: Vec<bool>) -> Self {
366        let mut mut_buf = MutableBuffer::new_null(data.len());
367        {
368            let mut_slice = mut_buf.as_slice_mut();
369            for (i, b) in data.iter().enumerate() {
370                if *b {
371                    bit_util::set_bit(mut_slice, i);
372                }
373            }
374        }
375        let array_data = ArrayData::builder(DataType::Boolean)
376            .len(data.len())
377            .add_buffer(mut_buf.into());
378
379        let array_data = unsafe { array_data.build_unchecked() };
380        BooleanArray::from(array_data)
381    }
382}
383
384impl From<Vec<Option<bool>>> for BooleanArray {
385    fn from(data: Vec<Option<bool>>) -> Self {
386        data.iter().collect()
387    }
388}
389
390impl From<ArrayData> for BooleanArray {
391    fn from(data: ArrayData) -> Self {
392        assert_eq!(
393            data.data_type(),
394            &DataType::Boolean,
395            "BooleanArray expected ArrayData with type {} got {}",
396            DataType::Boolean,
397            data.data_type()
398        );
399        assert_eq!(
400            data.buffers().len(),
401            1,
402            "BooleanArray data should contain a single buffer only (values buffer)"
403        );
404        let values = BooleanBuffer::new(data.buffers()[0].clone(), data.offset(), data.len());
405
406        Self {
407            values,
408            nulls: data.nulls().cloned(),
409        }
410    }
411}
412
413impl From<BooleanArray> for ArrayData {
414    fn from(array: BooleanArray) -> Self {
415        let builder = ArrayDataBuilder::new(DataType::Boolean)
416            .len(array.values.len())
417            .offset(array.values.offset())
418            .nulls(array.nulls)
419            .buffers(vec![array.values.into_inner()]);
420
421        unsafe { builder.build_unchecked() }
422    }
423}
424
425impl<'a> IntoIterator for &'a BooleanArray {
426    type Item = Option<bool>;
427    type IntoIter = BooleanIter<'a>;
428
429    fn into_iter(self) -> Self::IntoIter {
430        BooleanIter::<'a>::new(self)
431    }
432}
433
434impl<'a> BooleanArray {
435    /// constructs a new iterator
436    pub fn iter(&'a self) -> BooleanIter<'a> {
437        BooleanIter::<'a>::new(self)
438    }
439}
440
441/// An optional boolean value
442///
443/// This struct is used as an adapter when creating `BooleanArray` from an iterator.
444/// `FromIterator` for `BooleanArray` takes an iterator where the elements can be `into`
445/// this struct. So once implementing `From` or `Into` trait for a type, an iterator of
446/// the type can be collected to `BooleanArray`.
447///
448/// See also [NativeAdapter](crate::array::NativeAdapter).
449#[derive(Debug)]
450struct BooleanAdapter {
451    /// Corresponding Rust native type if available
452    pub native: Option<bool>,
453}
454
455impl From<bool> for BooleanAdapter {
456    fn from(value: bool) -> Self {
457        BooleanAdapter {
458            native: Some(value),
459        }
460    }
461}
462
463impl From<&bool> for BooleanAdapter {
464    fn from(value: &bool) -> Self {
465        BooleanAdapter {
466            native: Some(*value),
467        }
468    }
469}
470
471impl From<Option<bool>> for BooleanAdapter {
472    fn from(value: Option<bool>) -> Self {
473        BooleanAdapter { native: value }
474    }
475}
476
477impl From<&Option<bool>> for BooleanAdapter {
478    fn from(value: &Option<bool>) -> Self {
479        BooleanAdapter { native: *value }
480    }
481}
482
483impl<Ptr: Into<BooleanAdapter>> FromIterator<Ptr> for BooleanArray {
484    fn from_iter<I: IntoIterator<Item = Ptr>>(iter: I) -> Self {
485        let iter = iter.into_iter();
486        let capacity = match iter.size_hint() {
487            (lower, Some(upper)) if lower == upper => lower,
488            _ => 0,
489        };
490        let mut builder = BooleanBuilder::with_capacity(capacity);
491        builder.extend(iter.map(|item| item.into().native));
492        builder.finish()
493    }
494}
495
496impl BooleanArray {
497    /// Creates a [`BooleanArray`] from an iterator of trusted length.
498    ///
499    /// # Safety
500    ///
501    /// The iterator must be [`TrustedLen`](https://doc.rust-lang.org/std/iter/trait.TrustedLen.html).
502    /// I.e. that `size_hint().1` correctly reports its length. Note that this is a stronger
503    /// guarantee that `ExactSizeIterator` provides which could still report a wrong length.
504    ///
505    /// # Panics
506    ///
507    /// Panics if the iterator does not report an upper bound on `size_hint()`.
508    #[inline]
509    #[allow(
510        private_bounds,
511        reason = "We will expose BooleanAdapter if there is a need"
512    )]
513    pub unsafe fn from_trusted_len_iter<I, P>(iter: I) -> Self
514    where
515        P: Into<BooleanAdapter>,
516        I: ExactSizeIterator<Item = P>,
517    {
518        let data_len = iter.len();
519
520        let num_bytes = bit_util::ceil(data_len, 8);
521        let mut null_builder = MutableBuffer::from_len_zeroed(num_bytes);
522        let mut val_builder = MutableBuffer::from_len_zeroed(num_bytes);
523
524        let data = val_builder.as_slice_mut();
525
526        let null_slice = null_builder.as_slice_mut();
527        iter.enumerate().for_each(|(i, item)| {
528            if let Some(a) = item.into().native {
529                unsafe {
530                    // SAFETY: There will be enough space in the buffers due to the trusted len size
531                    // hint
532                    bit_util::set_bit_raw(null_slice.as_mut_ptr(), i);
533                    if a {
534                        bit_util::set_bit_raw(data.as_mut_ptr(), i);
535                    }
536                }
537            }
538        });
539
540        let data = unsafe {
541            ArrayData::new_unchecked(
542                DataType::Boolean,
543                data_len,
544                None,
545                Some(null_builder.into()),
546                0,
547                vec![val_builder.into()],
548                vec![],
549            )
550        };
551        BooleanArray::from(data)
552    }
553}
554
555impl From<BooleanBuffer> for BooleanArray {
556    fn from(values: BooleanBuffer) -> Self {
557        Self {
558            values,
559            nulls: None,
560        }
561    }
562}
563
564#[cfg(test)]
565mod tests {
566    use super::*;
567    use arrow_buffer::Buffer;
568    use rand::{Rng, rng};
569
570    #[test]
571    fn test_boolean_fmt_debug() {
572        let arr = BooleanArray::from(vec![true, false, false]);
573        assert_eq!(
574            "BooleanArray\n[\n  true,\n  false,\n  false,\n]",
575            format!("{arr:?}")
576        );
577    }
578
579    #[test]
580    fn test_boolean_with_null_fmt_debug() {
581        let mut builder = BooleanArray::builder(3);
582        builder.append_value(true);
583        builder.append_null();
584        builder.append_value(false);
585        let arr = builder.finish();
586        assert_eq!(
587            "BooleanArray\n[\n  true,\n  null,\n  false,\n]",
588            format!("{arr:?}")
589        );
590    }
591
592    #[test]
593    fn test_boolean_array_from_vec() {
594        let buf = Buffer::from([10_u8]);
595        let arr = BooleanArray::from(vec![false, true, false, true]);
596        assert_eq!(&buf, arr.values().inner());
597        assert_eq!(4, arr.len());
598        assert_eq!(0, arr.offset());
599        assert_eq!(0, arr.null_count());
600        for i in 0..4 {
601            assert!(!arr.is_null(i));
602            assert!(arr.is_valid(i));
603            assert_eq!(i == 1 || i == 3, arr.value(i), "failed at {i}")
604        }
605    }
606
607    #[test]
608    fn test_boolean_array_from_vec_option() {
609        let buf = Buffer::from([10_u8]);
610        let arr = BooleanArray::from(vec![Some(false), Some(true), None, Some(true)]);
611        assert_eq!(&buf, arr.values().inner());
612        assert_eq!(4, arr.len());
613        assert_eq!(0, arr.offset());
614        assert_eq!(1, arr.null_count());
615        for i in 0..4 {
616            if i == 2 {
617                assert!(arr.is_null(i));
618                assert!(!arr.is_valid(i));
619            } else {
620                assert!(!arr.is_null(i));
621                assert!(arr.is_valid(i));
622                assert_eq!(i == 1 || i == 3, arr.value(i), "failed at {i}")
623            }
624        }
625    }
626
627    #[test]
628    fn test_boolean_array_from_packed() {
629        let v = [1_u8, 2_u8, 3_u8];
630        let arr = BooleanArray::new_from_packed(v, 0, 24);
631        assert_eq!(24, arr.len());
632        assert_eq!(0, arr.offset());
633        assert_eq!(0, arr.null_count());
634        assert!(arr.nulls.is_none());
635        for i in 0..24 {
636            assert!(!arr.is_null(i));
637            assert!(arr.is_valid(i));
638            assert_eq!(
639                i == 0 || i == 9 || i == 16 || i == 17,
640                arr.value(i),
641                "failed t {i}"
642            )
643        }
644    }
645
646    #[test]
647    fn test_boolean_array_from_slice_u8() {
648        let v: Vec<u8> = vec![1, 2, 3];
649        let slice = &v[..];
650        let arr = BooleanArray::new_from_u8(slice);
651        assert_eq!(24, arr.len());
652        assert_eq!(0, arr.offset());
653        assert_eq!(0, arr.null_count());
654        assert!(arr.nulls().is_none());
655        for i in 0..24 {
656            assert!(!arr.is_null(i));
657            assert!(arr.is_valid(i));
658            assert_eq!(
659                i == 0 || i == 9 || i == 16 || i == 17,
660                arr.value(i),
661                "failed t {i}"
662            )
663        }
664    }
665
666    #[test]
667    fn test_boolean_array_from_iter() {
668        let v = vec![Some(false), Some(true), Some(false), Some(true)];
669        let arr = v.into_iter().collect::<BooleanArray>();
670        assert_eq!(4, arr.len());
671        assert_eq!(0, arr.offset());
672        assert_eq!(0, arr.null_count());
673        assert!(arr.nulls().is_none());
674        for i in 0..3 {
675            assert!(!arr.is_null(i));
676            assert!(arr.is_valid(i));
677            assert_eq!(i == 1 || i == 3, arr.value(i), "failed at {i}")
678        }
679    }
680
681    #[test]
682    fn test_boolean_array_from_non_nullable_iter() {
683        let v = vec![true, false, true];
684        let arr = v.into_iter().collect::<BooleanArray>();
685        assert_eq!(3, arr.len());
686        assert_eq!(0, arr.offset());
687        assert_eq!(0, arr.null_count());
688        assert!(arr.nulls().is_none());
689
690        assert!(arr.value(0));
691        assert!(!arr.value(1));
692        assert!(arr.value(2));
693    }
694
695    #[test]
696    fn test_boolean_array_from_nullable_iter() {
697        let v = vec![Some(true), None, Some(false), None];
698        let arr = v.into_iter().collect::<BooleanArray>();
699        assert_eq!(4, arr.len());
700        assert_eq!(0, arr.offset());
701        assert_eq!(2, arr.null_count());
702        assert!(arr.nulls().is_some());
703
704        assert!(arr.is_valid(0));
705        assert!(arr.is_null(1));
706        assert!(arr.is_valid(2));
707        assert!(arr.is_null(3));
708
709        assert!(arr.value(0));
710        assert!(!arr.value(2));
711    }
712
713    #[test]
714    fn test_boolean_array_from_nullable_trusted_len_iter() {
715        // Should exhibit the same behavior as `from_iter`, which is tested above.
716        let v = vec![Some(true), None, Some(false), None];
717        let expected = v.clone().into_iter().collect::<BooleanArray>();
718        let actual = unsafe {
719            // SAFETY: `v` has trusted length
720            BooleanArray::from_trusted_len_iter(v.into_iter())
721        };
722        assert_eq!(expected, actual);
723    }
724
725    #[test]
726    fn test_boolean_array_from_iter_with_larger_upper_bound() {
727        // See https://github.com/apache/arrow-rs/issues/8505
728        // This returns an upper size hint of 4
729        let iterator = vec![Some(true), None, Some(false), None]
730            .into_iter()
731            .filter(Option::is_some);
732        let arr = iterator.collect::<BooleanArray>();
733        assert_eq!(2, arr.len());
734    }
735
736    #[test]
737    fn test_boolean_array_builder() {
738        // Test building a boolean array with ArrayData builder and offset
739        // 000011011
740        let buf = Buffer::from([27_u8]);
741        let buf2 = buf.clone();
742        let data = ArrayData::builder(DataType::Boolean)
743            .len(5)
744            .offset(2)
745            .add_buffer(buf)
746            .build()
747            .unwrap();
748        let arr = BooleanArray::from(data);
749        assert_eq!(&buf2, arr.values().inner());
750        assert_eq!(5, arr.len());
751        assert_eq!(2, arr.offset());
752        assert_eq!(0, arr.null_count());
753        for i in 0..3 {
754            assert_eq!(i != 0, arr.value(i), "failed at {i}");
755        }
756    }
757
758    #[test]
759    #[should_panic(
760        expected = "Trying to access an element at index 4 from a BooleanArray of length 3"
761    )]
762    fn test_fixed_size_binary_array_get_value_index_out_of_bound() {
763        let v = vec![Some(true), None, Some(false)];
764        let array = v.into_iter().collect::<BooleanArray>();
765
766        array.value(4);
767    }
768
769    #[test]
770    #[should_panic(expected = "BooleanArray data should contain a single buffer only \
771                               (values buffer)")]
772    // Different error messages, so skip for now
773    // https://github.com/apache/arrow-rs/issues/1545
774    #[cfg(not(feature = "force_validate"))]
775    fn test_boolean_array_invalid_buffer_len() {
776        let data = unsafe {
777            ArrayData::builder(DataType::Boolean)
778                .len(5)
779                .build_unchecked()
780        };
781        drop(BooleanArray::from(data));
782    }
783
784    #[test]
785    #[should_panic(expected = "BooleanArray expected ArrayData with type Boolean got Int32")]
786    fn test_from_array_data_validation() {
787        let _ = BooleanArray::from(ArrayData::new_empty(&DataType::Int32));
788    }
789
790    #[test]
791    #[cfg_attr(miri, ignore)] // Takes too long
792    fn test_true_false_count() {
793        let mut rng = rng();
794
795        for _ in 0..10 {
796            // No nulls
797            let d: Vec<_> = (0..2000).map(|_| rng.random_bool(0.5)).collect();
798            let b = BooleanArray::from(d.clone());
799
800            let expected_true = d.iter().filter(|x| **x).count();
801            assert_eq!(b.true_count(), expected_true);
802            assert_eq!(b.false_count(), d.len() - expected_true);
803
804            // With nulls
805            let d: Vec<_> = (0..2000)
806                .map(|_| rng.random_bool(0.5).then(|| rng.random_bool(0.5)))
807                .collect();
808            let b = BooleanArray::from(d.clone());
809
810            let expected_true = d.iter().filter(|x| matches!(x, Some(true))).count();
811            assert_eq!(b.true_count(), expected_true);
812
813            let expected_false = d.iter().filter(|x| matches!(x, Some(false))).count();
814            assert_eq!(b.false_count(), expected_false);
815        }
816    }
817
818    #[test]
819    fn test_into_parts() {
820        let boolean_array = [Some(true), None, Some(false)]
821            .into_iter()
822            .collect::<BooleanArray>();
823        let (values, nulls) = boolean_array.into_parts();
824        assert_eq!(values.values(), &[0b0000_0001]);
825        assert!(nulls.is_some());
826        assert_eq!(nulls.unwrap().buffer().as_slice(), &[0b0000_0101]);
827
828        let boolean_array =
829            BooleanArray::from(vec![false, false, false, false, false, false, false, true]);
830        let (values, nulls) = boolean_array.into_parts();
831        assert_eq!(values.values(), &[0b1000_0000]);
832        assert!(nulls.is_none());
833    }
834
835    #[test]
836    fn test_new_null_array() {
837        let arr = BooleanArray::new_null(5);
838
839        assert_eq!(arr.len(), 5);
840        assert_eq!(arr.null_count(), 5);
841        assert_eq!(arr.true_count(), 0);
842        assert_eq!(arr.false_count(), 0);
843
844        for i in 0..5 {
845            assert!(arr.is_null(i));
846            assert!(!arr.is_valid(i));
847        }
848    }
849
850    #[test]
851    fn test_slice_with_nulls() {
852        let arr = BooleanArray::from(vec![Some(true), None, Some(false)]);
853        let sliced = arr.slice(1, 2);
854
855        assert_eq!(sliced.len(), 2);
856        assert_eq!(sliced.null_count(), 1);
857
858        assert!(sliced.is_null(0));
859        assert!(sliced.is_valid(1));
860        assert!(!sliced.value(1));
861    }
862}