Skip to main content

vortex_array/arrays/list/
rebuild.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_buffer::BitBuffer;
5use vortex_buffer::BitBufferMut;
6use vortex_buffer::BufferAllocatorRef;
7use vortex_buffer::BufferMut;
8use vortex_error::VortexExpect;
9use vortex_error::VortexResult;
10use vortex_mask::AllOr;
11use vortex_mask::Mask;
12
13use crate::ArrayRef;
14use crate::ExecutionCtx;
15use crate::IntoArray;
16use crate::arrays::ListArray;
17use crate::arrays::PrimitiveArray;
18use crate::arrays::list::ListArrayExt;
19use crate::arrays::list::ListArraySlotsExt;
20use crate::arrays::primitive::PrimitiveArrayExt;
21use crate::dtype::IntegerPType;
22use crate::dtype::PType;
23use crate::match_each_unsigned_integer_ptype;
24use crate::optimizer::ArrayOptimizer;
25use crate::validity::Validity;
26
27impl ListArray {
28    /// Compacts the [`ListArray`] to only the elements that valid lists reference: nothing before
29    /// the first list, after the last or under a null list.
30    ///
31    /// Null lists come out empty, the offsets start at 0, end at the length of the elements and
32    /// keep their type, and the validity is kept. An array with nothing to drop is returned as it
33    /// is.
34    pub fn compact(&self, ctx: &mut ExecutionCtx) -> VortexResult<ListArray> {
35        let validity = self.list_validity();
36        if validity.definitely_no_nulls()
37            && self.offset_at(0, ctx)? == 0
38            && self.offset_at(self.len(), ctx)? == self.elements().len()
39        {
40            return Ok(self.clone());
41        }
42
43        let offsets = self.offsets().clone().execute::<PrimitiveArray>(ctx)?;
44        let offsets_ptype = offsets.ptype();
45        // Offsets are never negative, so they are rebuilt unsigned and reinterpreted back.
46        let offsets = offsets.reinterpret_cast(offsets_ptype.to_unsigned());
47        let valid = validity.execute_mask(self.len(), ctx)?;
48        match_each_unsigned_integer_ptype!(offsets.ptype(), |O| {
49            self.rebuild_with_valid(offsets.as_slice::<O>(), offsets_ptype, &valid, ctx)
50        })
51    }
52
53    fn rebuild_with_valid<O: IntegerPType>(
54        &self,
55        offsets: &[O],
56        offsets_ptype: PType,
57        valid: &Mask,
58        ctx: &mut ExecutionCtx,
59    ) -> VortexResult<ListArray> {
60        let (starts, end) = (&offsets[..self.len()], offsets[self.len()].as_());
61        let null_runs =
62            null_runs_holding_elements(valid, |index| offsets[index] != offsets[index + 1]);
63        if null_runs.is_empty() && offsets[0].as_() == 0 && end == self.elements().len() {
64            return Ok(self.clone());
65        }
66
67        let (elements, mut offsets) =
68            drop_unreferenced_elements(self.elements(), starts, end, &null_runs, ctx.allocator())?;
69        let elements = elements.optimize_ctx(ctx)?;
70        offsets.push(
71            num_traits::cast(elements.len())
72                .vortex_expect("the elements kept fit the offsets' type"),
73        );
74        let offsets = PrimitiveArray::new(offsets.freeze(), Validity::NonNullable)
75            .reinterpret_cast(offsets_ptype)
76            .into_array();
77        // SAFETY: the offsets keep their type, start at 0, never decrease and end at the length of
78        // the elements, which are the valid lists' elements in order.
79        Ok(unsafe { ListArray::new_unchecked(elements, offsets, self.list_validity()) })
80    }
81}
82
83/// The runs of null lists that hold elements, given which lists hold elements.
84pub(crate) fn null_runs_holding_elements(
85    valid: &Mask,
86    mut holds_elements: impl FnMut(usize) -> bool,
87) -> Vec<(usize, usize)> {
88    match valid.bit_buffer() {
89        AllOr::All => Vec::new(),
90        AllOr::None if (0..valid.len()).any(&mut holds_elements) => vec![(0, valid.len())],
91        AllOr::None => Vec::new(),
92        AllOr::Some(valid) => BitBuffer::collect_bool(valid.len(), &mut holds_elements)
93            .bitand_not(valid)
94            .set_slices()
95            .collect(),
96    }
97}
98
99/// Drops the elements before the first of the lists laid out back to back, after the last, and
100/// under the runs of null lists from [`null_runs_holding_elements`], which come out empty.
101///
102/// `end` is where the last list ends. It is a `usize` rather than an `O` because a list view's last
103/// list can end past what its offsets' type holds: with `u8` offsets `[1, 5, 105]` and sizes
104/// `[4, 100, 200]`, it ends at 305.
105///
106/// Returns the elements kept and where each list now starts. A [`ListArray`] needs one more offset,
107/// where its last list ends, so the buffer has room to push it without reallocating.
108pub(crate) fn drop_unreferenced_elements<O: IntegerPType>(
109    elements: &ArrayRef,
110    starts: &[O],
111    end: usize,
112    null_runs: &[(usize, usize)],
113    allocator: &BufferAllocatorRef,
114) -> VortexResult<(ArrayRef, BufferMut<O>)> {
115    let start_of = |index: usize| starts.get(index).map_or(end, |start| start.as_());
116    let first = start_of(0);
117    // The ranges of elements kept, counted from the first list's start.
118    let mut kept = Vec::with_capacity(null_runs.len() + 1);
119    let mut kept_start = 0;
120    let mut offsets = BufferMut::with_capacity_in(starts.len() + 1, allocator.clone());
121    offsets.extend_from_slice(starts);
122    let mut dropped = starts.first().copied().unwrap_or_else(O::zero);
123    let mut from = 0;
124    for &(run_start, run_end) in null_runs {
125        if kept_start < start_of(run_start) - first {
126            kept.push((kept_start, start_of(run_start) - first));
127        }
128        kept_start = start_of(run_end) - first;
129
130        for offset in &mut offsets[from..run_start] {
131            *offset = *offset - dropped;
132        }
133        offsets[run_start..run_end].fill(starts[run_start] - dropped);
134        // A run at the end leaves no list after it to move down.
135        if let Some(&next) = starts.get(run_end) {
136            dropped += next - starts[run_start];
137        }
138        from = run_end;
139    }
140    if kept_start < end - first {
141        kept.push((kept_start, end - first));
142    }
143    for offset in &mut offsets[from..] {
144        *offset = *offset - dropped;
145    }
146
147    let referenced = elements.slice(first..end)?;
148    let elements = match kept[..] {
149        [] => referenced.slice(0..0)?,
150        [(start, stop)] => referenced.slice(start..stop)?,
151        _ => {
152            let mut bits = BitBufferMut::new_unset(end - first);
153            for &(start, stop) in &kept {
154                bits.fill_range(start, stop, true);
155            }
156            // With the ranges cached on the mask, the filter copies the elements range by range.
157            referenced.filter(Mask::from_buffer_with_slices(bits.freeze(), kept))?
158        }
159    };
160    Ok((elements, offsets))
161}