Skip to main content

polars_core/frame/group_by/
position.rs

1use std::mem::ManuallyDrop;
2use std::ops::{Deref, DerefMut};
3
4use polars_arrow::offset::OffsetsBuffer;
5use polars_utils::idx_vec::IdxVec;
6use rayon::iter::plumbing::UnindexedConsumer;
7use rayon::prelude::*;
8
9use crate::prelude::*;
10use crate::runtime::RAYON;
11use crate::utils::{NoNull, flatten, slice_slice};
12
13/// Indexes of the groups, the first index is stored separately.
14/// this make sorting fast.
15#[derive(Debug, Clone, PartialEq, Eq, Default)]
16pub struct GroupsIdx {
17    pub(crate) sorted_by_first_idx: bool,
18    /// Positions of the start of each group.
19    first: Vec<IdxSize>,
20    /// Global positions of all elements of all groups.
21    all: Vec<IdxVec>,
22}
23
24pub type IdxItem = (IdxSize, IdxVec);
25pub type BorrowIdxItem<'a> = (IdxSize, &'a IdxVec);
26
27impl Drop for GroupsIdx {
28    fn drop(&mut self) {
29        let v = std::mem::take(&mut self.all);
30        // ~65k took approximately 1ms on local machine, so from that point we drop on other thread
31        // to stop query from being blocked
32        #[cfg(not(target_family = "wasm"))]
33        if v.len() > 1 << 16 {
34            std::thread::spawn(move || drop(v));
35        } else {
36            drop(v);
37        }
38
39        #[cfg(target_family = "wasm")]
40        drop(v);
41    }
42}
43
44impl From<Vec<IdxItem>> for GroupsIdx {
45    fn from(v: Vec<IdxItem>) -> Self {
46        v.into_iter().collect()
47    }
48}
49
50impl From<Vec<Vec<IdxItem>>> for GroupsIdx {
51    fn from(v: Vec<Vec<IdxItem>>) -> Self {
52        // single threaded flatten: 10% faster than `iter().flatten().collect()
53        // this is the multi-threaded impl of that
54        let (cap, offsets) = flatten::cap_and_offsets(&v);
55        let mut first = Vec::with_capacity(cap);
56        let first_ptr = first.as_ptr() as usize;
57        let mut all = Vec::with_capacity(cap);
58        let all_ptr = all.as_ptr() as usize;
59
60        RAYON.install(|| {
61            v.into_par_iter()
62                .zip(offsets)
63                .for_each(|(mut inner, offset)| {
64                    unsafe {
65                        let first = (first_ptr as *const IdxSize as *mut IdxSize).add(offset);
66                        let all = (all_ptr as *const IdxVec as *mut IdxVec).add(offset);
67
68                        let inner_ptr = inner.as_mut_ptr();
69                        for i in 0..inner.len() {
70                            let (first_val, vals) = std::ptr::read(inner_ptr.add(i));
71                            std::ptr::write(first.add(i), first_val);
72                            std::ptr::write(all.add(i), vals);
73                        }
74                        // set len to 0 so that the contents will not get dropped
75                        // they are moved to `first` and `all`
76                        inner.set_len(0);
77                    }
78                });
79        });
80        unsafe {
81            all.set_len(cap);
82            first.set_len(cap);
83        }
84        GroupsIdx {
85            sorted_by_first_idx: false,
86            first,
87            all,
88        }
89    }
90}
91
92impl GroupsIdx {
93    pub fn new(first: Vec<IdxSize>, all: Vec<IdxVec>, sorted_by_first_idx: bool) -> Self {
94        Self {
95            sorted_by_first_idx,
96            first,
97            all,
98        }
99    }
100
101    pub fn sort_by_first_idx(&mut self) {
102        if self.sorted_by_first_idx {
103            return;
104        }
105        let mut idx = 0;
106        let first = std::mem::take(&mut self.first);
107        // store index and values so that we can sort those
108        let mut idx_vals = first
109            .into_iter()
110            .map(|v| {
111                let out = [idx, v];
112                idx += 1;
113                out
114            })
115            .collect_trusted::<Vec<_>>();
116        idx_vals.sort_unstable_by_key(|v| v[1]);
117
118        let take_first = || idx_vals.iter().map(|v| v[1]).collect_trusted::<Vec<_>>();
119        let take_all = || {
120            idx_vals
121                .iter()
122                .map(|v| unsafe {
123                    let idx = v[0] as usize;
124                    std::mem::take(self.all.get_unchecked_mut(idx))
125                })
126                .collect_trusted::<Vec<_>>()
127        };
128        let (first, all) = RAYON.install(|| rayon::join(take_first, take_all));
129        self.first = first;
130        self.all = all;
131        self.sorted_by_first_idx = true
132    }
133    pub fn is_sorted_by_first_idx(&self) -> bool {
134        self.sorted_by_first_idx
135    }
136
137    pub fn iter(
138        &self,
139    ) -> std::iter::Zip<
140        std::iter::Copied<std::slice::Iter<'_, IdxSize>>,
141        std::slice::Iter<'_, IdxVec>,
142    > {
143        self.into_iter()
144    }
145
146    #[inline(always)]
147    pub fn all(&self) -> &[IdxVec] {
148        &self.all
149    }
150
151    #[inline(always)]
152    pub fn first(&self) -> &[IdxSize] {
153        &self.first
154    }
155
156    #[inline(always)]
157    pub(crate) fn len(&self) -> usize {
158        self.first.len()
159    }
160
161    #[inline(always)]
162    pub(crate) unsafe fn get_unchecked(&self, index: usize) -> BorrowIdxItem<'_> {
163        let first = *self.first.get_unchecked(index);
164        let all = self.all.get_unchecked(index);
165        (first, all)
166    }
167
168    // Create an 'empty group', containing 1 group of length 0
169    pub fn new_empty() -> Self {
170        Self {
171            sorted_by_first_idx: false,
172            first: vec![0],
173            all: vec![vec![].into()],
174        }
175    }
176}
177
178impl FromIterator<IdxItem> for GroupsIdx {
179    fn from_iter<T: IntoIterator<Item = IdxItem>>(iter: T) -> Self {
180        let (first, all) = iter.into_iter().unzip();
181        GroupsIdx {
182            sorted_by_first_idx: false,
183            first,
184            all,
185        }
186    }
187}
188
189impl<'a> IntoIterator for &'a GroupsIdx {
190    type Item = BorrowIdxItem<'a>;
191    type IntoIter = std::iter::Zip<
192        std::iter::Copied<std::slice::Iter<'a, IdxSize>>,
193        std::slice::Iter<'a, IdxVec>,
194    >;
195
196    fn into_iter(self) -> Self::IntoIter {
197        self.first.iter().copied().zip(self.all.iter())
198    }
199}
200
201impl IntoIterator for GroupsIdx {
202    type Item = IdxItem;
203    type IntoIter = std::iter::Zip<std::vec::IntoIter<IdxSize>, std::vec::IntoIter<IdxVec>>;
204
205    fn into_iter(mut self) -> Self::IntoIter {
206        let first = std::mem::take(&mut self.first);
207        let all = std::mem::take(&mut self.all);
208        first.into_iter().zip(all)
209    }
210}
211
212impl FromParallelIterator<IdxItem> for GroupsIdx {
213    fn from_par_iter<I>(par_iter: I) -> Self
214    where
215        I: IntoParallelIterator<Item = IdxItem>,
216    {
217        let (first, all) = par_iter.into_par_iter().unzip();
218        GroupsIdx {
219            sorted_by_first_idx: false,
220            first,
221            all,
222        }
223    }
224}
225
226impl<'a> IntoParallelIterator for &'a GroupsIdx {
227    type Iter = rayon::iter::Zip<
228        rayon::iter::Copied<rayon::slice::Iter<'a, IdxSize>>,
229        rayon::slice::Iter<'a, IdxVec>,
230    >;
231    type Item = BorrowIdxItem<'a>;
232
233    fn into_par_iter(self) -> Self::Iter {
234        self.first.par_iter().copied().zip(self.all.par_iter())
235    }
236}
237
238impl IntoParallelIterator for GroupsIdx {
239    type Iter = rayon::iter::Zip<rayon::vec::IntoIter<IdxSize>, rayon::vec::IntoIter<IdxVec>>;
240    type Item = IdxItem;
241
242    fn into_par_iter(mut self) -> Self::Iter {
243        let first = std::mem::take(&mut self.first);
244        let all = std::mem::take(&mut self.all);
245        first.into_par_iter().zip(all.into_par_iter())
246    }
247}
248
249/// Every group is indicated by an array where the
250///  - first value is an index to the start of the group
251///  - second value is the length of the group
252///
253/// Only used when group values are stored together
254///
255/// This type should have the invariant that it is always sorted in ascending
256/// order by the start indices.
257pub type GroupsSlice = Vec<[IdxSize; 2]>;
258
259#[derive(Debug, Clone, PartialEq, Eq)]
260pub enum GroupsType {
261    Idx(GroupsIdx),
262    Slice {
263        // the groups slices
264        groups: GroupsSlice,
265        /// Indicates if the groups may overlap, i.e., at least one index MAY be
266        /// included in more than one group slice.
267        overlapping: bool,
268        /// Indicates if the groups are rolling, i.e. for every consecutive group
269        /// slice (offset, len), and given start = offset and end = offset + len,
270        /// then both new_start >= start AND new_end >= end MUST be true.
271        monotonic: bool,
272    },
273}
274
275impl Default for GroupsType {
276    fn default() -> Self {
277        GroupsType::Idx(GroupsIdx::default())
278    }
279}
280
281/// Returns whether `groups` is monotonic:
282/// True if for every consecutive pair of group slices both the
283/// start and the end offset are non-decreasing.
284pub fn slice_groups_are_monotonic(groups: &GroupsSlice) -> bool {
285    if groups.len() < 2 {
286        return true;
287    }
288
289    let (offset, len) = (groups[0][0], groups[0][1]);
290    let mut prev_start = offset;
291    let mut prev_end = offset + len;
292
293    for g in &groups[1..] {
294        let start = g[0];
295        let end = g[0] + g[1];
296
297        if start < prev_start || end < prev_end {
298            return false;
299        }
300
301        prev_start = start;
302        prev_end = end;
303    }
304    true
305}
306
307impl GroupsType {
308    pub fn new_slice(groups: GroupsSlice, overlapping: bool, monotonic: bool) -> Self {
309        #[cfg(debug_assertions)]
310        {
311            fn groups_overlap(groups: &GroupsSlice) -> bool {
312                if groups.len() < 2 {
313                    return false;
314                }
315                let mut groups = groups.clone();
316                groups.sort();
317                let mut prev_end = groups[0][1];
318
319                for g in &groups[1..] {
320                    let start = g[0];
321                    let end = g[1];
322                    if start < prev_end {
323                        return true;
324                    }
325                    if end > prev_end {
326                        prev_end = end;
327                    }
328                }
329                false
330            }
331
332            assert!(overlapping || !groups_overlap(&groups));
333            assert!(!monotonic || slice_groups_are_monotonic(&groups));
334        }
335
336        Self::Slice {
337            groups,
338            overlapping,
339            monotonic,
340        }
341    }
342
343    pub fn into_idx(self) -> GroupsIdx {
344        match self {
345            GroupsType::Idx(groups) => groups,
346            GroupsType::Slice { groups, .. } => {
347                polars_warn!(
348                    "Had to reallocate groups, missed an optimization opportunity. Please open an issue."
349                );
350                groups
351                    .iter()
352                    .map(|&[first, len]| (first, (first..first + len).collect::<IdxVec>()))
353                    .collect()
354            },
355        }
356    }
357
358    pub(crate) fn prepare_list_agg(
359        &self,
360        total_len: usize,
361    ) -> (Option<IdxCa>, OffsetsBuffer<i64>, bool) {
362        let mut can_fast_explode = true;
363        match self {
364            GroupsType::Idx(groups) => {
365                let mut list_offset = Vec::with_capacity(self.len() + 1);
366                let mut gather_offsets = Vec::with_capacity(total_len);
367
368                let mut len_so_far = 0i64;
369                list_offset.push(len_so_far);
370
371                for idx in groups {
372                    let idx = idx.1;
373                    gather_offsets.extend_from_slice(idx);
374                    len_so_far += idx.len() as i64;
375                    list_offset.push(len_so_far);
376                    can_fast_explode &= !idx.is_empty();
377                }
378                unsafe {
379                    (
380                        Some(IdxCa::from_vec(PlSmallStr::EMPTY, gather_offsets)),
381                        OffsetsBuffer::new_unchecked(list_offset.into()),
382                        can_fast_explode,
383                    )
384                }
385            },
386            GroupsType::Slice { groups, .. } => {
387                let mut list_offset = Vec::with_capacity(self.len() + 1);
388                let mut gather_offsets = Vec::with_capacity(total_len);
389                let mut len_so_far = 0i64;
390                list_offset.push(len_so_far);
391
392                for g in groups {
393                    let len = g[1];
394                    let offset = g[0];
395                    gather_offsets.extend(offset..offset + len);
396
397                    len_so_far += len as i64;
398                    list_offset.push(len_so_far);
399                    can_fast_explode &= len > 0;
400                }
401
402                unsafe {
403                    (
404                        Some(IdxCa::from_vec(PlSmallStr::EMPTY, gather_offsets)),
405                        OffsetsBuffer::new_unchecked(list_offset.into()),
406                        can_fast_explode,
407                    )
408                }
409            },
410        }
411    }
412
413    pub fn iter(&self) -> GroupsTypeIter<'_> {
414        GroupsTypeIter::new(self)
415    }
416
417    pub fn sort_by_first_idx(&mut self) {
418        match self {
419            GroupsType::Idx(groups) => {
420                if !groups.is_sorted_by_first_idx() {
421                    groups.sort_by_first_idx()
422                }
423            },
424            GroupsType::Slice { .. } => {
425                // invariant of the type
426            },
427        }
428    }
429
430    pub(crate) fn is_sorted_by_first_idx(&self) -> bool {
431        match self {
432            GroupsType::Idx(groups) => groups.is_sorted_by_first_idx(),
433            GroupsType::Slice { .. } => true,
434        }
435    }
436
437    pub fn is_overlapping(&self) -> bool {
438        matches!(
439            self,
440            GroupsType::Slice {
441                overlapping: true,
442                ..
443            }
444        )
445    }
446
447    pub fn is_monotonic(&self) -> bool {
448        matches!(
449            self,
450            GroupsType::Slice {
451                monotonic: true,
452                ..
453            }
454        )
455    }
456
457    pub fn take_group_firsts(self) -> Vec<IdxSize> {
458        match self {
459            GroupsType::Idx(mut groups) => std::mem::take(&mut groups.first),
460            GroupsType::Slice { groups, .. } => {
461                groups.into_iter().map(|[first, _len]| first).collect()
462            },
463        }
464    }
465
466    /// Checks if groups are of equal length. The caller is responsible for
467    /// updating the groups by calling `groups()` prior to calling this method.
468    pub fn check_lengths(self: &GroupsType, other: &GroupsType) -> PolarsResult<()> {
469        if std::ptr::eq(self, other) {
470            return Ok(());
471        }
472        polars_ensure!(self.iter().zip(other.iter()).all(|(a, b)| {
473            a.len() == b.len()
474        }), ShapeMismatch: "expressions must have matching group lengths");
475        Ok(())
476    }
477
478    /// # Safety
479    /// This will not do any bounds checks. The caller must ensure
480    /// all groups have members.
481    pub unsafe fn take_group_lasts(self) -> Vec<IdxSize> {
482        match self {
483            GroupsType::Idx(groups) => groups
484                .all
485                .iter()
486                .map(|idx| *idx.get_unchecked(idx.len() - 1))
487                .collect(),
488            GroupsType::Slice { groups, .. } => groups
489                .into_iter()
490                .map(|[first, len]| first + len - 1)
491                .collect(),
492        }
493    }
494
495    pub fn par_iter(&self) -> GroupsTypeParIter<'_> {
496        GroupsTypeParIter::new(self)
497    }
498
499    /// Get a reference to the `GroupsIdx`.
500    ///
501    /// # Panic
502    ///
503    /// panics if the groups are a slice.
504    pub fn unwrap_idx(&self) -> &GroupsIdx {
505        match self {
506            GroupsType::Idx(groups) => groups,
507            GroupsType::Slice { .. } => panic!("groups are slices not index"),
508        }
509    }
510
511    /// Get a reference to the `GroupsSlice`.
512    ///
513    /// # Panic
514    ///
515    /// panics if the groups are an idx.
516    pub fn unwrap_slice(&self) -> &GroupsSlice {
517        match self {
518            GroupsType::Slice { groups, .. } => groups,
519            GroupsType::Idx(_) => panic!("groups are index not slices"),
520        }
521    }
522
523    pub fn get(&self, index: usize) -> GroupsIndicator<'_> {
524        match self {
525            GroupsType::Idx(groups) => {
526                let first = groups.first[index];
527                let all = &groups.all[index];
528                GroupsIndicator::Idx((first, all))
529            },
530            GroupsType::Slice { groups, .. } => GroupsIndicator::Slice(groups[index]),
531        }
532    }
533
534    /// Get a mutable reference to the `GroupsIdx`.
535    ///
536    /// # Panic
537    ///
538    /// panics if the groups are a slice.
539    pub fn idx_mut(&mut self) -> &mut GroupsIdx {
540        match self {
541            GroupsType::Idx(groups) => groups,
542            GroupsType::Slice { .. } => panic!("groups are slices not index"),
543        }
544    }
545
546    pub fn len(&self) -> usize {
547        match self {
548            GroupsType::Idx(groups) => groups.len(),
549            GroupsType::Slice { groups, .. } => groups.len(),
550        }
551    }
552
553    pub fn is_empty(&self) -> bool {
554        self.len() == 0
555    }
556
557    pub fn group_count(&self) -> IdxCa {
558        match self {
559            GroupsType::Idx(groups) => {
560                let ca: NoNull<IdxCa> = groups
561                    .iter()
562                    .map(|(_first, idx)| idx.len() as IdxSize)
563                    .collect_trusted();
564                ca.into_inner()
565            },
566            GroupsType::Slice { groups, .. } => {
567                let ca: NoNull<IdxCa> = groups.iter().map(|[_first, len]| *len).collect_trusted();
568                ca.into_inner()
569            },
570        }
571    }
572
573    pub fn as_list_chunked(&self) -> ListChunked {
574        match self {
575            GroupsType::Idx(groups) => groups
576                .iter()
577                .map(|(_first, idx)| {
578                    let ca: NoNull<IdxCa> = idx.iter().map(|&v| v as IdxSize).collect();
579                    ca.into_inner().into_series()
580                })
581                .collect_trusted(),
582            GroupsType::Slice { groups, .. } => groups
583                .iter()
584                .map(|&[first, len]| {
585                    let ca: NoNull<IdxCa> = (first..first + len).collect_trusted();
586                    ca.into_inner().into_series()
587                })
588                .collect_trusted(),
589        }
590    }
591
592    pub fn into_sliceable(self) -> GroupPositions {
593        let len = self.len();
594        slice_groups(Arc::new(self), 0, len)
595    }
596
597    pub fn num_elements(&self) -> usize {
598        match self {
599            GroupsType::Idx(i) => i.all().iter().map(|v| v.len()).sum(),
600            GroupsType::Slice {
601                groups,
602                overlapping: _,
603                monotonic: _,
604            } => groups.iter().map(|[_, l]| *l as usize).sum(),
605        }
606    }
607}
608
609impl From<GroupsIdx> for GroupsType {
610    fn from(groups: GroupsIdx) -> Self {
611        GroupsType::Idx(groups)
612    }
613}
614
615pub enum GroupsIndicator<'a> {
616    Idx(BorrowIdxItem<'a>),
617    Slice([IdxSize; 2]),
618}
619
620impl GroupsIndicator<'_> {
621    pub fn len(&self) -> usize {
622        match self {
623            GroupsIndicator::Idx(g) => g.1.len(),
624            GroupsIndicator::Slice([_, len]) => *len as usize,
625        }
626    }
627    pub fn first(&self) -> IdxSize {
628        match self {
629            GroupsIndicator::Idx(g) => g.0,
630            GroupsIndicator::Slice([first, _]) => *first,
631        }
632    }
633    pub fn is_empty(&self) -> bool {
634        self.len() == 0
635    }
636}
637
638pub struct GroupsTypeIter<'a> {
639    vals: &'a GroupsType,
640    len: usize,
641    idx: usize,
642}
643
644impl<'a> GroupsTypeIter<'a> {
645    fn new(vals: &'a GroupsType) -> Self {
646        let len = vals.len();
647        let idx = 0;
648        GroupsTypeIter { vals, len, idx }
649    }
650}
651
652impl<'a> Iterator for GroupsTypeIter<'a> {
653    type Item = GroupsIndicator<'a>;
654
655    fn nth(&mut self, n: usize) -> Option<Self::Item> {
656        self.idx = self.idx.saturating_add(n);
657        self.next()
658    }
659
660    fn next(&mut self) -> Option<Self::Item> {
661        if self.idx >= self.len {
662            return None;
663        }
664
665        let out = unsafe {
666            match self.vals {
667                GroupsType::Idx(groups) => {
668                    let item = groups.get_unchecked(self.idx);
669                    Some(GroupsIndicator::Idx(item))
670                },
671                GroupsType::Slice { groups, .. } => {
672                    Some(GroupsIndicator::Slice(*groups.get_unchecked(self.idx)))
673                },
674            }
675        };
676        self.idx += 1;
677        out
678    }
679}
680
681pub struct GroupsTypeParIter<'a> {
682    vals: &'a GroupsType,
683    len: usize,
684}
685
686impl<'a> GroupsTypeParIter<'a> {
687    fn new(vals: &'a GroupsType) -> Self {
688        let len = vals.len();
689        GroupsTypeParIter { vals, len }
690    }
691}
692
693impl<'a> ParallelIterator for GroupsTypeParIter<'a> {
694    type Item = GroupsIndicator<'a>;
695
696    fn drive_unindexed<C>(self, consumer: C) -> C::Result
697    where
698        C: UnindexedConsumer<Self::Item>,
699    {
700        (0..self.len)
701            .into_par_iter()
702            .map(|i| unsafe {
703                match self.vals {
704                    GroupsType::Idx(groups) => GroupsIndicator::Idx(groups.get_unchecked(i)),
705                    GroupsType::Slice { groups, .. } => {
706                        GroupsIndicator::Slice(*groups.get_unchecked(i))
707                    },
708                }
709            })
710            .drive_unindexed(consumer)
711    }
712}
713
714#[derive(Debug)]
715pub struct GroupPositions {
716    // SAFETY: sliced is a shallow clone of original
717    // It emulates a shared reference, not an exclusive reference
718    // Its data must not be mutated through direct access
719    sliced: ManuallyDrop<GroupsType>,
720    // Unsliced buffer
721    original: Arc<GroupsType>,
722    offset: i64,
723    len: usize,
724}
725
726impl Clone for GroupPositions {
727    fn clone(&self) -> Self {
728        let sliced = slice_groups_inner(&self.original, self.offset, self.len);
729
730        Self {
731            sliced,
732            original: self.original.clone(),
733            offset: self.offset,
734            len: self.len,
735        }
736    }
737}
738
739impl AsRef<GroupsType> for GroupPositions {
740    fn as_ref(&self) -> &GroupsType {
741        self.sliced.deref()
742    }
743}
744
745impl Deref for GroupPositions {
746    type Target = GroupsType;
747
748    fn deref(&self) -> &Self::Target {
749        self.sliced.deref()
750    }
751}
752
753impl Default for GroupPositions {
754    fn default() -> Self {
755        GroupsType::default().into_sliceable()
756    }
757}
758
759impl GroupPositions {
760    pub fn slice(&self, offset: i64, len: usize) -> Self {
761        let offset = self.offset + offset;
762        slice_groups(self.original.clone(), offset, len)
763    }
764
765    pub fn sort_by_first_idx(&mut self) {
766        if !self.as_ref().is_sorted_by_first_idx() {
767            let original = Arc::make_mut(&mut self.original);
768            original.sort_by_first_idx();
769
770            self.sliced = slice_groups_inner(original, self.offset, self.len);
771        }
772    }
773
774    pub fn unroll(mut self) -> GroupPositions {
775        match self.sliced.deref_mut() {
776            GroupsType::Idx(_) => self,
777            GroupsType::Slice {
778                overlapping: false, ..
779            } => self,
780            GroupsType::Slice { groups, .. } => {
781                // SAFETY: sliced is a shallow partial clone of original.
782                // A new owning Vec is required per GH issue #21859
783                let mut cum_offset = 0 as IdxSize;
784                let groups: Vec<_> = groups
785                    .iter()
786                    .map(|[_, len]| {
787                        let new = [cum_offset, *len];
788                        cum_offset += *len;
789                        new
790                    })
791                    .collect();
792
793                GroupsType::new_slice(groups, false, true).into_sliceable()
794            },
795        }
796    }
797
798    pub fn as_unrolled_slice(&self) -> Option<&GroupsSlice> {
799        match &*self.sliced {
800            GroupsType::Idx(_) => None,
801            GroupsType::Slice {
802                groups: _,
803                overlapping: true,
804                monotonic: _,
805            } => None,
806            GroupsType::Slice {
807                groups,
808                overlapping: false,
809                monotonic: _,
810            } => Some(groups),
811        }
812    }
813
814    /// Compare groups based on inner pointer.
815    pub fn is_same(&self, other: &Self) -> bool {
816        Arc::ptr_eq(&self.original, &other.original)
817            && self.offset == other.offset
818            && self.len == other.len
819    }
820}
821
822fn slice_groups_inner(g: &GroupsType, offset: i64, len: usize) -> ManuallyDrop<GroupsType> {
823    // SAFETY:
824    // we create new `Vec`s from the sliced groups. But we wrap them in ManuallyDrop
825    // so that we never call drop on them.
826    // These groups lifetimes are bounded to the `g`. This must remain valid
827    // for the scope of the aggregation.
828    match g {
829        GroupsType::Idx(groups) => {
830            let first = unsafe {
831                let first = slice_slice(groups.first(), offset, len);
832                let ptr = first.as_ptr() as *mut _;
833                Vec::from_raw_parts(ptr, first.len(), first.len())
834            };
835
836            let all = unsafe {
837                let all = slice_slice(groups.all(), offset, len);
838                let ptr = all.as_ptr() as *mut _;
839                Vec::from_raw_parts(ptr, all.len(), all.len())
840            };
841            ManuallyDrop::new(GroupsType::Idx(GroupsIdx::new(
842                first,
843                all,
844                groups.is_sorted_by_first_idx(),
845            )))
846        },
847        GroupsType::Slice {
848            groups,
849            overlapping,
850            monotonic,
851        } => {
852            let groups = unsafe {
853                let groups = slice_slice(groups, offset, len);
854                let ptr = groups.as_ptr() as *mut _;
855                Vec::from_raw_parts(ptr, groups.len(), groups.len())
856            };
857
858            ManuallyDrop::new(GroupsType::new_slice(groups, *overlapping, *monotonic))
859        },
860    }
861}
862
863fn slice_groups(g: Arc<GroupsType>, offset: i64, len: usize) -> GroupPositions {
864    let sliced = slice_groups_inner(g.as_ref(), offset, len);
865
866    GroupPositions {
867        sliced,
868        original: g,
869        offset,
870        len,
871    }
872}