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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
use std::borrow::Cow;
use std::sync::Arc;

use arrow::array::ArrayRef;
use polars_error::constants::LENGTH_LIMIT_MSG;
use polars_utils::IdxSize;

use crate::datatypes::IdxCa;
use crate::error::PolarsResult;
use crate::prelude::explode::ExplodeByOffsets;
use crate::prelude::*;
use crate::series::private::{PrivateSeries, PrivateSeriesNumeric};
use crate::series::*;

impl Series {
    pub fn new_null(name: &str, len: usize) -> Series {
        NullChunked::new(Arc::from(name), len).into_series()
    }
}

#[derive(Clone)]
pub struct NullChunked {
    pub(crate) name: Arc<str>,
    length: IdxSize,
    // we still need chunks as many series consumers expect
    // chunks to be there
    chunks: Vec<ArrayRef>,
}

impl NullChunked {
    pub(crate) fn new(name: Arc<str>, len: usize) -> Self {
        Self {
            name,
            length: len as IdxSize,
            chunks: vec![Box::new(arrow::array::NullArray::new(
                ArrowDataType::Null,
                len,
            ))],
        }
    }
}
impl PrivateSeriesNumeric for NullChunked {}

impl PrivateSeries for NullChunked {
    fn compute_len(&mut self) {
        fn inner(chunks: &[ArrayRef]) -> usize {
            match chunks.len() {
                // fast path
                1 => chunks[0].len(),
                _ => chunks.iter().fold(0, |acc, arr| acc + arr.len()),
            }
        }
        self.length = IdxSize::try_from(inner(&self.chunks)).expect(LENGTH_LIMIT_MSG);
    }
    fn _field(&self) -> Cow<Field> {
        Cow::Owned(Field::new(self.name(), DataType::Null))
    }

    #[allow(unused)]
    fn _set_flags(&mut self, flags: Settings) {}

    fn _dtype(&self) -> &DataType {
        &DataType::Null
    }

    #[cfg(feature = "zip_with")]
    fn zip_with_same_type(&self, mask: &BooleanChunked, other: &Series) -> PolarsResult<Series> {
        let len = match (self.len(), mask.len(), other.len()) {
            (a, b, c) if a == b && b == c => a,
            (1, a, b) | (a, 1, b) | (a, b, 1) if a == b => a,
            (a, 1, 1) | (1, a, 1) | (1, 1, a) => a,
            (_, 0, _) => 0,
            _ => {
                polars_bail!(ShapeMismatch: "shapes of `self`, `mask` and `other` are not suitable for `zip_with` operation")
            },
        };

        Ok(Self::new(self.name().into(), len).into_series())
    }
    fn explode_by_offsets(&self, offsets: &[i64]) -> Series {
        ExplodeByOffsets::explode_by_offsets(self, offsets)
    }

    #[cfg(feature = "algorithm_group_by")]
    fn group_tuples(&self, _multithreaded: bool, _sorted: bool) -> PolarsResult<GroupsProxy> {
        Ok(if self.is_empty() {
            GroupsProxy::default()
        } else {
            GroupsProxy::Slice {
                groups: vec![[0, self.length]],
                rolling: false,
            }
        })
    }

    fn _get_flags(&self) -> Settings {
        Settings::empty()
    }
}

impl SeriesTrait for NullChunked {
    fn name(&self) -> &str {
        self.name.as_ref()
    }

    fn rename(&mut self, name: &str) {
        self.name = Arc::from(name)
    }

    fn chunks(&self) -> &Vec<ArrayRef> {
        &self.chunks
    }
    unsafe fn chunks_mut(&mut self) -> &mut Vec<ArrayRef> {
        &mut self.chunks
    }

    fn chunk_lengths(&self) -> ChunkIdIter {
        self.chunks.iter().map(|chunk| chunk.len())
    }

    #[cfg(feature = "chunked_ids")]
    unsafe fn _take_chunked_unchecked(&self, by: &[ChunkId], _sorted: IsSorted) -> Series {
        NullChunked::new(self.name.clone(), by.len()).into_series()
    }

    #[cfg(feature = "chunked_ids")]
    unsafe fn _take_opt_chunked_unchecked(&self, by: &[Option<ChunkId>]) -> Series {
        NullChunked::new(self.name.clone(), by.len()).into_series()
    }

    fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {
        Ok(NullChunked::new(self.name.clone(), indices.len()).into_series())
    }

    unsafe fn take_unchecked(&self, indices: &IdxCa) -> Series {
        NullChunked::new(self.name.clone(), indices.len()).into_series()
    }

    fn take_slice(&self, indices: &[IdxSize]) -> PolarsResult<Series> {
        Ok(NullChunked::new(self.name.clone(), indices.len()).into_series())
    }

    unsafe fn take_slice_unchecked(&self, indices: &[IdxSize]) -> Series {
        NullChunked::new(self.name.clone(), indices.len()).into_series()
    }

    fn len(&self) -> usize {
        self.length as usize
    }

    fn has_validity(&self) -> bool {
        true
    }

    fn rechunk(&self) -> Series {
        NullChunked::new(self.name.clone(), self.len()).into_series()
    }

    fn cast(&self, data_type: &DataType) -> PolarsResult<Series> {
        Ok(Series::full_null(self.name.as_ref(), self.len(), data_type))
    }

    fn null_count(&self) -> usize {
        self.len()
    }

    #[cfg(feature = "algorithm_group_by")]
    fn unique(&self) -> PolarsResult<Series> {
        let ca = NullChunked::new(self.name.clone(), self.n_unique().unwrap());
        Ok(ca.into_series())
    }

    #[cfg(feature = "algorithm_group_by")]
    fn n_unique(&self) -> PolarsResult<usize> {
        let n = if self.is_empty() { 0 } else { 1 };
        Ok(n)
    }

    fn new_from_index(&self, _index: usize, length: usize) -> Series {
        NullChunked::new(self.name.clone(), length).into_series()
    }

    fn get(&self, index: usize) -> PolarsResult<AnyValue> {
        polars_ensure!(index < self.len(), oob = index, self.len());
        Ok(AnyValue::Null)
    }

    fn slice(&self, offset: i64, length: usize) -> Series {
        let (chunks, len) = chunkops::slice(&self.chunks, offset, length, self.len());
        NullChunked {
            name: self.name.clone(),
            length: len as IdxSize,
            chunks,
        }
        .into_series()
    }

    fn is_null(&self) -> BooleanChunked {
        BooleanChunked::full(self.name(), true, self.len())
    }

    fn is_not_null(&self) -> BooleanChunked {
        BooleanChunked::full(self.name(), false, self.len())
    }

    fn reverse(&self) -> Series {
        self.clone().into_series()
    }

    fn filter(&self, filter: &BooleanChunked) -> PolarsResult<Series> {
        let len = filter.sum().unwrap_or(0);
        Ok(NullChunked::new(self.name.clone(), len as usize).into_series())
    }

    fn shift(&self, _periods: i64) -> Series {
        self.clone().into_series()
    }

    fn append(&mut self, other: &Series) -> PolarsResult<()> {
        polars_ensure!(other.dtype() == &DataType::Null, ComputeError: "expected null dtype");
        // we don't create a new null array to keep probability of aligned chunks higher
        self.chunks.extend(other.chunks().iter().cloned());
        self.length += other.len() as IdxSize;
        Ok(())
    }

    fn extend(&mut self, other: &Series) -> PolarsResult<()> {
        *self = NullChunked::new(self.name.clone(), self.len() + other.len());
        Ok(())
    }

    fn clone_inner(&self) -> Arc<dyn SeriesTrait> {
        Arc::new(self.clone())
    }
}

unsafe impl IntoSeries for NullChunked {
    fn into_series(self) -> Series
    where
        Self: Sized,
    {
        Series(Arc::new(self))
    }
}