Skip to main content

polars_io/utils/
slice.rs

1use polars_utils::slice_enum::Slice;
2
3/// Given a `slice` that is relative to the start of a list of files, calculate the slice to apply
4/// at a file with a row offset of `current_row_offset`.
5pub fn split_slice_at_file(
6    current_row_offset_ref: &mut usize,
7    n_rows_this_file: usize,
8    global_slice_start: usize,
9    global_slice_end: usize,
10) -> (usize, usize) {
11    let current_row_offset = *current_row_offset_ref;
12    *current_row_offset_ref += n_rows_this_file;
13    match SplitSlicePosition::split_slice_at_file(
14        current_row_offset,
15        n_rows_this_file,
16        Slice::from(global_slice_start..global_slice_end),
17    ) {
18        SplitSlicePosition::Overlapping(offset, len) => (offset, len),
19        SplitSlicePosition::Before | SplitSlicePosition::After => (0, 0),
20    }
21}
22
23#[derive(Debug)]
24pub enum SplitSlicePosition {
25    Before,
26    Overlapping(usize, usize),
27    After,
28}
29
30impl SplitSlicePosition {
31    /// # Panics
32    /// Panics if `global_slice` is [`Slice::Negative`].
33    pub fn split_slice_at_file(
34        current_row_offset: usize,
35        n_rows_this_file: usize,
36        global_slice: Slice,
37    ) -> Self {
38        assert!(global_slice.is_positive());
39
40        // e.g.
41        // slice: (offset: 1, len: 1)
42        // files:
43        //   0: (1 row): current_offset: 0, next_file_offset: 1
44        //   1: (1 row): current_offset: 1, next_file_offset: 2
45        //   2: (1 row): current_offset: 2, next_file_offset: 3
46        // in this example we want to include only file 1.
47
48        let next_row_offset = current_row_offset + n_rows_this_file;
49
50        if next_row_offset <= global_slice.positive_offset() {
51            Self::Before
52        } else if global_slice
53            .end_position()
54            .is_some_and(|end| current_row_offset >= end)
55        {
56            Self::After
57        } else {
58            let range = global_slice
59                .offsetted(current_row_offset)
60                .map_or(0..n_rows_this_file, |s| s.resolve(n_rows_this_file));
61            Self::Overlapping(range.start, range.len())
62        }
63    }
64}