Skip to main content

polars_utils/
slice_enum.rs

1use std::num::NonZeroUsize;
2use std::ops::{Index, IndexMut, Range};
3
4use crate::IdxSize;
5use crate::pl_str::PlSmallStr;
6
7/// A selection of rows, resolved against the height of its input once that is known.
8///
9/// A slice from 0 that runs to the end has no variant; `Option<Slice>::None` stands for it.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
13pub enum Slice {
14    /// Rows `offset..offset + len`.
15    Positive { offset: usize, len: usize },
16    /// At most `len` rows, starting `offset_from_end` rows before the end.
17    ///
18    /// A `len` above `offset_from_end` selects the same rows as `len == offset_from_end`.
19    Negative { offset_from_end: usize, len: usize },
20    /// Rows `offset..`.
21    PositiveUnbounded { offset: NonZeroUsize },
22}
23
24impl Slice {
25    pub const EMPTY: Slice = Slice::Positive { offset: 0, len: 0 };
26
27    /// Create the slice of `len` rows from `offset`, counting from the end if `offset` is
28    /// negative. Run to the end if `len` is `None`. Return `None` if that selects every row.
29    #[inline]
30    pub fn new(offset: i64, len: Option<usize>) -> Option<Self> {
31        let abs_offset = usize::try_from(offset.unsigned_abs()).unwrap_or(usize::MAX);
32
33        match (offset >= 0, len) {
34            (true, Some(len)) => Some(Slice::Positive {
35                offset: abs_offset,
36                len,
37            }),
38            (true, None) => Slice::skip(abs_offset),
39            (false, len) => Some(Slice::Negative {
40                offset_from_end: abs_offset,
41                len: len.map_or(abs_offset, |len| len.min(abs_offset)),
42            }),
43        }
44        .map(Self::canonical)
45    }
46
47    /// Return the position `offset` refers to in `n_rows` rows, counting from the end if `offset`
48    /// is negative, clamped to `0..=n_rows`.
49    #[inline]
50    pub fn resolve_offset(offset: i64, n_rows: usize) -> usize {
51        Slice::new(offset, None).map_or(0, |s| s.resolve(n_rows).start)
52    }
53
54    /// Create the slice of `len` rows from `offset`. Run to the end if `len` is `None`. Return
55    /// `None` if that selects every row.
56    #[inline]
57    pub fn new_positive(offset: usize, len: Option<usize>) -> Option<Self> {
58        match len {
59            Some(len) => Some(Slice::Positive { offset, len }),
60            None => Slice::skip(offset),
61        }
62    }
63
64    /// Create the slice of the first `n` rows.
65    #[inline]
66    pub fn head(n: usize) -> Self {
67        Slice::Positive { offset: 0, len: n }
68    }
69
70    /// Create the slice of the last `n` rows.
71    #[inline]
72    pub fn tail(n: usize) -> Self {
73        Slice::Negative {
74            offset_from_end: n,
75            len: n,
76        }
77    }
78
79    /// Create the slice of all rows after the first `n`.
80    ///
81    /// This returns `None` if `n` is 0.
82    #[inline]
83    pub fn skip(n: usize) -> Option<Self> {
84        NonZeroUsize::new(n).map(|offset| Slice::PositiveUnbounded { offset })
85    }
86
87    /// Return the maximum number of rows selected, or `None` if the slice runs to the end.
88    #[inline]
89    pub fn len(&self) -> Option<usize> {
90        match self.canonical() {
91            Slice::Positive { len, .. } | Slice::Negative { len, .. } => Some(len),
92            Slice::PositiveUnbounded { .. } => None,
93        }
94    }
95
96    /// Return whether no rows are selected at any height.
97    #[inline]
98    pub fn is_empty(&self) -> bool {
99        self.len() == Some(0)
100    }
101
102    /// Return whether the slice counts from the start.
103    #[inline]
104    pub fn is_positive(&self) -> bool {
105        !self.is_negative()
106    }
107
108    /// Return whether the slice counts from the end.
109    #[inline]
110    pub fn is_negative(&self) -> bool {
111        matches!(self, Slice::Negative { .. })
112    }
113
114    /// Return the offset of a positive slice.
115    ///
116    /// # Panics
117    /// Panics if `self` is [`Slice::Negative`].
118    pub fn positive_offset(&self) -> usize {
119        match self {
120            Slice::Positive { offset, .. } => *offset,
121            Slice::PositiveUnbounded { offset } => offset.get(),
122            Slice::Negative { .. } => panic!("cannot use positive_offset() on a negative slice"),
123        }
124    }
125
126    /// Return the number of leading rows needed to apply the slice, or `None` if that depends
127    /// on the height.
128    pub fn end_position(&self) -> Option<usize> {
129        match self {
130            Slice::Positive { offset, len } => offset.checked_add(*len),
131            Slice::PositiveUnbounded { .. } | Slice::Negative { .. } => None,
132        }
133    }
134
135    /// Return whether the signed offset and the end of the slice fit in an `i64`.
136    pub fn is_within_i64(&self) -> bool {
137        match *self {
138            Slice::Positive { .. } => self
139                .end_position()
140                .is_some_and(|end| i64::try_from(end).is_ok()),
141            Slice::PositiveUnbounded { offset } => i64::try_from(offset.get()).is_ok(),
142            Slice::Negative {
143                offset_from_end, ..
144            } => 0i64.checked_sub_unsigned(offset_from_end as u64).is_some(),
145        }
146    }
147
148    /// Return the smallest `head` or `tail` that contains the slice, or `None` if the slice
149    /// may need every row.
150    pub fn bounding_limit(&self) -> Option<Slice> {
151        match self {
152            Slice::Positive { .. } => self.end_position().map(Slice::head),
153            Slice::Negative {
154                offset_from_end, ..
155            } => Some(Slice::tail(*offset_from_end)),
156            Slice::PositiveUnbounded { .. } => None,
157        }
158    }
159
160    /// Return the equivalent slice to apply to the rows from `position` on, or `None` if that
161    /// would select every row.
162    ///
163    /// # Panics
164    /// Panics if `self` is [`Slice::Negative`].
165    pub fn offsetted(self, position: usize) -> Option<Self> {
166        match self {
167            Slice::Positive { offset, len } => {
168                let (offset, len) = if position <= offset {
169                    (offset - position, len)
170                } else {
171                    (0, len.saturating_sub(position - offset))
172                };
173                Some(Slice::Positive { offset, len })
174            },
175            Slice::PositiveUnbounded { offset } => {
176                Slice::skip(offset.get().saturating_sub(position))
177            },
178            Slice::Negative { .. } => panic!("cannot use offsetted() on a negative slice"),
179        }
180    }
181
182    /// Return the rows the slice selects from the next `n_rows` rows, and the slice to apply to
183    /// the rows after them, `None` if that would select every row.
184    ///
185    /// # Panics
186    /// Panics if `self` is [`Slice::Negative`].
187    pub fn split_front(self, n_rows: usize) -> (Range<usize>, Option<Self>) {
188        (self.resolve(n_rows), self.offsetted(n_rows))
189    }
190
191    /// Return which rows the slice selects from `n_rows` rows.
192    #[inline]
193    pub fn resolve(self, n_rows: usize) -> Range<usize> {
194        match self.canonical() {
195            Slice::Positive { offset, len } => {
196                offset.min(n_rows)..offset.saturating_add(len).min(n_rows)
197            },
198            Slice::PositiveUnbounded { offset } => offset.get().min(n_rows)..n_rows,
199            Slice::Negative {
200                offset_from_end,
201                len,
202            } => {
203                n_rows.saturating_sub(offset_from_end)..n_rows.saturating_sub(offset_from_end - len)
204            },
205        }
206    }
207
208    /// Return the positive slice that selects the same rows from `n_rows` rows.
209    #[inline]
210    pub fn restrict_to_bounds(self, n_rows: usize) -> Self {
211        Slice::from(self.resolve(n_rows))
212    }
213
214    /// Return the signed offset and the length, `None` if the slice runs to the end.
215    ///
216    /// # Panics
217    /// Panics if the signed offset does not fit in an `i64`.
218    pub fn to_signed_offset_len(&self) -> (i64, Option<usize>) {
219        let (offset, len) = match self.canonical() {
220            Slice::Positive { offset, len } => (i64::try_from(offset).ok(), Some(len)),
221            Slice::PositiveUnbounded { offset } => (i64::try_from(offset.get()).ok(), None),
222            Slice::Negative {
223                offset_from_end,
224                len,
225            } => (0i64.checked_sub_unsigned(offset_from_end as u64), Some(len)),
226        };
227        (offset.expect("slice offset does not fit in an i64"), len)
228    }
229
230    /// Return the offset and the length of a positive slice, `None` if the slice runs to the end.
231    ///
232    /// # Panics
233    /// Panics if `self` is [`Slice::Negative`].
234    pub fn to_unsigned_offset_len(&self) -> (usize, Option<usize>) {
235        (self.positive_offset(), self.len())
236    }
237
238    /// Format the slice as `(offset, len)`, writing `∞` for the length of a slice that runs to the
239    /// end.
240    pub fn fmt_tuple(&self) -> PlSmallStr {
241        let (offset, len) = self.to_signed_offset_len();
242        match len {
243            Some(len) => crate::format_pl_smallstr!("({offset}, {len})"),
244            None => crate::format_pl_smallstr!("({offset}, ∞)"),
245        }
246    }
247
248    /// Return the signed offset and the length, writing `IdxSize::MAX` for a length that runs to
249    /// the end or does not fit in an `IdxSize`.
250    // TODO: @3.0: Remove once the Python IR visitor takes an optional length.
251    pub fn to_legacy_signed_offset_len(&self) -> (i64, IdxSize) {
252        let (offset, len) = self.to_signed_offset_len();
253        let len = len.map_or(IdxSize::MAX, |len| {
254            IdxSize::try_from(len).unwrap_or(IdxSize::MAX)
255        });
256        (offset, len)
257    }
258
259    /// Return the slice that selects the same rows as applying `self` and then `next` at every
260    /// height, or `None` if this pair is not combined or the result does not fit in an `i64`.
261    pub fn reslice(self, next: Slice) -> Option<Slice> {
262        use Slice::*;
263
264        if self.is_empty() || next.is_empty() {
265            return Some(Self::EMPTY);
266        }
267
268        let combined = match (self.canonical(), next.canonical()) {
269            (Positive { offset: a, len: l }, Positive { offset: b, len: m }) => Positive {
270                offset: a.checked_add(b)?,
271                len: m.min(l.saturating_sub(b)),
272            },
273            (Positive { offset: a, len: l }, PositiveUnbounded { offset: b }) => Positive {
274                offset: a.checked_add(b.get())?,
275                len: l.saturating_sub(b.get()),
276            },
277            (PositiveUnbounded { offset: a }, Positive { offset: b, len: m }) => Positive {
278                offset: a.get().checked_add(b)?,
279                len: m,
280            },
281            (PositiveUnbounded { offset: a }, PositiveUnbounded { offset: b }) => {
282                PositiveUnbounded {
283                    offset: a.checked_add(b.get())?,
284                }
285            },
286            (first @ Negative { len: l, .. }, Positive { offset: 0, len: m }) if m >= l => first,
287            (
288                Negative {
289                    offset_from_end: k,
290                    len: l,
291                },
292                Negative {
293                    offset_from_end: k2,
294                    len: m2,
295                },
296            ) => {
297                if k2 >= l {
298                    Negative {
299                        offset_from_end: k,
300                        len: l.saturating_sub(k2 - m2),
301                    }
302                } else {
303                    Negative {
304                        offset_from_end: k - l + k2,
305                        len: m2,
306                    }
307                }
308            },
309            _ => return None,
310        };
311
312        if combined.is_empty() {
313            return Some(Self::EMPTY);
314        }
315        combined.is_within_i64().then_some(combined)
316    }
317
318    /// Return the smallest slice that contains both `a` and `b` at every height, or `None` if only
319    /// every row does.
320    pub fn try_new_enclosing(a: Slice, b: Slice) -> Option<Slice> {
321        use Slice::*;
322
323        if a.is_empty() {
324            return Some(b);
325        }
326        if b.is_empty() {
327            return Some(a);
328        }
329
330        match (a.canonical(), b.canonical()) {
331            (
332                Negative {
333                    offset_from_end: k,
334                    len: l,
335                },
336                Negative {
337                    offset_from_end: k2,
338                    len: l2,
339                },
340            ) => {
341                let offset_from_end = usize::max(k, k2);
342                let stop_from_end = usize::min(k - l, k2 - l2);
343                Some(Negative {
344                    offset_from_end,
345                    len: offset_from_end - stop_from_end,
346                })
347            },
348            (Negative { .. }, _) | (_, Negative { .. }) => None,
349            (a, b) => {
350                let offset = usize::min(a.positive_offset(), b.positive_offset());
351                match Option::zip(a.end_position(), b.end_position()) {
352                    Some((end_a, end_b)) => Some(Positive {
353                        offset,
354                        len: usize::max(end_a, end_b) - offset,
355                    }),
356                    None => Slice::skip(offset),
357                }
358            },
359        }
360    }
361
362    /// Return the slice that selects the rows of `self` from the output of `outer`, or `None`
363    /// if `outer` does not contain `self` or if both are the same open-ended slice.
364    pub fn try_within(self, outer: Slice) -> Option<Slice> {
365        use Slice::*;
366
367        if self.is_empty() {
368            return Some(Self::EMPTY);
369        }
370
371        match (self.canonical(), outer.canonical()) {
372            (
373                Negative {
374                    offset_from_end: k,
375                    len: l,
376                },
377                Negative {
378                    offset_from_end: outer_k,
379                    len: outer_l,
380                },
381            ) => {
382                let outer_stop_from_end = outer_k - outer_l;
383                (k <= outer_k && k - l >= outer_stop_from_end).then(|| Negative {
384                    offset_from_end: k - outer_stop_from_end,
385                    len: l,
386                })
387            },
388            (Negative { .. }, _) | (_, Negative { .. }) => None,
389            (inner, outer) => {
390                let offset = inner
391                    .positive_offset()
392                    .checked_sub(outer.positive_offset())?;
393                let is_within_end = match (inner.end_position(), outer.end_position()) {
394                    (_, None) => true,
395                    (Some(end), Some(outer_end)) => end <= outer_end,
396                    (None, Some(_)) => false,
397                };
398                if !is_within_end {
399                    return None;
400                }
401                match inner {
402                    Positive { len, .. } => Some(Positive { offset, len }),
403                    _ => Slice::skip(offset),
404                }
405            },
406        }
407    }
408
409    #[inline]
410    fn canonical(self) -> Self {
411        match self {
412            Slice::Negative {
413                offset_from_end,
414                len,
415            } => Slice::Negative {
416                offset_from_end,
417                len: len.min(offset_from_end),
418            },
419            slice => slice,
420        }
421    }
422}
423
424impl std::fmt::Display for Slice {
425    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
426        let (offset, len) = self.to_signed_offset_len();
427        match len {
428            Some(len) => write!(f, "offset: {offset}, len: {len}"),
429            None => write!(f, "offset: {offset}, len: ∞"),
430        }
431    }
432}
433
434impl From<(i64, usize)> for Slice {
435    #[inline]
436    fn from((offset, len): (i64, usize)) -> Self {
437        Slice::new(offset, Some(len)).unwrap()
438    }
439}
440
441impl From<Range<usize>> for Slice {
442    #[inline]
443    fn from(range: Range<usize>) -> Self {
444        Slice::Positive {
445            offset: range.start,
446            len: range.len(),
447        }
448    }
449}
450
451impl From<(usize, usize)> for Slice {
452    #[inline]
453    fn from((offset, len): (usize, usize)) -> Self {
454        Slice::Positive { offset, len }
455    }
456}
457
458impl<T> Index<Slice> for [T] {
459    type Output = [T];
460
461    #[inline]
462    fn index(&self, slice: Slice) -> &[T] {
463        &self[slice.resolve(self.len())]
464    }
465}
466
467impl<T> IndexMut<Slice> for [T] {
468    #[inline]
469    fn index_mut(&mut self, slice: Slice) -> &mut [T] {
470        let range = slice.resolve(self.len());
471        &mut self[range]
472    }
473}
474
475impl<T> Index<Slice> for Vec<T> {
476    type Output = [T];
477
478    #[inline]
479    fn index(&self, slice: Slice) -> &[T] {
480        &self.as_slice()[slice]
481    }
482}
483
484impl<T> IndexMut<Slice> for Vec<T> {
485    #[inline]
486    fn index_mut(&mut self, slice: Slice) -> &mut [T] {
487        &mut self.as_mut_slice()[slice]
488    }
489}
490
491#[cfg(test)]
492mod tests {
493    use super::Slice;
494
495    #[test]
496    fn test_slice_offset() {
497        assert_eq!(
498            Slice::Positive { offset: 3, len: 10 }.offsetted(1),
499            Some(Slice::Positive { offset: 2, len: 10 })
500        );
501        assert_eq!(
502            Slice::Positive { offset: 3, len: 10 }.offsetted(5),
503            Some(Slice::Positive { offset: 0, len: 8 })
504        );
505        assert_eq!(Slice::skip(3).unwrap().offsetted(5), None);
506        assert_eq!(Slice::skip(5).unwrap().offsetted(3), Slice::skip(2));
507    }
508
509    #[test]
510    fn test_slice_resolve() {
511        assert_eq!(Slice::Positive { offset: 3, len: 10 }.resolve(7), 3..7,);
512        assert_eq!(Slice::Positive { offset: 3, len: 10 }.resolve(0), 0..0,);
513        assert_eq!(Slice::Positive { offset: 3, len: 10 }.resolve(1), 1..1,);
514        assert_eq!(Slice::Positive { offset: 2, len: 0 }.resolve(10), 2..2,);
515        assert_eq!(
516            Slice::Negative {
517                offset_from_end: 3,
518                len: 2
519            }
520            .resolve(4),
521            1..3,
522        );
523        assert_eq!(
524            Slice::Negative {
525                offset_from_end: 3,
526                len: 2
527            }
528            .resolve(3),
529            0..2,
530        );
531        assert_eq!(
532            Slice::Negative {
533                offset_from_end: 3,
534                len: 2
535            }
536            .resolve(2),
537            0..1,
538        );
539        assert_eq!(
540            Slice::Negative {
541                offset_from_end: 3,
542                len: 2
543            }
544            .resolve(1),
545            0..0,
546        );
547        assert_eq!(Slice::skip(2).unwrap().resolve(5), 2..5,);
548    }
549
550    #[test]
551    fn test_slice_new() {
552        assert_eq!(Slice::new(-3, None), Some(Slice::tail(3)));
553        assert_eq!(Slice::new(-3, Some(10)), Some(Slice::tail(3)));
554        assert_eq!(Slice::new(5, None), Slice::skip(5));
555        assert_eq!(Slice::new(0, None), None);
556        assert_eq!(Slice::skip(0), None);
557        assert_eq!(
558            Slice::from((i64::MIN, 1)).to_signed_offset_len(),
559            (i64::MIN, Some(1))
560        );
561    }
562
563    /// All slices with offsets and lengths up to a small bound, including non-canonical
564    /// negative ones.
565    fn small_slices() -> Vec<Slice> {
566        let mut out = Vec::new();
567        for offset in 0..6 {
568            out.extend(Slice::skip(offset));
569            for len in 0..6 {
570                out.push(Slice::Positive { offset, len });
571                out.push(Slice::Negative {
572                    offset_from_end: offset,
573                    len,
574                });
575            }
576        }
577        out
578    }
579
580    #[test]
581    fn test_slice_offsetted() {
582        for slice in small_slices().into_iter().filter(|s| s.is_positive()) {
583            for position in 0..8 {
584                let offsetted = slice.offsetted(position);
585                for n_rows in position..12 {
586                    let rows: Vec<usize> = (0..n_rows).collect();
587                    let rest = &rows[position..];
588                    assert_eq!(
589                        offsetted.map_or(rest, |s| &rest[s]),
590                        rows[slice]
591                            .iter()
592                            .copied()
593                            .filter(|&r| r >= position)
594                            .collect::<Vec<_>>(),
595                        "{slice:?} from {position} at {n_rows} rows"
596                    );
597                }
598            }
599        }
600    }
601
602    #[test]
603    fn test_slice_reslice() {
604        for first in small_slices() {
605            for next in small_slices() {
606                let Some(combined) = first.reslice(next) else {
607                    assert!(
608                        !is_reslice_supported(first, next),
609                        "{first:?} then {next:?}"
610                    );
611                    continue;
612                };
613                for n_rows in 0..12 {
614                    let rows: Vec<usize> = (0..n_rows).collect();
615                    assert_eq!(
616                        &rows[combined], &rows[first][next],
617                        "{first:?} then {next:?} at {n_rows} rows"
618                    );
619                }
620            }
621        }
622    }
623
624    /// Return whether `reslice` combines `first` and `next`.
625    fn is_reslice_supported(first: Slice, next: Slice) -> bool {
626        use Slice::*;
627        match (first, next) {
628            _ if first.is_empty() || next.is_empty() => true,
629            (Negative { .. }, Negative { .. }) => true,
630            (Negative { .. }, Positive { offset: 0, len }) => len >= first.len().unwrap(),
631            (Negative { .. }, _) | (_, Negative { .. }) => false,
632            _ => true,
633        }
634    }
635
636    #[test]
637    fn test_slice_try_new_enclosing_and_try_within() {
638        for a in small_slices() {
639            for b in small_slices() {
640                let Some(cover) = Slice::try_new_enclosing(a, b) else {
641                    let only_all_rows_cover = a.is_positive()
642                        && b.is_positive()
643                        && usize::min(a.positive_offset(), b.positive_offset()) == 0
644                        && (a.len().is_none() || b.len().is_none());
645                    assert!(
646                        a.is_negative() != b.is_negative() || only_all_rows_cover,
647                        "{a:?} {b:?}"
648                    );
649                    continue;
650                };
651                for inner in [a, b] {
652                    let Some(within) = inner.try_within(cover) else {
653                        assert!(
654                            inner == cover && inner.len().is_none(),
655                            "{inner:?} {cover:?}"
656                        );
657                        continue;
658                    };
659                    for n_rows in 0..12 {
660                        let rows: Vec<usize> = (0..n_rows).collect();
661                        assert_eq!(
662                            &rows[cover][within], &rows[inner],
663                            "{inner:?} within {cover:?} at {n_rows} rows"
664                        );
665                    }
666                }
667            }
668        }
669    }
670
671    #[test]
672    fn test_slice_try_within() {
673        for inner in small_slices() {
674            for outer in small_slices() {
675                let Some(within) = inner.try_within(outer) else {
676                    continue;
677                };
678                for n_rows in 0..12 {
679                    let rows: Vec<usize> = (0..n_rows).collect();
680                    assert_eq!(
681                        &rows[outer][within], &rows[inner],
682                        "{inner:?} within {outer:?} at {n_rows} rows"
683                    );
684                }
685            }
686        }
687    }
688}