1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#[cfg(feature = "object")]
use crate::chunked_array::object::builder::ObjectChunkedBuilder;
use crate::prelude::*;
use crate::utils::slice_offsets;
#[cfg(feature = "object")]
use arrow::array::Array;
use arrow::compute::concatenate;

#[inline]
fn slice(
    chunks: &[ArrayRef],
    offset: i64,
    slice_length: usize,
    own_length: usize,
) -> Vec<ArrayRef> {
    let mut new_chunks = Vec::with_capacity(1);
    let (raw_offset, slice_len) = slice_offsets(offset, slice_length, own_length);

    let mut remaining_length = slice_len;
    let mut remaining_offset = raw_offset;

    for chunk in chunks {
        let chunk_len = chunk.len();
        if remaining_offset > 0 && remaining_offset >= chunk_len {
            remaining_offset -= chunk_len;
            continue;
        }
        let take_len = if remaining_length + remaining_offset > chunk_len {
            chunk_len - remaining_offset
        } else {
            remaining_length
        };

        debug_assert!(remaining_offset + take_len <= chunk.len());
        unsafe {
            // Safety:
            // this function ensures the slices are in bounds
            new_chunks.push(chunk.slice_unchecked(remaining_offset, take_len).into());
        }
        remaining_length -= take_len;
        remaining_offset = 0;
        if remaining_length == 0 {
            break;
        }
    }
    new_chunks
}

impl<T> ChunkOps for ChunkedArray<T>
where
    T: PolarsNumericType,
{
    fn rechunk(&self) -> Self {
        if self.chunks().len() == 1 {
            self.clone()
        } else {
            let chunks = vec![concatenate::concatenate(
                self.chunks
                    .iter()
                    .map(|a| &**a)
                    .collect::<Vec<_>>()
                    .as_slice(),
            )
            .unwrap()
            .into()];
            ChunkedArray::from_chunks(self.name(), chunks)
        }
    }
    #[inline]
    fn slice(&self, offset: i64, length: usize) -> Self {
        self.copy_with_chunks(slice(&self.chunks, offset, length, self.len()))
    }
}

impl ChunkOps for BooleanChunked {
    fn rechunk(&self) -> Self {
        if self.chunks().len() == 1 {
            self.clone()
        } else {
            let chunks = vec![concatenate::concatenate(
                self.chunks
                    .iter()
                    .map(|a| &**a)
                    .collect::<Vec<_>>()
                    .as_slice(),
            )
            .unwrap()
            .into()];
            ChunkedArray::from_chunks(self.name(), chunks)
        }
    }
    #[inline]
    fn slice(&self, offset: i64, length: usize) -> Self {
        self.copy_with_chunks(slice(&self.chunks, offset, length, self.len()))
    }
}

impl ChunkOps for Utf8Chunked {
    fn rechunk(&self) -> Self {
        if self.chunks().len() == 1 {
            self.clone()
        } else {
            let chunks = vec![concatenate::concatenate(
                self.chunks
                    .iter()
                    .map(|a| &**a)
                    .collect::<Vec<_>>()
                    .as_slice(),
            )
            .unwrap()
            .into()];
            ChunkedArray::from_chunks(self.name(), chunks)
        }
    }
    #[inline]
    fn slice(&self, offset: i64, length: usize) -> Self {
        self.copy_with_chunks(slice(&self.chunks, offset, length, self.len()))
    }
}

impl ChunkOps for ListChunked {
    fn rechunk(&self) -> Self {
        if self.chunks.len() == 1 {
            self.clone()
        } else {
            let chunks = vec![concatenate::concatenate(
                self.chunks
                    .iter()
                    .map(|a| &**a)
                    .collect::<Vec<_>>()
                    .as_slice(),
            )
            .unwrap()
            .into()];
            let mut ca = ListChunked::from_chunks(self.name(), chunks);
            if self.can_fast_explode() {
                ca.set_fast_explode()
            }
            ca
        }
    }
    #[inline]
    fn slice(&self, offset: i64, length: usize) -> Self {
        self.copy_with_chunks(slice(&self.chunks, offset, length, self.len()))
    }
}

#[cfg(feature = "object")]
impl<T> ChunkOps for ObjectChunked<T>
where
    T: PolarsObject,
{
    fn rechunk(&self) -> Self
    where
        Self: std::marker::Sized,
    {
        if self.chunks.len() == 1 {
            self.clone()
        } else {
            let mut builder = ObjectChunkedBuilder::new(self.name(), self.len());
            let chunks = self.downcast_iter();

            // todo! use iterators once implemented
            // no_null path
            if !self.has_validity() {
                for arr in chunks {
                    for idx in 0..arr.len() {
                        builder.append_value(arr.value(idx).clone())
                    }
                }
            } else {
                for arr in chunks {
                    for idx in 0..arr.len() {
                        if arr.is_valid(idx) {
                            builder.append_value(arr.value(idx).clone())
                        } else {
                            builder.append_null()
                        }
                    }
                }
            }
            builder.finish()
        }
    }
    #[inline]
    fn slice(&self, offset: i64, length: usize) -> Self {
        self.copy_with_chunks(slice(&self.chunks, offset, length, self.len()))
    }
}

#[cfg(test)]
mod test {
    use crate::prelude::*;

    #[test]
    #[cfg(feature = "dtype-categorical")]
    fn test_categorical_map_after_rechunk() {
        let s = Series::new("", &["foo", "bar", "spam"]);
        let mut a = s.cast(&DataType::Categorical(None)).unwrap();

        a.append(&a.slice(0, 2)).unwrap();
        let a = a.rechunk();
        assert!(a.categorical().unwrap().get_rev_map().len() > 0);
    }
}