1use std::any::Any;
2
3use polars_error::constants::LENGTH_LIMIT_MSG;
4
5use self::compare_inner::TotalOrdInner;
6use super::*;
7use crate::chunked_array::ops::compare_inner::{IntoTotalEqInner, NonNull, TotalEqInner};
8use crate::chunked_array::ops::sort::arg_sort_multiple::arg_sort_multiple_impl;
9use crate::series::private::{PrivateSeries, PrivateSeriesNumeric};
10use crate::series::*;
11
12impl Series {
13 pub fn new_null(name: PlSmallStr, len: usize) -> Series {
14 NullChunked::new(name, len).into_series()
15 }
16}
17
18#[derive(Clone)]
19pub struct NullChunked {
20 pub(crate) name: PlSmallStr,
21 length: usize,
22 chunks: Vec<ArrayRef>,
25}
26
27impl NullChunked {
28 pub(crate) fn new(name: PlSmallStr, len: usize) -> Self {
29 if len >= (IdxSize::MAX as usize) && chunkops::CHECK_LENGTH.get() {
30 panic!("{}", LENGTH_LIMIT_MSG);
31 }
32
33 Self {
34 name,
35 length: len,
36 chunks: vec![Box::new(arrow::array::NullArray::new(
37 ArrowDataType::Null,
38 len,
39 ))],
40 }
41 }
42
43 pub fn len(&self) -> usize {
44 self.length
45 }
46
47 pub fn is_empty(&self) -> bool {
48 self.length == 0
49 }
50}
51impl PrivateSeriesNumeric for NullChunked {
52 fn bit_repr(&self) -> Option<BitRepr> {
53 Some(BitRepr::U32(UInt32Chunked::full_null(
54 self.name.clone(),
55 self.len(),
56 )))
57 }
58}
59
60impl PrivateSeries for NullChunked {
61 fn compute_len(&mut self) {
62 fn inner(chunks: &[ArrayRef]) -> usize {
63 match chunks.len() {
64 1 => chunks[0].len(),
66 _ => chunks.iter().fold(0, |acc, arr| acc + arr.len()),
67 }
68 }
69 let len = inner(&self.chunks);
70 if len >= (IdxSize::MAX as usize) && chunkops::CHECK_LENGTH.get() {
71 panic!("{}", LENGTH_LIMIT_MSG);
72 }
73 self.length = len;
74 }
75 fn _field(&self) -> Cow<'_, Field> {
76 Cow::Owned(Field::new(self.name().clone(), DataType::Null))
77 }
78
79 #[allow(unused)]
80 fn _set_flags(&mut self, flags: StatisticsFlags) {}
81
82 fn _dtype(&self) -> &DataType {
83 &DataType::Null
84 }
85
86 #[cfg(feature = "zip_with")]
87 fn zip_with_same_type(&self, mask: &BooleanChunked, other: &Series) -> PolarsResult<Series> {
88 let len = match (self.len(), mask.len(), other.len()) {
89 (a, b, c) if a == b && b == c => a,
90 (1, a, b) | (a, 1, b) | (a, b, 1) if a == b => a,
91 (a, 1, 1) | (1, a, 1) | (1, 1, a) => a,
92 (_, 0, _) => 0,
93 _ => {
94 polars_bail!(ShapeMismatch: "shapes of `self`, `mask` and `other` are not suitable for `zip_with` operation")
95 },
96 };
97
98 Ok(Self::new(self.name().clone(), len).into_series())
99 }
100
101 fn into_total_eq_inner<'a>(&'a self) -> Box<dyn TotalEqInner + 'a> {
102 IntoTotalEqInner::into_total_eq_inner(self)
103 }
104 fn into_total_ord_inner<'a>(&'a self) -> Box<dyn TotalOrdInner + 'a> {
105 IntoTotalOrdInner::into_total_ord_inner(self)
106 }
107
108 fn subtract(&self, _rhs: &Series) -> PolarsResult<Series> {
109 null_arithmetic(self, _rhs, "subtract")
110 }
111
112 fn add_to(&self, _rhs: &Series) -> PolarsResult<Series> {
113 null_arithmetic(self, _rhs, "add_to")
114 }
115 fn multiply(&self, _rhs: &Series) -> PolarsResult<Series> {
116 null_arithmetic(self, _rhs, "multiply")
117 }
118 fn divide(&self, _rhs: &Series) -> PolarsResult<Series> {
119 null_arithmetic(self, _rhs, "divide")
120 }
121 fn remainder(&self, _rhs: &Series) -> PolarsResult<Series> {
122 null_arithmetic(self, _rhs, "remainder")
123 }
124
125 #[cfg(feature = "algorithm_group_by")]
126 fn group_tuples(&self, _multithreaded: bool, _sorted: bool) -> PolarsResult<GroupsType> {
127 Ok(if self.is_empty() {
128 GroupsType::default()
129 } else {
130 GroupsType::new_slice(vec![[0, self.length as IdxSize]], false, true)
131 })
132 }
133
134 #[cfg(feature = "algorithm_group_by")]
135 unsafe fn agg_list(&self, groups: &GroupsType) -> Series {
136 AggList::agg_list(self, groups)
137 }
138
139 fn _get_flags(&self) -> StatisticsFlags {
140 StatisticsFlags::empty()
141 }
142
143 fn vec_hash(
144 &self,
145 random_state: PlSeedableRandomStateQuality,
146 buf: &mut Vec<u64>,
147 ) -> PolarsResult<()> {
148 VecHash::vec_hash(self, random_state, buf)?;
149 Ok(())
150 }
151
152 fn vec_hash_combine(
153 &self,
154 build_hasher: PlSeedableRandomStateQuality,
155 hashes: &mut [u64],
156 ) -> PolarsResult<()> {
157 VecHash::vec_hash_combine(self, build_hasher, hashes)?;
158 Ok(())
159 }
160
161 fn arg_sort_multiple(
162 &self,
163 by: &[Column],
164 options: &SortMultipleOptions,
165 ) -> PolarsResult<IdxCa> {
166 let vals = (0..self.len())
167 .map(|i| (i as IdxSize, NonNull(())))
168 .collect();
169 arg_sort_multiple_impl(vals, by, options)
170 }
171}
172
173fn null_arithmetic(lhs: &NullChunked, rhs: &Series, op: &str) -> PolarsResult<Series> {
174 let output_len = match (lhs.len(), rhs.len()) {
175 (1, len_r) => len_r,
176 (len_l, 1) => len_l,
177 (len_l, len_r) if len_l == len_r => len_l,
178 _ => polars_bail!(ComputeError: "Cannot {:?} two series of different lengths.", op),
179 };
180 Ok(NullChunked::new(lhs.name().clone(), output_len).into_series())
181}
182
183impl SeriesTrait for NullChunked {
184 fn name(&self) -> &PlSmallStr {
185 &self.name
186 }
187
188 fn rename(&mut self, name: PlSmallStr) {
189 self.name = name
190 }
191
192 fn chunks(&self) -> &Vec<ArrayRef> {
193 &self.chunks
194 }
195 unsafe fn chunks_mut(&mut self) -> &mut Vec<ArrayRef> {
196 &mut self.chunks
197 }
198
199 fn chunk_lengths(&self) -> ChunkLenIter<'_> {
200 self.chunks.iter().map(|chunk| chunk.len())
201 }
202
203 fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {
204 Ok(NullChunked::new(self.name.clone(), indices.len()).into_series())
205 }
206
207 unsafe fn take_unchecked(&self, indices: &IdxCa) -> Series {
208 NullChunked::new(self.name.clone(), indices.len()).into_series()
209 }
210
211 fn take_slice(&self, indices: &[IdxSize]) -> PolarsResult<Series> {
212 Ok(NullChunked::new(self.name.clone(), indices.len()).into_series())
213 }
214
215 unsafe fn take_slice_unchecked(&self, indices: &[IdxSize]) -> Series {
216 NullChunked::new(self.name.clone(), indices.len()).into_series()
217 }
218
219 fn deposit(&self, validity: &Bitmap) -> Series {
220 assert_eq!(validity.set_bits(), 0);
221 self.clone().into_series()
222 }
223
224 fn len(&self) -> usize {
225 self.length
226 }
227
228 fn has_nulls(&self) -> bool {
229 !self.is_empty()
230 }
231
232 fn rechunk(&self) -> Series {
233 NullChunked::new(self.name.clone(), self.len()).into_series()
234 }
235
236 fn with_validity(&self, _validity: Option<Bitmap>) -> Series {
237 self.clone().into_series()
238 }
239
240 fn drop_nulls(&self) -> Series {
241 NullChunked::new(self.name.clone(), 0).into_series()
242 }
243
244 fn cast(&self, dtype: &DataType, _cast_options: CastOptions) -> PolarsResult<Series> {
245 Ok(Series::full_null(self.name.clone(), self.len(), dtype))
246 }
247
248 fn null_count(&self) -> usize {
249 self.len()
250 }
251
252 #[cfg(feature = "algorithm_group_by")]
253 fn unique(&self) -> PolarsResult<Series> {
254 let ca = NullChunked::new(self.name.clone(), self.n_unique().unwrap());
255 Ok(ca.into_series())
256 }
257
258 #[cfg(feature = "algorithm_group_by")]
259 fn n_unique(&self) -> PolarsResult<usize> {
260 let n = if self.is_empty() { 0 } else { 1 };
261 Ok(n)
262 }
263
264 #[cfg(feature = "algorithm_group_by")]
265 fn arg_unique(&self) -> PolarsResult<IdxCa> {
266 let idxs: Vec<IdxSize> = (0..self.n_unique().unwrap() as IdxSize).collect();
267 Ok(IdxCa::new(self.name().clone(), idxs))
268 }
269
270 #[cfg(feature = "algorithm_group_by")]
271 fn unique_id(&self) -> PolarsResult<(IdxSize, Vec<IdxSize>)> {
272 if self.is_empty() {
273 Ok((0, Vec::new()))
274 } else {
275 Ok((1, vec![0; self.len()]))
276 }
277 }
278
279 fn new_from_index(&self, _index: usize, length: usize) -> Series {
280 NullChunked::new(self.name.clone(), length).into_series()
281 }
282
283 unsafe fn get_unchecked(&self, _index: usize) -> AnyValue<'_> {
284 AnyValue::Null
285 }
286
287 fn slice(&self, offset: i64, length: usize) -> Series {
288 let (chunks, len) = chunkops::slice(&self.chunks, offset, length, self.len());
289 NullChunked {
290 name: self.name.clone(),
291 length: len,
292 chunks,
293 }
294 .into_series()
295 }
296
297 fn split_at(&self, offset: i64) -> (Series, Series) {
298 let (l, r) = chunkops::split_at(self.chunks(), offset, self.len());
299 (
300 NullChunked {
301 name: self.name.clone(),
302 length: l.iter().map(|arr| arr.len()).sum(),
303 chunks: l,
304 }
305 .into_series(),
306 NullChunked {
307 name: self.name.clone(),
308 length: r.iter().map(|arr| arr.len()).sum(),
309 chunks: r,
310 }
311 .into_series(),
312 )
313 }
314
315 fn sort_with(&self, _options: SortOptions) -> PolarsResult<Series> {
316 Ok(self.clone().into_series())
317 }
318
319 fn arg_sort(&self, _options: SortOptions) -> IdxCa {
320 IdxCa::from_vec(self.name().clone(), (0..self.len() as IdxSize).collect())
321 }
322
323 fn is_null(&self) -> BooleanChunked {
324 BooleanChunked::full(self.name().clone(), true, self.len())
325 }
326
327 fn is_not_null(&self) -> BooleanChunked {
328 BooleanChunked::full(self.name().clone(), false, self.len())
329 }
330
331 fn reverse(&self) -> Series {
332 self.clone().into_series()
333 }
334
335 fn filter(&self, filter: &BooleanChunked) -> PolarsResult<Series> {
336 let len = if self.is_empty() {
337 polars_ensure!(filter.len() <= 1, ShapeMismatch: "filter's length: {} differs from that of the series: 0", filter.len());
339 0
340 } else if filter.len() == 1 {
341 return match filter.get(0) {
342 Some(true) => Ok(self.clone().into_series()),
343 None | Some(false) => Ok(NullChunked::new(self.name.clone(), 0).into_series()),
344 };
345 } else {
346 polars_ensure!(filter.len() == self.len(), ShapeMismatch: "filter's length: {} differs from that of the series: {}", filter.len(), self.len());
347 filter.sum().unwrap_or(0) as usize
348 };
349 Ok(NullChunked::new(self.name.clone(), len).into_series())
350 }
351
352 fn shift(&self, _periods: i64) -> Series {
353 self.clone().into_series()
354 }
355
356 fn sum_reduce(&self) -> PolarsResult<Scalar> {
357 Ok(Scalar::null(DataType::Null))
358 }
359
360 fn min_reduce(&self) -> PolarsResult<Scalar> {
361 Ok(Scalar::null(DataType::Null))
362 }
363
364 fn max_reduce(&self) -> PolarsResult<Scalar> {
365 Ok(Scalar::null(DataType::Null))
366 }
367
368 fn mean_reduce(&self) -> PolarsResult<Scalar> {
369 Ok(Scalar::null(DataType::Null))
370 }
371
372 fn median_reduce(&self) -> PolarsResult<Scalar> {
373 Ok(Scalar::null(DataType::Null))
374 }
375
376 fn std_reduce(&self, _ddof: u8) -> PolarsResult<Scalar> {
377 Ok(Scalar::null(DataType::Null))
378 }
379
380 fn var_reduce(&self, _ddof: u8) -> PolarsResult<Scalar> {
381 Ok(Scalar::null(DataType::Null))
382 }
383
384 fn append(&mut self, other: &Series) -> PolarsResult<()> {
385 polars_ensure!(other.dtype() == &DataType::Null, ComputeError: "expected null dtype");
386 self.length += other.len();
388 self.chunks.extend(other.chunks().iter().cloned());
389 Ok(())
390 }
391 fn append_owned(&mut self, mut other: Series) -> PolarsResult<()> {
392 polars_ensure!(other.dtype() == &DataType::Null, ComputeError: "expected null dtype");
393 let other: &mut NullChunked = other._get_inner_mut().as_any_mut().downcast_mut().unwrap();
395 self.length += other.len();
396 self.chunks.extend(std::mem::take(&mut other.chunks));
397 Ok(())
398 }
399
400 fn extend(&mut self, other: &Series) -> PolarsResult<()> {
401 *self = NullChunked::new(self.name.clone(), self.len() + other.len());
402 Ok(())
403 }
404
405 #[cfg(feature = "approx_unique")]
406 fn approx_n_unique(&self) -> PolarsResult<IdxSize> {
407 Ok(if self.is_empty() { 0 } else { 1 })
408 }
409
410 fn clone_inner(&self) -> Arc<dyn SeriesTrait> {
411 Arc::new(self.clone())
412 }
413
414 fn find_validity_mismatch(&self, other: &Series, idxs: &mut Vec<IdxSize>) {
415 ChunkNestingUtils::find_validity_mismatch(self, other, idxs)
416 }
417
418 fn as_any(&self) -> &dyn Any {
419 self
420 }
421
422 fn as_any_mut(&mut self) -> &mut dyn Any {
423 self
424 }
425
426 fn as_phys_any(&self) -> &dyn Any {
427 self
428 }
429
430 fn as_arc_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
431 self as _
432 }
433}
434
435unsafe impl IntoSeries for NullChunked {
436 fn into_series(self) -> Series
437 where
438 Self: Sized,
439 {
440 Series(Arc::new(self))
441 }
442}