1#![forbid(unsafe_code)]
2#![warn(rustdoc::broken_intra_doc_links)]
3
4use std::sync::{Arc, OnceLock};
58
59use fp_types::{
60 DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType, Timedelta,
61 Timestamp, TypeError, cast_scalar, cast_scalar_owned, common_dtype, infer_dtype, nanall,
62 nanany, nanargmax, nanargmin, nancummax, nancummin, nancumprod, nancumsum, nankurt, nanmax,
63 nanmean, nanmedian, nanmin, nannunique, nanprod, nanptp, nanquantile, nansem, nanskew, nanstd,
64 nansum, nanvar,
65};
66use rustc_hash::{FxHashMap, FxHashSet};
67use serde::{Deserialize, Serialize};
68use thiserror::Error;
69
70const STRIDED_FLOAT64_MIN_LEN: usize = 1024;
71
72#[doc(hidden)]
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct Utf8LowerHexSequence {
75 prefix_len: usize,
76 hex_width: usize,
77 start: u64,
78}
79
80impl Utf8LowerHexSequence {
81 #[must_use]
82 pub fn prefix_len(&self) -> usize {
83 self.prefix_len
84 }
85
86 #[must_use]
87 pub fn hex_width(&self) -> usize {
88 self.hex_width
89 }
90
91 #[must_use]
92 pub fn width(&self) -> usize {
93 self.prefix_len + self.hex_width
94 }
95
96 #[must_use]
97 pub fn start(&self) -> u64 {
98 self.start
99 }
100
101 #[must_use]
102 pub fn value_at(&self, row: usize) -> Option<u64> {
103 self.start.checked_add(row as u64)
104 }
105
106 #[must_use]
107 pub fn same_shape(&self, other: Self) -> bool {
108 self.prefix_len == other.prefix_len && self.hex_width == other.hex_width
109 }
110}
111
112#[derive(Debug)]
113struct Utf8FactorizeDefaultWitness {
114 codes: Arc<[i64]>,
115 unique_bytes: Arc<[u8]>,
116 unique_offsets: Arc<[usize]>,
117}
118
119fn build_utf8_factorize_default_witness(
120 bytes: &[u8],
121 offsets: &[usize],
122) -> Utf8FactorizeDefaultWitness {
123 let nrows = offsets.len().saturating_sub(1);
124 let mut idx_map: FxHashMap<&[u8], i64> = FxHashMap::default();
125 let mut codes: Vec<i64> = Vec::with_capacity(nrows);
126 let mut unique_bytes: Vec<u8> = Vec::new();
127 let mut unique_offsets: Vec<usize> = Vec::new();
128 unique_offsets.push(0);
129
130 for row in 0..nrows {
131 let span = &bytes[offsets[row]..offsets[row + 1]];
132 let code = match idx_map.get(span) {
133 Some(&code) => code,
134 None => {
135 let code = unique_offsets.len() as i64 - 1;
136 idx_map.insert(span, code);
137 unique_bytes.extend_from_slice(span);
138 unique_offsets.push(unique_bytes.len());
139 code
140 }
141 };
142 codes.push(code);
143 }
144
145 Utf8FactorizeDefaultWitness {
146 codes: Arc::from(codes),
147 unique_bytes: Arc::from(unique_bytes),
148 unique_offsets: Arc::from(unique_offsets),
149 }
150}
151
152#[derive(Debug, Clone, Eq)]
153pub struct ValidityMask {
154 words: Vec<u64>,
155 invalid_ranges: Option<Arc<[(usize, usize)]>>,
156 len: usize,
157}
158
159impl ValidityMask {
160 fn is_all_valid_sentinel(&self) -> bool {
161 self.len > 0 && self.words.is_empty() && self.invalid_ranges.is_none()
162 }
163
164 fn invalid_ranges_contain(ranges: &[(usize, usize)], idx: usize) -> bool {
165 let mut lo = 0usize;
166 let mut hi = ranges.len();
167 while lo < hi {
168 let mid = (lo + hi) / 2;
169 let (start, len) = ranges[mid];
170 let end = start + len;
171 if idx < start {
172 hi = mid;
173 } else if idx >= end {
174 lo = mid + 1;
175 } else {
176 return true;
177 }
178 }
179 false
180 }
181
182 fn invalid_ranges_len(ranges: &[(usize, usize)]) -> usize {
183 ranges.iter().map(|&(_, len)| len).sum()
184 }
185
186 fn materialized_all_valid_words(len: usize) -> Vec<u64> {
187 let word_count = len.div_ceil(64);
188 let mut words = vec![u64::MAX; word_count];
189 let remainder = len % 64;
190 if remainder > 0
191 && let Some(last) = words.last_mut()
192 {
193 *last = (1_u64 << remainder) - 1;
194 }
195 words
196 }
197
198 fn materialized_words(&self) -> Vec<u64> {
199 if self.is_all_valid_sentinel() {
200 return Self::materialized_all_valid_words(self.len);
201 }
202 if let Some(ranges) = &self.invalid_ranges {
203 let mut words = Self::materialized_all_valid_words(self.len);
204 for &(start, len) in ranges.iter() {
205 for idx in start..start + len {
206 words[idx / 64] &= !(1_u64 << (idx % 64));
207 }
208 }
209 return words;
210 }
211 self.words.clone()
212 }
213
214 #[must_use]
218 #[doc(hidden)]
219 pub fn packed_words_for_scan(&self) -> Vec<u64> {
220 self.materialized_words()
221 }
222
223 fn words_are_all_valid(words: &[u64], len: usize) -> bool {
224 if len == 0 {
225 return words.is_empty();
226 }
227 let word_count = len.div_ceil(64);
228 if words.len() != word_count {
229 return false;
230 }
231 let full_words = len / 64;
232 if words.iter().take(full_words).any(|&word| word != u64::MAX) {
233 return false;
234 }
235 let remainder = len % 64;
236 if remainder == 0 {
237 return true;
238 }
239 words.get(full_words).copied() == Some((1_u64 << remainder) - 1)
240 }
241
242 fn materialize_if_all_valid_sentinel(&mut self) {
243 if self.is_all_valid_sentinel() || self.invalid_ranges.is_some() {
244 self.words = self.materialized_words();
245 self.invalid_ranges = None;
246 }
247 }
248
249 #[must_use]
250 pub fn from_values(values: &[Scalar]) -> Self {
251 let len = values.len();
252 let word_count = len.div_ceil(64);
253 let mut words = vec![0_u64; word_count];
254 let mut all_valid = true;
255 for (idx, value) in values.iter().enumerate() {
256 if !value.is_missing() {
257 words[idx / 64] |= 1_u64 << (idx % 64);
258 } else {
259 all_valid = false;
260 }
261 }
262 if all_valid {
263 return Self::all_valid(len);
264 }
265 Self {
266 words,
267 invalid_ranges: None,
268 len,
269 }
270 }
271
272 #[must_use]
278 pub fn from_f64(data: &[f64]) -> Self {
279 let len = data.len();
280 let word_count = len.div_ceil(64);
281 let mut words = vec![0_u64; word_count];
282 let mut all_valid = true;
283 for (idx, &v) in data.iter().enumerate() {
284 if !v.is_nan() {
285 words[idx / 64] |= 1_u64 << (idx % 64);
286 } else {
287 all_valid = false;
288 }
289 }
290 if all_valid {
291 return Self::all_valid(len);
292 }
293 Self {
294 words,
295 invalid_ranges: None,
296 len,
297 }
298 }
299
300 #[must_use]
301 pub fn all_valid(len: usize) -> Self {
302 Self {
303 words: Vec::new(),
304 invalid_ranges: None,
305 len,
306 }
307 }
308
309 #[must_use]
314 #[doc(hidden)]
315 pub fn from_words(words: Vec<u64>, len: usize) -> Self {
316 debug_assert_eq!(words.len(), len.div_ceil(64));
317 debug_assert!(
318 len.is_multiple_of(64) || words.last().is_none_or(|w| w >> (len % 64) == 0),
319 "validity bits beyond len must be zero"
320 );
321 if Self::words_are_all_valid(&words, len) {
322 return Self::all_valid(len);
323 }
324 Self {
325 words,
326 invalid_ranges: None,
327 len,
328 }
329 }
330
331 #[must_use]
332 #[doc(hidden)]
333 pub fn from_invalid_ranges(invalid_ranges: Arc<[(usize, usize)]>, len: usize) -> Self {
334 debug_assert!(
335 invalid_ranges.iter().all(|&(start, run_len)| {
336 start.checked_add(run_len).is_some_and(|end| end <= len)
337 })
338 );
339 debug_assert!(invalid_ranges.windows(2).all(|window| {
340 let (left_start, left_len) = window[0];
341 let (right_start, _) = window[1];
342 left_start + left_len <= right_start
343 }));
344 if invalid_ranges.is_empty() {
345 return Self::all_valid(len);
346 }
347 Self {
348 words: Vec::new(),
349 invalid_ranges: Some(invalid_ranges),
350 len,
351 }
352 }
353
354 #[must_use]
355 pub fn all_invalid(len: usize) -> Self {
356 let word_count = len.div_ceil(64);
357 Self {
358 words: vec![0_u64; word_count],
359 invalid_ranges: None,
360 len,
361 }
362 }
363
364 #[must_use]
365 pub fn get(&self, idx: usize) -> bool {
366 if idx >= self.len {
367 return false;
368 }
369 if self.is_all_valid_sentinel() {
370 return true;
371 }
372 if let Some(ranges) = &self.invalid_ranges {
373 return !Self::invalid_ranges_contain(ranges, idx);
374 }
375 (self.words[idx / 64] >> (idx % 64)) & 1 == 1
376 }
377
378 pub fn set(&mut self, idx: usize, value: bool) {
379 if idx >= self.len {
380 return;
381 }
382 if self.is_all_valid_sentinel() {
383 if value {
384 return;
385 }
386 self.materialize_if_all_valid_sentinel();
387 } else if self.invalid_ranges.is_some() {
388 self.materialize_if_all_valid_sentinel();
389 }
390 if value {
391 self.words[idx / 64] |= 1_u64 << (idx % 64);
392 } else {
393 self.words[idx / 64] &= !(1_u64 << (idx % 64));
394 }
395 }
396
397 #[must_use]
398 pub fn count_valid(&self) -> usize {
399 if self.is_all_valid_sentinel() {
400 return self.len;
401 }
402 if let Some(ranges) = &self.invalid_ranges {
403 return self.len.saturating_sub(Self::invalid_ranges_len(ranges));
404 }
405 let full_words = self.len / 64;
406 let mut count: u32 = self.words[..full_words]
407 .iter()
408 .map(|w| w.count_ones())
409 .sum();
410 let remainder = self.len % 64;
411 if remainder > 0 && full_words < self.words.len() {
412 let mask = (1_u64 << remainder) - 1;
413 count += (self.words[full_words] & mask).count_ones();
414 }
415 count as usize
416 }
417
418 #[must_use]
419 pub fn len(&self) -> usize {
420 self.len
421 }
422
423 #[must_use]
424 pub fn is_empty(&self) -> bool {
425 self.len == 0
426 }
427
428 #[must_use]
429 pub fn and_mask(&self, other: &Self) -> Self {
430 let len = self.len.min(other.len);
431 if len == 0 {
432 return Self::all_invalid(0);
433 }
434 if self.is_all_valid_sentinel() && other.is_all_valid_sentinel() {
435 return Self::all_valid(len);
436 }
437 if self.is_all_valid_sentinel() {
438 return other.slice(0, len);
439 }
440 if other.is_all_valid_sentinel() {
441 return self.slice(0, len);
442 }
443 let left_words = self.materialized_words();
444 let right_words = other.materialized_words();
445 let word_count = len.div_ceil(64);
446 let words = left_words[..word_count]
447 .iter()
448 .zip(&right_words[..word_count])
449 .map(|(a, b)| a & b)
450 .collect();
451 Self::from_words(words, len)
452 }
453
454 #[must_use]
455 pub fn or_mask(&self, other: &Self) -> Self {
456 let len = self.len.min(other.len);
457 if len == 0 {
458 return Self::all_invalid(0);
459 }
460 if self.is_all_valid_sentinel() || other.is_all_valid_sentinel() {
461 return Self::all_valid(len);
462 }
463 let left_words = self.materialized_words();
464 let right_words = other.materialized_words();
465 let word_count = len.div_ceil(64);
466 let words = left_words[..word_count]
467 .iter()
468 .zip(&right_words[..word_count])
469 .map(|(a, b)| a | b)
470 .collect();
471 Self::from_words(words, len)
472 }
473
474 #[must_use]
475 pub fn not_mask(&self) -> Self {
476 if self.is_all_valid_sentinel() {
477 return Self::all_invalid(self.len);
478 }
479 let mut words: Vec<u64> = self.materialized_words().iter().map(|w| !w).collect();
480 let remainder = self.len % 64;
481 if remainder > 0 && !words.is_empty() {
482 let last = words.len() - 1;
483 words[last] &= (1_u64 << remainder) - 1;
484 }
485 Self::from_words(words, self.len)
486 }
487
488 pub fn bits(&self) -> impl Iterator<Item = bool> + '_ {
491 (0..self.len).map(|idx| self.get(idx))
492 }
493
494 #[doc(hidden)]
495 pub fn for_each_invalid_range(&self, mut visit: impl FnMut(usize, usize)) {
496 if self.len == 0 || self.is_all_valid_sentinel() {
497 return;
498 }
499 if let Some(ranges) = &self.invalid_ranges {
500 for &(start, len) in ranges.iter() {
501 visit(start, len);
502 }
503 return;
504 }
505
506 let mut pending_start = 0usize;
507 let mut pending_len = 0usize;
508 for word_idx in 0..self.len.div_ceil(64) {
509 let mut invalid_bits = !self.words.get(word_idx).copied().unwrap_or(0);
510 if word_idx == self.len / 64 {
511 let remainder = self.len % 64;
512 if remainder > 0 {
513 invalid_bits &= (1_u64 << remainder) - 1;
514 }
515 }
516
517 while invalid_bits != 0 {
518 let bit_start = invalid_bits.trailing_zeros() as usize;
519 let shifted = invalid_bits >> bit_start;
520 let run_len = (!shifted).trailing_zeros() as usize;
521 let start = word_idx * 64 + bit_start;
522
523 if pending_len > 0 && pending_start + pending_len == start {
524 pending_len += run_len;
525 } else {
526 if pending_len > 0 {
527 visit(pending_start, pending_len);
528 }
529 pending_start = start;
530 pending_len = run_len;
531 }
532
533 let run_mask = if run_len == 64 {
534 u64::MAX
535 } else {
536 ((1_u64 << run_len) - 1) << bit_start
537 };
538 invalid_bits &= !run_mask;
539 }
540 }
541
542 if pending_len > 0 {
543 visit(pending_start, pending_len);
544 }
545 }
546
547 #[must_use]
549 pub fn count_invalid(&self) -> usize {
550 self.len.saturating_sub(self.count_valid())
551 }
552
553 #[must_use]
555 pub fn any(&self) -> bool {
556 if self.is_all_valid_sentinel() {
557 return true;
558 }
559 self.count_valid() > 0
560 }
561
562 #[must_use]
564 pub fn all(&self) -> bool {
565 if self.is_all_valid_sentinel() {
566 return true;
567 }
568 self.count_valid() == self.len
569 }
570
571 #[must_use]
575 pub fn xor_mask(&self, other: &Self) -> Self {
576 let len = self.len.min(other.len);
577 if len == 0 {
578 return Self::all_invalid(0);
579 }
580 if self.is_all_valid_sentinel() && other.is_all_valid_sentinel() {
581 return Self::all_invalid(len);
582 }
583 if self.is_all_valid_sentinel() {
584 return other.slice(0, len).not_mask();
585 }
586 if other.is_all_valid_sentinel() {
587 return self.slice(0, len).not_mask();
588 }
589 let left_words = self.materialized_words();
590 let right_words = other.materialized_words();
591 let word_count = len.div_ceil(64);
592 let mut words: Vec<u64> = left_words[..word_count]
593 .iter()
594 .zip(&right_words[..word_count])
595 .map(|(a, b)| a ^ b)
596 .collect();
597 let remainder = len % 64;
598 if remainder > 0 && !words.is_empty() {
599 let last = words.len() - 1;
600 words[last] &= (1_u64 << remainder) - 1;
601 }
602 Self::from_words(words, len)
603 }
604
605 #[must_use]
610 pub fn slice(&self, start: usize, len: usize) -> Self {
611 if start >= self.len {
612 return Self::all_invalid(0);
613 }
614 let effective_len = len.min(self.len - start);
615 if self.is_all_valid_sentinel() {
616 return Self::all_valid(effective_len);
617 }
618 let mut out = Self::all_invalid(effective_len);
619 for i in 0..effective_len {
620 if self.get(start + i) {
621 out.set(i, true);
622 }
623 }
624 out
625 }
626
627 #[must_use]
629 pub fn concat(&self, other: &Self) -> Self {
630 let total = self.len + other.len;
631 if self.all() && other.all() {
632 return Self::all_valid(total);
633 }
634 let mut out = Self::all_invalid(total);
635 for i in 0..self.len {
636 if self.get(i) {
637 out.set(i, true);
638 }
639 }
640 for i in 0..other.len {
641 if other.get(i) {
642 out.set(self.len + i, true);
643 }
644 }
645 out
646 }
647
648 #[must_use]
650 pub fn first_valid(&self) -> Option<usize> {
651 if self.is_all_valid_sentinel() {
652 return Some(0);
653 }
654 (0..self.len).find(|&i| self.get(i))
655 }
656
657 #[must_use]
659 pub fn last_valid(&self) -> Option<usize> {
660 if self.is_all_valid_sentinel() {
661 return Some(self.len - 1);
662 }
663 (0..self.len).rev().find(|&i| self.get(i))
664 }
665}
666
667impl PartialEq for ValidityMask {
668 fn eq(&self, other: &Self) -> bool {
669 self.len == other.len && self.bits().eq(other.bits())
670 }
671}
672
673impl Serialize for ValidityMask {
674 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
675 use serde::ser::SerializeStruct;
676 let bits: Vec<bool> = self.bits().collect();
677 let mut state = serializer.serialize_struct("ValidityMask", 1)?;
678 state.serialize_field("bits", &bits)?;
679 state.end()
680 }
681}
682
683impl<'de> Deserialize<'de> for ValidityMask {
684 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
685 #[derive(Deserialize)]
686 struct Raw {
687 bits: Vec<bool>,
688 }
689 let raw = Raw::deserialize(deserializer)?;
690 let len = raw.bits.len();
691 let word_count = len.div_ceil(64);
692 let mut words = vec![0_u64; word_count];
693 for (idx, &valid) in raw.bits.iter().enumerate() {
694 if valid {
695 words[idx / 64] |= 1_u64 << (idx % 64);
696 }
697 }
698 Ok(Self::from_words(words, len))
699 }
700}
701
702#[derive(Debug, Clone, PartialEq)]
711pub enum ColumnData {
712 Float64(Arc<[f64]>),
713 Int64(Arc<[i64]>),
714 Bool(Arc<[bool]>),
715 Utf8(Vec<String>),
716 Timedelta64(Vec<i64>),
717 Datetime64(Vec<i64>),
718 Period(Vec<i64>, PeriodFreq),
722 Interval(Vec<Interval>),
723}
724
725#[derive(Debug, Clone, Copy, PartialEq, Eq)]
732#[doc(hidden)]
733pub struct Int64DenseCycleWitness {
734 pub start: i64,
735 pub period: usize,
736 pub len: usize,
737}
738
739impl Int64DenseCycleWitness {
740 #[must_use]
741 pub fn offset_count_for_key(self, key: i64) -> Option<(usize, usize)> {
742 let offset = usize::try_from(key.checked_sub(self.start)?).ok()?;
743 if offset >= self.period {
744 return None;
745 }
746 let full_cycles = self.len / self.period;
747 let tail = self.len % self.period;
748 let count = full_cycles + usize::from(offset < tail);
749 (count > 0).then_some((offset, count))
750 }
751}
752
753#[derive(Clone)]
754struct Int64Chunk {
755 data: Arc<[i64]>,
756 start: usize,
757 len: usize,
758}
759
760impl Int64Chunk {
761 fn new(data: Arc<[i64]>, start: usize, len: usize) -> Self {
762 debug_assert!(start.checked_add(len).is_some_and(|end| end <= data.len()));
763 Self { data, start, len }
764 }
765
766 fn as_slice(&self) -> &[i64] {
767 &self.data[self.start..self.start + self.len]
768 }
769}
770
771#[derive(Clone)]
772struct Float64Chunk {
773 data: Arc<[f64]>,
774 start: usize,
775 len: usize,
776}
777
778impl Float64Chunk {
779 fn new(data: Arc<[f64]>, start: usize, len: usize) -> Self {
780 debug_assert!(start.checked_add(len).is_some_and(|end| end <= data.len()));
781 Self { data, start, len }
782 }
783
784 fn as_slice(&self) -> &[f64] {
785 &self.data[self.start..self.start + self.len]
786 }
787}
788
789#[derive(Clone)]
790struct Float64DotInput {
791 data: Arc<[f64]>,
792 start: usize,
793}
794
795impl Float64DotInput {
796 fn new(data: Arc<[f64]>, start: usize, len: usize) -> Self {
797 debug_assert!(start.checked_add(len).is_some_and(|end| end <= data.len()));
798 Self { data, start }
799 }
800
801 fn value_at(&self, row: usize) -> f64 {
802 self.data[self.start + row]
803 }
804}
805
806#[derive(Debug, Clone, Copy, PartialEq, Eq)]
807#[doc(hidden)]
808pub enum PairwiseFloat64Stat {
809 Corr,
810 Cov,
811}
812
813#[derive(Clone)]
814struct Float64PairwiseStatInput {
815 data: Arc<[f64]>,
816 start: usize,
817}
818
819impl Float64PairwiseStatInput {
820 fn new(data: Arc<[f64]>, start: usize, len: usize) -> Self {
821 debug_assert!(start.checked_add(len).is_some_and(|end| end <= data.len()));
822 Self { data, start }
823 }
824
825 fn value_at(&self, row: usize) -> f64 {
826 self.data[self.start + row]
827 }
828}
829
830struct Float64PairwiseStatMatrixPlan {
831 cols: Arc<[Float64PairwiseStatInput]>,
832 row_len: usize,
833 stat: PairwiseFloat64Stat,
834 min_periods: usize,
835 matrix: OnceLock<Arc<[f64]>>,
836}
837
838impl Float64PairwiseStatMatrixPlan {
839 fn new(
840 cols: Arc<[Float64PairwiseStatInput]>,
841 row_len: usize,
842 stat: PairwiseFloat64Stat,
843 min_periods: usize,
844 ) -> Self {
845 Self {
846 cols,
847 row_len,
848 stat,
849 min_periods,
850 matrix: OnceLock::new(),
851 }
852 }
853
854 fn column_len(&self) -> usize {
855 self.cols.len()
856 }
857
858 fn materialize_column(&self, col: usize) -> Vec<f64> {
859 let n = self.column_len();
860 debug_assert!(col < n);
861 let matrix = self
862 .matrix
863 .get_or_init(|| Arc::from(self.compute_matrix_values()));
864 (0..n).map(|row| matrix[row * n + col]).collect()
865 }
866
867 #[allow(clippy::too_many_arguments)]
868 fn finalize(
869 stat: PairwiseFloat64Stat,
870 min_periods: usize,
871 count: usize,
872 sum_x: f64,
873 sum_y: f64,
874 sum_xy: f64,
875 sum_x2: f64,
876 sum_y2: f64,
877 ) -> f64 {
878 let threshold = min_periods.max(2);
879 if count < threshold {
880 return f64::NAN;
881 }
882 let n_f = count as f64;
883 let mean_x = sum_x / n_f;
884 let mean_y = sum_y / n_f;
885 let cov_xy = (sum_xy - n_f * mean_x * mean_y) / (n_f - 1.0);
886 match stat {
887 PairwiseFloat64Stat::Cov => cov_xy,
888 PairwiseFloat64Stat::Corr => {
889 let var_x = (sum_x2 - n_f * mean_x * mean_x) / (n_f - 1.0);
890 let var_y = (sum_y2 - n_f * mean_y * mean_y) / (n_f - 1.0);
891 let denom = (var_x * var_y).sqrt();
892 if denom < f64::EPSILON {
893 f64::NAN
894 } else {
895 cov_xy / denom
896 }
897 }
898 }
899 }
900
901 fn compute_matrix_values(&self) -> Vec<f64> {
902 let n = self.column_len();
903 let len = self.row_len;
904 let mut mat = vec![0.0_f64; n * n];
905 if n == 0 {
906 return mat;
907 }
908
909 let shifted_storage: Vec<Vec<f64>> = self
910 .cols
911 .iter()
912 .map(|col| {
913 let k = (0..len)
914 .map(|row| col.value_at(row))
915 .find(|x| x.is_finite())
916 .unwrap_or(0.0);
917 (0..len).map(|row| col.value_at(row) - k).collect()
918 })
919 .collect();
920 let col_data: Vec<&[f64]> = shifted_storage.iter().map(Vec::as_slice).collect();
921
922 let mut sum = vec![0.0_f64; n];
923 let mut sum2 = vec![0.0_f64; n];
924 let moment = |col: &[f64]| -> (f64, f64) {
925 let mut s = 0.0_f64;
926 let mut s2 = 0.0_f64;
927 for &x in col {
928 s += x;
929 s2 += x * x;
930 }
931 (s, s2)
932 };
933 let moment_workers = std::thread::available_parallelism()
934 .map_or(1, std::num::NonZeroUsize::get)
935 .min(64)
936 .min(n.max(1));
937 if moment_workers >= 2 && (len as u128) * (n as u128) >= (1u128 << 20) {
938 let next_col = std::sync::atomic::AtomicUsize::new(0);
939 let col_data_ref: &[&[f64]] = &col_data;
940 let parts = std::thread::scope(|scope| {
941 let mut handles = Vec::with_capacity(moment_workers);
942 for _ in 0..moment_workers {
943 let next_col = &next_col;
944 handles.push(scope.spawn(move || {
945 let mut out: Vec<(usize, f64, f64)> = Vec::new();
946 loop {
947 let idx = next_col.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
948 if idx >= col_data_ref.len() {
949 break;
950 }
951 let (s, s2) = moment(col_data_ref[idx]);
952 out.push((idx, s, s2));
953 }
954 out
955 }));
956 }
957 let mut all = Vec::with_capacity(handles.len());
958 for handle in handles {
959 all.push(handle.join().unwrap_or_default());
960 }
961 all
962 });
963 for part in parts {
964 for (idx, s, s2) in part {
965 sum[idx] = s;
966 sum2[idx] = s2;
967 }
968 }
969 } else {
970 for (idx, col) in col_data.iter().enumerate() {
971 let (s, s2) = moment(col);
972 sum[idx] = s;
973 sum2[idx] = s2;
974 }
975 }
976
977 const BT: usize = 4;
978 const BAND_COUNT: usize = 64;
979 let mut gram = vec![0.0_f64; n * n];
980 let big_enough = (len as u128) * (n as u128) * (n as u128) >= (1u128 << 23);
981 let band_count = BAND_COUNT.min(len);
982 if band_count >= 2 && big_enough {
983 let band = len.div_ceil(band_count);
984 let bands: Vec<(usize, usize)> = (0..band_count)
985 .map(|b| (b * band, ((b + 1) * band).min(len)))
986 .filter(|&(a, b)| a < b)
987 .collect();
988 let worker_count = std::thread::available_parallelism()
989 .map_or(1, std::num::NonZeroUsize::get)
990 .min(64)
991 .min(bands.len());
992 let next_band = std::sync::atomic::AtomicUsize::new(0);
993 let bands_ref: &[(usize, usize)] = &bands;
994 let cols_ref: &[&[f64]] = &col_data;
995 let mut partials: Vec<Vec<f64>> = Vec::new();
996 std::thread::scope(|scope| {
997 let mut handles = Vec::with_capacity(worker_count);
998 for _ in 0..worker_count {
999 let next_band = &next_band;
1000 handles.push(scope.spawn(move || {
1001 let mut out: Vec<(usize, Vec<f64>)> = Vec::new();
1002 loop {
1003 let b = next_band.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1004 if b >= bands_ref.len() {
1005 break;
1006 }
1007 let (r0, r1) = bands_ref[b];
1008 let mut panel = vec![0.0_f64; (r1 - r0) * BT];
1009 let mut gram_out = vec![0.0_f64; n * n];
1010 pairwise_stat_gram_partial_rows(
1011 cols_ref,
1012 n,
1013 r0,
1014 r1,
1015 &mut panel,
1016 &mut gram_out,
1017 );
1018 out.push((b, gram_out));
1019 }
1020 out
1021 }));
1022 }
1023 let mut indexed: Vec<(usize, Vec<f64>)> = Vec::with_capacity(bands.len());
1024 for handle in handles {
1025 if let Ok(mut part) = handle.join() {
1026 indexed.append(&mut part);
1027 }
1028 }
1029 indexed.sort_by_key(|(b, _)| *b);
1030 partials = indexed.into_iter().map(|(_, g)| g).collect();
1031 });
1032 for partial in &partials {
1033 if partial.len() != n * n {
1034 continue;
1035 }
1036 for j in 0..n {
1037 for i in 0..=j {
1038 gram[i * n + j] += partial[i * n + j];
1039 }
1040 }
1041 }
1042 } else {
1043 let mut panel = vec![0.0_f64; len.max(1) * BT];
1044 pairwise_stat_gram_partial_rows(&col_data, n, 0, len, &mut panel, &mut gram);
1045 }
1046
1047 for j in 0..n {
1048 for i in 0..=j {
1049 let g = gram[i * n + j];
1050 mat[i * n + j] = Self::finalize(
1051 self.stat,
1052 self.min_periods,
1053 len,
1054 sum[i],
1055 sum[j],
1056 g,
1057 sum2[i],
1058 sum2[j],
1059 );
1060 if i != j {
1061 mat[j * n + i] = Self::finalize(
1062 self.stat,
1063 self.min_periods,
1064 len,
1065 sum[j],
1066 sum[i],
1067 g,
1068 sum2[j],
1069 sum2[i],
1070 );
1071 }
1072 }
1073 }
1074 mat
1075 }
1076}
1077
1078fn pairwise_stat_gram_partial_rows(
1079 col_data: &[&[f64]],
1080 n: usize,
1081 r0: usize,
1082 r1: usize,
1083 panel: &mut [f64],
1084 gram_out: &mut [f64],
1085) {
1086 const BT: usize = 4;
1087 let rows = r1 - r0;
1088 let mut tj = 0;
1089 while tj < n {
1090 let bj = BT.min(n - tj);
1091 for dj in 0..bj {
1092 let cj = col_data[tj + dj];
1093 for lr in 0..rows {
1094 panel[lr * BT + dj] = cj[r0 + lr];
1095 }
1096 }
1097 let mut ti = 0;
1098 while ti <= tj {
1099 let bi = BT.min(n - ti);
1100 let mut acc = [[0.0_f64; BT]; BT];
1101 if bi == BT && bj == BT {
1102 for lr in 0..rows {
1103 let pr = &panel[lr * BT..lr * BT + BT];
1104 for (di, acc_row) in acc.iter_mut().enumerate() {
1105 let av = col_data[ti + di][r0 + lr];
1106 for dj in 0..BT {
1107 acc_row[dj] += av * pr[dj];
1108 }
1109 }
1110 }
1111 } else {
1112 for lr in 0..rows {
1113 for (di, acc_row) in acc.iter_mut().enumerate().take(bi) {
1114 let av = col_data[ti + di][r0 + lr];
1115 for (dj, slot) in acc_row.iter_mut().enumerate().take(bj) {
1116 *slot += av * panel[lr * BT + dj];
1117 }
1118 }
1119 }
1120 }
1121 for (di, acc_row) in acc.iter().enumerate().take(bi) {
1122 let gi = ti + di;
1123 for (dj, slot) in acc_row.iter().enumerate().take(bj) {
1124 let gj = tj + dj;
1125 if gi <= gj {
1126 gram_out[gi * n + gj] += *slot;
1127 }
1128 }
1129 }
1130 ti += BT;
1131 }
1132 tj += BT;
1133 }
1134}
1135
1136fn certify_int64_dense_cycle(data: &[i64]) -> Option<Int64DenseCycleWitness> {
1137 let (&start, rest) = data.split_first()?;
1138 let mut period = None;
1139 for (idx, &value) in rest.iter().enumerate() {
1140 let row = idx + 1;
1141 if value == start {
1142 period = Some(row);
1143 break;
1144 }
1145 let row_i64 = i64::try_from(row).ok()?;
1146 if value != start.checked_add(row_i64)? {
1147 return None;
1148 }
1149 }
1150 let period = period.unwrap_or(data.len());
1151 if period == 0 {
1152 return None;
1153 }
1154 let last_offset = i64::try_from(period.checked_sub(1)?).ok()?;
1155 start.checked_add(last_offset)?;
1156 for (row, &value) in data.iter().enumerate() {
1157 let offset = i64::try_from(row % period).ok()?;
1158 if value != start.checked_add(offset)? {
1159 return None;
1160 }
1161 }
1162 Some(Int64DenseCycleWitness {
1163 start,
1164 period,
1165 len: data.len(),
1166 })
1167}
1168
1169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1175#[doc(hidden)]
1176pub struct BoolAffineSelectionWitness {
1177 pub start: usize,
1178 pub step: usize,
1179 pub len: usize,
1180}
1181
1182#[derive(Default)]
1183struct BoolAffineSelectionBuilder {
1184 first: usize,
1185 previous: usize,
1186 step: usize,
1187 len: usize,
1188 is_affine: bool,
1189}
1190
1191impl BoolAffineSelectionBuilder {
1192 fn push(&mut self, position: usize) {
1193 match self.len {
1194 0 => {
1195 self.first = position;
1196 self.previous = position;
1197 self.is_affine = true;
1198 }
1199 1 => {
1200 self.step = position - self.first;
1201 self.is_affine = self.step != 0;
1202 self.previous = position;
1203 }
1204 _ => {
1205 if position - self.previous != self.step {
1206 self.is_affine = false;
1207 }
1208 self.previous = position;
1209 }
1210 }
1211 self.len += 1;
1212 }
1213
1214 fn finish(self) -> Option<BoolAffineSelectionWitness> {
1215 match self.len {
1216 0 => None,
1217 1 => Some(BoolAffineSelectionWitness {
1218 start: self.first,
1219 step: 1,
1220 len: self.len,
1221 }),
1222 _ if self.is_affine => Some(BoolAffineSelectionWitness {
1223 start: self.first,
1224 step: self.step,
1225 len: self.len,
1226 }),
1227 _ => None,
1228 }
1229 }
1230}
1231
1232fn certify_bool_affine_selection(data: &[bool]) -> Option<BoolAffineSelectionWitness> {
1233 let mut builder = BoolAffineSelectionBuilder::default();
1234 for (idx, keep) in data.iter().copied().enumerate() {
1235 if keep {
1236 builder.push(idx);
1237 if !builder.is_affine {
1238 return None;
1239 }
1240 }
1241 }
1242 builder.finish()
1243}
1244
1245impl ColumnData {
1246 #[must_use]
1252 pub fn from_scalars(values: &[Scalar], dtype: DType) -> Self {
1253 match dtype {
1254 DType::Float64 => {
1255 let data: Vec<f64> = values
1256 .iter()
1257 .map(|v| match v {
1258 Scalar::Float64(f) => *f,
1259 Scalar::Int64(i) => *i as f64,
1260 Scalar::Bool(true) => 1.0,
1261 Scalar::Bool(false) => 0.0,
1262 _ => 0.0, })
1264 .collect();
1265 Self::Float64(Arc::from(data))
1266 }
1267 DType::Int64 | DType::Int64Nullable => {
1268 let data: Vec<i64> = values
1269 .iter()
1270 .map(|v| match v {
1271 Scalar::Int64(i) => *i,
1272 Scalar::Bool(b) => i64::from(*b),
1273 _ => 0, })
1275 .collect();
1276 Self::Int64(Arc::from(data))
1277 }
1278 DType::Categorical => {
1279 let data: Vec<i64> = values
1280 .iter()
1281 .map(|v| match v {
1282 Scalar::Int64(i) => *i,
1283 _ => -1,
1284 })
1285 .collect();
1286 Self::Int64(Arc::from(data))
1287 }
1288 DType::Bool | DType::BoolNullable => {
1289 let data: Vec<bool> = values
1290 .iter()
1291 .map(|v| match v {
1292 Scalar::Bool(b) => *b,
1293 _ => false,
1294 })
1295 .collect();
1296 Self::Bool(Arc::from(data))
1297 }
1298 DType::Utf8 => {
1299 let data: Vec<String> = values
1300 .iter()
1301 .map(|v| match v {
1302 Scalar::Utf8(s) => s.clone(),
1303 _ => String::new(),
1304 })
1305 .collect();
1306 Self::Utf8(data)
1307 }
1308 DType::Null => Self::Float64(Arc::from(vec![0.0; values.len()])),
1309 DType::Sparse => Self::Utf8(vec![String::new(); values.len()]),
1310 DType::Timedelta64 => {
1311 let data: Vec<i64> = values
1312 .iter()
1313 .map(|v| match v {
1314 Scalar::Timedelta64(n) => *n,
1315 Scalar::Int64(i) => *i,
1316 _ => Timedelta::NAT,
1317 })
1318 .collect();
1319 Self::Timedelta64(data)
1320 }
1321 DType::Datetime64 => {
1322 let data: Vec<i64> = values
1323 .iter()
1324 .map(|v| match v {
1325 Scalar::Datetime64(n) => *n,
1326 Scalar::Int64(i) => *i,
1327 _ => Timestamp::NAT,
1328 })
1329 .collect();
1330 Self::Datetime64(data)
1331 }
1332 DType::Period => {
1333 let freq = values
1336 .iter()
1337 .find_map(|v| match v {
1338 Scalar::Period(p) if p.ordinal != i64::MIN => Some(p.freq),
1339 _ => None,
1340 })
1341 .unwrap_or(PeriodFreq::Daily);
1342 let data: Vec<i64> = values
1343 .iter()
1344 .map(|v| match v {
1345 Scalar::Period(p) => p.ordinal,
1346 Scalar::Int64(i) => *i,
1347 _ => i64::MIN, })
1349 .collect();
1350 Self::Period(data, freq)
1351 }
1352 DType::Interval => {
1353 let data: Vec<Interval> = values
1354 .iter()
1355 .map(|v| match v {
1356 Scalar::Interval(interval) => *interval,
1357 _ => Interval::new(0.0, 0.0, IntervalClosed::Right),
1358 })
1359 .collect();
1360 Self::Interval(data)
1361 }
1362 }
1363 }
1364
1365 #[must_use]
1367 pub fn to_scalars(&self, dtype: DType, validity: &ValidityMask) -> Vec<Scalar> {
1368 match self {
1369 Self::Float64(data) => data
1370 .iter()
1371 .enumerate()
1372 .map(|(i, v)| {
1373 if !validity.get(i) {
1374 Scalar::missing_for_dtype(dtype)
1375 } else {
1376 Scalar::Float64(*v)
1377 }
1378 })
1379 .collect(),
1380 Self::Int64(data) => data
1381 .iter()
1382 .enumerate()
1383 .map(|(i, v)| {
1384 if !validity.get(i) {
1385 Scalar::missing_for_dtype(dtype)
1386 } else {
1387 Scalar::Int64(*v)
1388 }
1389 })
1390 .collect(),
1391 Self::Bool(data) => data
1392 .iter()
1393 .enumerate()
1394 .map(|(i, v)| {
1395 if !validity.get(i) {
1396 Scalar::missing_for_dtype(dtype)
1397 } else {
1398 Scalar::Bool(*v)
1399 }
1400 })
1401 .collect(),
1402 Self::Utf8(data) => data
1403 .iter()
1404 .enumerate()
1405 .map(|(i, v)| {
1406 if !validity.get(i) {
1407 Scalar::missing_for_dtype(dtype)
1408 } else {
1409 Scalar::Utf8(v.clone())
1410 }
1411 })
1412 .collect(),
1413 Self::Timedelta64(data) => data
1414 .iter()
1415 .enumerate()
1416 .map(|(i, v)| {
1417 if !validity.get(i) || *v == Timedelta::NAT {
1418 Scalar::Timedelta64(Timedelta::NAT)
1419 } else {
1420 Scalar::Timedelta64(*v)
1421 }
1422 })
1423 .collect(),
1424 Self::Datetime64(data) => data
1425 .iter()
1426 .enumerate()
1427 .map(|(i, v)| {
1428 if !validity.get(i) || *v == Timestamp::NAT {
1429 Scalar::Datetime64(Timestamp::NAT)
1430 } else {
1431 Scalar::Datetime64(*v)
1432 }
1433 })
1434 .collect(),
1435 Self::Period(data, freq) => data
1436 .iter()
1437 .enumerate()
1438 .map(|(i, v)| {
1439 if !validity.get(i) || *v == i64::MIN {
1440 Scalar::Period(Period::new(i64::MIN, *freq))
1441 } else {
1442 Scalar::Period(Period::new(*v, *freq))
1443 }
1444 })
1445 .collect(),
1446 Self::Interval(data) => data
1447 .iter()
1448 .enumerate()
1449 .map(|(i, v)| {
1450 if !validity.get(i) {
1451 Scalar::missing_for_dtype(dtype)
1452 } else {
1453 Scalar::Interval(*v)
1454 }
1455 })
1456 .collect(),
1457 }
1458 }
1459
1460 #[must_use]
1461 pub fn len(&self) -> usize {
1462 match self {
1463 Self::Float64(d) => d.len(),
1464 Self::Int64(d) => d.len(),
1465 Self::Bool(d) => d.len(),
1466 Self::Utf8(d) => d.len(),
1467 Self::Timedelta64(d) => d.len(),
1468 Self::Datetime64(d) => d.len(),
1469 Self::Period(d, _) => d.len(),
1470 Self::Interval(d) => d.len(),
1471 }
1472 }
1473
1474 #[must_use]
1475 pub fn is_empty(&self) -> bool {
1476 self.len() == 0
1477 }
1478}
1479
1480fn scalar_compare(left: &Scalar, right: &Scalar, op: ComparisonOp) -> Result<bool, ColumnError> {
1485 let left_dtype = left.dtype();
1487 let right_dtype = right.dtype();
1488 if left_dtype != right_dtype
1489 && let Ok(common) = fp_types::common_dtype(left_dtype, right_dtype)
1490 && common == DType::Int64
1491 {
1492 let l_cast = fp_types::cast_scalar(left, common)?;
1493 let r_cast = fp_types::cast_scalar(right, common)?;
1494 if let (Scalar::Int64(a), Scalar::Int64(b)) = (&l_cast, &r_cast) {
1496 return Ok(match op {
1497 ComparisonOp::Gt => a > b,
1498 ComparisonOp::Lt => a < b,
1499 ComparisonOp::Eq => a == b,
1500 ComparisonOp::Ne => a != b,
1501 ComparisonOp::Ge => a >= b,
1502 ComparisonOp::Le => a <= b,
1503 });
1504 }
1505 }
1506
1507 if let (Scalar::Utf8(a), Scalar::Utf8(b)) = (left, right) {
1509 return Ok(match op {
1510 ComparisonOp::Gt => a > b,
1511 ComparisonOp::Lt => a < b,
1512 ComparisonOp::Eq => a == b,
1513 ComparisonOp::Ne => a != b,
1514 ComparisonOp::Ge => a >= b,
1515 ComparisonOp::Le => a <= b,
1516 });
1517 }
1518
1519 if let (Scalar::Bool(a), Scalar::Bool(b)) = (left, right) {
1521 return Ok(match op {
1522 ComparisonOp::Gt => *a && !*b,
1523 ComparisonOp::Lt => !*a && *b,
1524 ComparisonOp::Eq => a == b,
1525 ComparisonOp::Ne => a != b,
1526 ComparisonOp::Ge => *a >= *b,
1527 ComparisonOp::Le => *a <= *b,
1528 });
1529 }
1530
1531 if let (Scalar::Int64(a), Scalar::Int64(b)) = (left, right) {
1533 return Ok(match op {
1534 ComparisonOp::Gt => a > b,
1535 ComparisonOp::Lt => a < b,
1536 ComparisonOp::Eq => a == b,
1537 ComparisonOp::Ne => a != b,
1538 ComparisonOp::Ge => a >= b,
1539 ComparisonOp::Le => a <= b,
1540 });
1541 }
1542
1543 let lhs = left.to_f64()?;
1545 let rhs = right.to_f64()?;
1546
1547 Ok(match op {
1548 ComparisonOp::Gt => lhs > rhs,
1549 ComparisonOp::Lt => lhs < rhs,
1550 ComparisonOp::Eq => lhs == rhs,
1551 ComparisonOp::Ne => lhs != rhs,
1552 ComparisonOp::Ge => lhs >= rhs,
1553 ComparisonOp::Le => lhs <= rhs,
1554 })
1555}
1556
1557fn vectorized_binary_f64(
1563 left: &[f64],
1564 right: &[f64],
1565 left_validity: &ValidityMask,
1566 right_validity: &ValidityMask,
1567 op: ArithmeticOp,
1568) -> (Vec<f64>, ValidityMask) {
1569 let combined = left_validity.and_mask(right_validity);
1570
1571 let apply = binary_f64_apply(op);
1573
1574 let out: Vec<f64> = left
1575 .iter()
1576 .zip(right.iter())
1577 .enumerate()
1578 .map(|(i, (&l, &r))| {
1579 if combined.get(i) {
1580 apply(l, r)
1581 } else {
1582 0.0 }
1584 })
1585 .collect();
1586
1587 (out, combined)
1588}
1589
1590fn binary_f64_apply(op: ArithmeticOp) -> fn(f64, f64) -> f64 {
1591 match op {
1592 ArithmeticOp::Add => |a, b| a + b,
1593 ArithmeticOp::Sub => |a, b| a - b,
1594 ArithmeticOp::Mul => |a, b| a * b,
1595 ArithmeticOp::Div => |a, b| a / b,
1596 ArithmeticOp::Mod => python_mod_f64,
1597 ArithmeticOp::Pow => |a, b| a.powf(b),
1598 ArithmeticOp::FloorDiv => python_floor_div_f64,
1599 }
1600}
1601
1602#[inline]
1616fn apply_f64_slices_nan_tracked(op: ArithmeticOp, a: &[f64], b: &[f64]) -> (Vec<f64>, bool, bool) {
1617 debug_assert_eq!(a.len(), b.len());
1618 const PARALLEL_MIN_LEN: usize = 1 << 20;
1619 const PARALLEL_MAX_CHUNKS: usize = 8;
1620
1621 let mut data = vec![0.0_f64; a.len()];
1622
1623 let worker_count = std::thread::available_parallelism()
1624 .map_or(1, usize::from)
1625 .min(PARALLEL_MAX_CHUNKS)
1626 .min(a.len().max(1));
1627 if a.len() >= PARALLEL_MIN_LEN && worker_count >= 2 {
1628 let chunk_len = a.len().div_ceil(worker_count);
1629 let mut chunks = Vec::with_capacity(worker_count);
1630 let mut rest = data.as_mut_slice();
1631 let mut start = 0usize;
1632 while start < a.len() {
1633 let end = (start + chunk_len).min(a.len());
1634 let (chunk, tail) = rest.split_at_mut(end - start);
1635 chunks.push((start, chunk));
1636 rest = tail;
1637 start = end;
1638 }
1639
1640 let (input_nan, output_nan) = std::thread::scope(|scope| {
1641 let mut handles = Vec::with_capacity(chunks.len());
1642 for (start, chunk) in chunks {
1643 let end = start + chunk.len();
1644 let a = &a[start..end];
1645 let b = &b[start..end];
1646 handles
1647 .push(scope.spawn(move || apply_f64_slices_nan_tracked_into(op, a, b, chunk)));
1648 }
1649
1650 let mut input_nan = false;
1651 let mut output_nan = false;
1652 for handle in handles {
1653 let (chunk_input_nan, chunk_output_nan) = match handle.join() {
1654 Ok(result) => result,
1655 Err(payload) => std::panic::resume_unwind(payload),
1656 };
1657 input_nan |= chunk_input_nan;
1658 output_nan |= chunk_output_nan;
1659 }
1660 (input_nan, output_nan)
1661 });
1662
1663 return (data, input_nan, output_nan);
1664 }
1665
1666 let (input_nan, output_nan) = apply_f64_slices_nan_tracked_into(op, a, b, &mut data);
1667 (data, input_nan, output_nan)
1668}
1669
1670#[inline]
1671fn apply_f64_slices_nan_tracked_into(
1672 op: ArithmeticOp,
1673 a: &[f64],
1674 b: &[f64],
1675 data: &mut [f64],
1676) -> (bool, bool) {
1677 debug_assert_eq!(a.len(), b.len());
1678 debug_assert_eq!(a.len(), data.len());
1679 let mut input_nan = false;
1680 let mut output_nan = false;
1681
1682 macro_rules! sweep {
1683 ($f:expr) => {{
1684 for ((x, y), d) in a.iter().zip(b).zip(data.iter_mut()) {
1685 let r = $f(*x, *y);
1686 input_nan |= x.is_nan() | y.is_nan();
1687 output_nan |= r.is_nan();
1688 *d = r;
1689 }
1690 }};
1691 }
1692
1693 match op {
1694 ArithmeticOp::Add => sweep!(|x: f64, y: f64| x + y),
1695 ArithmeticOp::Sub => sweep!(|x: f64, y: f64| x - y),
1696 ArithmeticOp::Mul => sweep!(|x: f64, y: f64| x * y),
1697 ArithmeticOp::Div => sweep!(|x: f64, y: f64| x / y),
1698 ArithmeticOp::Mod => sweep!(python_mod_f64),
1699 ArithmeticOp::Pow => sweep!(|x: f64, y: f64| x.powf(y)),
1700 ArithmeticOp::FloorDiv => sweep!(python_floor_div_f64),
1701 }
1702
1703 (input_nan, output_nan)
1704}
1705
1706fn unit_range_len(start: i64, end: i64) -> Option<usize> {
1707 usize::try_from(end.checked_sub(start)?.checked_add(1)?).ok()
1708}
1709
1710fn python_mod_f64(lhs: f64, rhs: f64) -> f64 {
1711 if lhs.is_nan() || rhs.is_nan() {
1712 return f64::NAN;
1713 }
1714
1715 if rhs.is_infinite() {
1716 if lhs.is_infinite() {
1717 return f64::NAN;
1718 }
1719 if lhs == 0.0 {
1720 return 0.0_f64.copysign(rhs);
1721 }
1722 if lhs.is_sign_positive() == rhs.is_sign_positive() {
1723 lhs
1724 } else {
1725 rhs
1726 }
1727 } else {
1728 lhs - python_floor_div_f64(lhs, rhs) * rhs
1729 }
1730}
1731
1732fn python_floor_div_f64(lhs: f64, rhs: f64) -> f64 {
1733 if lhs.is_nan() || rhs.is_nan() {
1734 return f64::NAN;
1735 }
1736
1737 if rhs.is_infinite() {
1738 if lhs.is_infinite() {
1739 return f64::NAN;
1740 }
1741 if lhs == 0.0 {
1742 return (lhs / rhs).floor();
1743 }
1744 if lhs.is_sign_positive() == rhs.is_sign_positive() {
1745 0.0
1746 } else {
1747 -1.0
1748 }
1749 } else if lhs.is_infinite() && rhs != 0.0 {
1750 f64::NAN
1751 } else {
1752 (lhs / rhs).floor()
1753 }
1754}
1755
1756fn python_floor_div_i64(lhs: i64, rhs: i64) -> i64 {
1757 debug_assert_ne!(rhs, 0);
1758 if lhs == i64::MIN && rhs == -1 {
1759 return i64::MIN;
1760 }
1761
1762 let quotient = lhs / rhs;
1763 let remainder = lhs % rhs;
1764 if remainder != 0 && ((remainder > 0) != (rhs > 0)) {
1765 quotient - 1
1766 } else {
1767 quotient
1768 }
1769}
1770
1771fn python_mod_i64(lhs: i64, rhs: i64) -> i64 {
1772 debug_assert_ne!(rhs, 0);
1773 if lhs == i64::MIN && rhs == -1 {
1774 return 0;
1775 }
1776
1777 let quotient = i128::from(python_floor_div_i64(lhs, rhs));
1778 let remainder = i128::from(lhs) - quotient * i128::from(rhs);
1779 let Ok(value) = i64::try_from(remainder) else {
1780 return 0;
1781 };
1782 value
1783}
1784
1785fn vectorized_binary_i64(
1790 left: &[i64],
1791 right: &[i64],
1792 left_validity: &ValidityMask,
1793 right_validity: &ValidityMask,
1794 op: ArithmeticOp,
1795) -> Option<(Vec<i64>, ValidityMask)> {
1796 let combined = left_validity.and_mask(right_validity);
1797
1798 if matches!(op, ArithmeticOp::Div | ArithmeticOp::Pow) {
1800 return None;
1801 }
1802
1803 if matches!(op, ArithmeticOp::Mod | ArithmeticOp::FloorDiv) {
1813 let has_zero_divisor = right
1814 .iter()
1815 .enumerate()
1816 .any(|(i, &r)| right_validity.get(i) && r == 0);
1817 if has_zero_divisor {
1818 return None;
1819 }
1820 }
1821
1822 let apply: fn(i64, i64) -> i64 = match op {
1823 ArithmeticOp::Add => |a, b| a.wrapping_add(b),
1824 ArithmeticOp::Sub => |a, b| a.wrapping_sub(b),
1825 ArithmeticOp::Mul => |a, b| a.wrapping_mul(b),
1826 ArithmeticOp::Mod => python_mod_i64,
1827 ArithmeticOp::FloorDiv => python_floor_div_i64,
1828 ArithmeticOp::Div | ArithmeticOp::Pow => unreachable!("handled by early return above"),
1829 };
1830
1831 let out: Vec<i64> = left
1832 .iter()
1833 .zip(right.iter())
1834 .enumerate()
1835 .map(|(i, (&l, &r))| {
1836 if combined.get(i) {
1837 apply(l, r)
1838 } else {
1839 0 }
1841 })
1842 .collect();
1843
1844 Some((out, combined))
1845}
1846
1847enum ScalarValues {
1848 Eager(Arc<[Scalar]>),
1860 LazyAllValidInt64 {
1861 data: Arc<[i64]>,
1862 dense_cycle: OnceLock<Option<Int64DenseCycleWitness>>,
1863 values: OnceLock<Vec<Scalar>>,
1864 },
1865 LazyAllValidInt64Chunks {
1866 chunks: Arc<[Int64Chunk]>,
1867 len: usize,
1868 data: OnceLock<Vec<i64>>,
1869 dense_cycle: OnceLock<Option<Int64DenseCycleWitness>>,
1870 values: OnceLock<Vec<Scalar>>,
1871 },
1872 LazyAllValidDatetime64 {
1877 data: Arc<[i64]>,
1878 values: OnceLock<Vec<Scalar>>,
1879 },
1880 LazyAllValidFloat64 {
1881 data: Arc<[f64]>,
1882 all_finite: OnceLock<bool>,
1883 values: OnceLock<Vec<Scalar>>,
1884 },
1885 LazyAllValidFloat64Chunks {
1886 chunks: Arc<[Float64Chunk]>,
1887 len: usize,
1888 data: OnceLock<Vec<f64>>,
1889 all_finite: OnceLock<bool>,
1890 values: OnceLock<Vec<Scalar>>,
1891 },
1892 LazyAllValidFloat64Slice {
1899 data: Arc<[f64]>,
1900 start: usize,
1901 len: usize,
1902 all_finite: OnceLock<bool>,
1903 values: OnceLock<Vec<Scalar>>,
1904 },
1905 LazyAllValidFloat64Dot {
1912 a_cols: Arc<[Float64DotInput]>,
1913 b_col: Arc<[f64]>,
1914 len: usize,
1915 data: OnceLock<Vec<f64>>,
1916 values: OnceLock<Vec<Scalar>>,
1917 },
1918 LazyAllValidFloat64PairwiseStatMatrixColumn {
1925 plan: Arc<Float64PairwiseStatMatrixPlan>,
1926 col: usize,
1927 data: OnceLock<Vec<f64>>,
1928 values: OnceLock<Vec<Scalar>>,
1929 },
1930 LazyCombineFirstFloat64 {
1938 left: Arc<[f64]>,
1939 right: Arc<[f64]>,
1940 left_validity_words: Arc<[u64]>,
1941 len: usize,
1942 data: OnceLock<Vec<f64>>,
1943 values: OnceLock<Vec<Scalar>>,
1944 },
1945 LazyStridedFloat64 {
1953 data: Arc<[f64]>,
1954 start: usize,
1955 step: usize,
1956 len: usize,
1957 expanded: OnceLock<Vec<f64>>,
1958 values: OnceLock<Vec<Scalar>>,
1959 },
1960 LazyNullableFloat64 {
1961 data: Vec<f64>,
1962 validity: ValidityMask,
1963 values: OnceLock<Vec<Scalar>>,
1964 },
1965 LazyNullableInt64 {
1971 data: Vec<i64>,
1972 validity: ValidityMask,
1973 values: OnceLock<Vec<Scalar>>,
1974 },
1975 LazyNullableBool {
1982 data: Vec<bool>,
1983 validity: ValidityMask,
1984 values: OnceLock<Vec<Scalar>>,
1985 },
1986 LazyAllValidBool {
1987 data: Arc<[bool]>,
1988 affine_selection: OnceLock<Option<BoolAffineSelectionWitness>>,
1989 values: OnceLock<Vec<Scalar>>,
1990 },
1991 LazyContiguousUtf8 {
2005 bytes: Arc<[u8]>,
2006 offsets: Arc<[usize]>,
2007 strictly_increasing: OnceLock<bool>,
2008 fixed_width: OnceLock<Option<usize>>,
2009 lower_hex_sequence: OnceLock<Option<Utf8LowerHexSequence>>,
2010 factorize_default: OnceLock<Utf8FactorizeDefaultWitness>,
2011 values: OnceLock<Vec<Scalar>>,
2012 },
2013 LazyLowerHexSequenceUtf8 {
2021 prefix: Arc<[u8]>,
2022 start: u64,
2023 len: usize,
2024 hex_width: usize,
2025 buffers: OnceLock<Utf8ArcBuffers>,
2026 values: OnceLock<Vec<Scalar>>,
2027 },
2028 LazyNullableUtf8 {
2038 bytes: Arc<[u8]>,
2039 offsets: Arc<[usize]>,
2040 validity: ValidityMask,
2041 values: OnceLock<Vec<Scalar>>,
2042 },
2043 LazyGatherUtf8 {
2056 source: Arc<[Scalar]>,
2057 positions: Arc<[usize]>,
2058 values: OnceLock<Vec<Scalar>>,
2059 },
2060 LazyNullableUtf8Range {
2067 source: Arc<[Scalar]>,
2068 null_prefix: usize,
2069 source_start: usize,
2070 source_len: usize,
2071 null_suffix: usize,
2072 values: OnceLock<Vec<Scalar>>,
2073 },
2074 LazyRepeatRunsInt64 {
2081 runs: Vec<(i64, usize)>,
2082 total_len: usize,
2083 data: OnceLock<Vec<i64>>,
2084 values: OnceLock<Vec<Scalar>>,
2085 },
2086 LazyRepeatValuesInt64 {
2090 run_values: Vec<i64>,
2091 run_lens: Arc<[usize]>,
2092 total_len: usize,
2093 data: OnceLock<Vec<i64>>,
2094 values: OnceLock<Vec<Scalar>>,
2095 },
2096 LazyRepeatedSlicesInt64 {
2101 data: Vec<i64>,
2102 segments: Arc<[(usize, usize)]>,
2103 total_len: usize,
2104 expanded: OnceLock<Vec<i64>>,
2105 values: OnceLock<Vec<Scalar>>,
2106 },
2107 LazyRepeatValuesFloat64 {
2114 run_values: Vec<f64>,
2115 run_lens: Arc<[usize]>,
2116 total_len: usize,
2117 values: OnceLock<Vec<Scalar>>,
2118 },
2119 LazyRepeatedSlicesFloat64 {
2125 data: Vec<f64>,
2126 segments: Arc<[(usize, usize)]>,
2127 total_len: usize,
2128 expanded: OnceLock<Vec<f64>>,
2129 values: OnceLock<Vec<Scalar>>,
2130 },
2131 LazyNullableRepeatedSlicesInt64 {
2139 data: Vec<i64>,
2140 segments: Arc<[(usize, usize)]>,
2141 total_len: usize,
2142 values: OnceLock<Vec<Scalar>>,
2143 },
2144 LazyNullableRepeatedSlicesFloat64 {
2148 data: Vec<f64>,
2149 segments: Arc<[(usize, usize)]>,
2150 total_len: usize,
2151 values: OnceLock<Vec<Scalar>>,
2152 },
2153 LazyNullableRepeatValuesFloat64 {
2161 run_values: Vec<f64>,
2162 run_valid: Arc<[bool]>,
2163 run_lens: Arc<[usize]>,
2164 total_len: usize,
2165 values: OnceLock<Vec<Scalar>>,
2166 },
2167 LazyNullableRepeatedPositionsI64AsFloat64 {
2171 source: Arc<[i64]>,
2172 positions: Arc<[usize]>,
2173 segments: Arc<[(usize, usize)]>,
2174 total_len: usize,
2175 values: OnceLock<Vec<Scalar>>,
2176 },
2177 LazyNullableDenseCycleRightI64AsFloat64 {
2182 source: Arc<[i64]>,
2183 left_witness: Int64DenseCycleWitness,
2184 right_witness: Int64DenseCycleWitness,
2185 min_key: i64,
2186 span: usize,
2187 total_len: usize,
2188 values: OnceLock<Vec<Scalar>>,
2189 },
2190 LazyNullableDenseCycleLeftI64AsFloat64 {
2195 source: Arc<[i64]>,
2196 left_witness: Int64DenseCycleWitness,
2197 right_witness: Int64DenseCycleWitness,
2198 min_key: i64,
2199 span: usize,
2200 total_len: usize,
2201 values: OnceLock<Vec<Scalar>>,
2202 },
2203 LazyDenseCycleProbeRepeatInt64 {
2207 source: Arc<[i64]>,
2208 probe_witness: Int64DenseCycleWitness,
2209 build_witness: Int64DenseCycleWitness,
2210 total_len: usize,
2211 data: OnceLock<Vec<i64>>,
2212 values: OnceLock<Vec<Scalar>>,
2213 },
2214 LazyLeftJoinDenseCycleLeftInt64 {
2218 source: Arc<[i64]>,
2219 left_witness: Int64DenseCycleWitness,
2220 right_witness: Int64DenseCycleWitness,
2221 total_len: usize,
2222 data: OnceLock<Vec<i64>>,
2223 values: OnceLock<Vec<Scalar>>,
2224 },
2225 LazyNullableDenseCycleProbeBuildInt64 {
2229 source: Arc<[i64]>,
2230 probe_witness: Int64DenseCycleWitness,
2231 build_witness: Int64DenseCycleWitness,
2232 total_len: usize,
2233 values: OnceLock<Vec<Scalar>>,
2234 },
2235 LazyLeftJoinDenseCycleRightInt64 {
2239 source: Arc<[i64]>,
2240 left_witness: Int64DenseCycleWitness,
2241 right_witness: Int64DenseCycleWitness,
2242 total_len: usize,
2243 data: OnceLock<Vec<i64>>,
2244 values: OnceLock<Vec<Scalar>>,
2245 },
2246 LazyNullableRepeatPositionsI64AsFloat64 {
2250 source: Arc<[i64]>,
2251 run_positions: Arc<[usize]>,
2252 run_valid: Arc<[bool]>,
2253 run_lens: Arc<[usize]>,
2254 total_len: usize,
2255 values: OnceLock<Vec<Scalar>>,
2256 },
2257 LazyUtf8Slice {
2267 bytes: Arc<[u8]>,
2268 offsets: Arc<[usize]>,
2269 start: usize,
2270 len: usize,
2271 values: OnceLock<Vec<Scalar>>,
2272 },
2273}
2274
2275type Utf8ArcViewSource = (Arc<[u8]>, Arc<[usize]>, usize);
2276type Utf8ArcBuffers = (Arc<[u8]>, Arc<[usize]>);
2277
2278impl ScalarValues {
2279 fn from_vec(values: Vec<Scalar>) -> Self {
2280 Self::Eager(Arc::from(values))
2281 }
2282
2283 fn lazy_all_valid_int64(data: Vec<i64>) -> Self {
2284 Self::lazy_all_valid_int64_arc(Arc::from(data))
2285 }
2286
2287 fn lazy_all_valid_int64_arc(data: Arc<[i64]>) -> Self {
2291 Self::LazyAllValidInt64 {
2292 data,
2293 dense_cycle: OnceLock::new(),
2294 values: OnceLock::new(),
2295 }
2296 }
2297
2298 fn lazy_all_valid_int64_chunks(chunks: Arc<[Int64Chunk]>, len: usize) -> Self {
2299 Self::LazyAllValidInt64Chunks {
2300 chunks,
2301 len,
2302 data: OnceLock::new(),
2303 dense_cycle: OnceLock::new(),
2304 values: OnceLock::new(),
2305 }
2306 }
2307
2308 fn lazy_all_valid_datetime64(data: Vec<i64>) -> Self {
2309 Self::lazy_all_valid_datetime64_arc(Arc::from(data))
2310 }
2311
2312 fn lazy_all_valid_datetime64_arc(data: Arc<[i64]>) -> Self {
2313 Self::LazyAllValidDatetime64 {
2314 data,
2315 values: OnceLock::new(),
2316 }
2317 }
2318
2319 fn lazy_all_valid_float64(data: Vec<f64>) -> Self {
2320 Self::lazy_all_valid_float64_with_finite(data, None)
2321 }
2322
2323 fn bool_once_lock(value: Option<bool>) -> OnceLock<bool> {
2324 let lock = OnceLock::new();
2325 if let Some(value) = value {
2326 let _ = lock.set(value);
2327 }
2328 lock
2329 }
2330
2331 fn lazy_all_valid_float64_with_finite(data: Vec<f64>, all_finite: Option<bool>) -> Self {
2332 let data = Arc::from(data);
2333 match all_finite {
2334 Some(all_finite) => {
2335 Self::lazy_all_valid_float64_arc_with_finite(data, Some(all_finite))
2336 }
2337 None => Self::lazy_all_valid_float64_arc(data),
2338 }
2339 }
2340
2341 fn all_valid_float64_finite_witness(&self) -> Option<bool> {
2345 match self {
2346 Self::LazyAllValidFloat64 { all_finite, .. }
2347 | Self::LazyAllValidFloat64Chunks { all_finite, .. }
2348 | Self::LazyAllValidFloat64Slice { all_finite, .. } => all_finite.get().copied(),
2349 _ => None,
2350 }
2351 }
2352
2353 fn lazy_all_valid_float64_arc(data: Arc<[f64]>) -> Self {
2355 Self::lazy_all_valid_float64_arc_with_finite(data, None)
2356 }
2357
2358 fn lazy_all_valid_float64_arc_with_finite(data: Arc<[f64]>, all_finite: Option<bool>) -> Self {
2359 Self::LazyAllValidFloat64 {
2360 data,
2361 all_finite: Self::bool_once_lock(all_finite),
2362 values: OnceLock::new(),
2363 }
2364 }
2365
2366 fn lazy_all_valid_float64_chunks(chunks: Arc<[Float64Chunk]>, len: usize) -> Self {
2367 Self::LazyAllValidFloat64Chunks {
2368 chunks,
2369 len,
2370 data: OnceLock::new(),
2371 all_finite: OnceLock::new(),
2372 values: OnceLock::new(),
2373 }
2374 }
2375
2376 fn lazy_strided_float64(data: Arc<[f64]>, start: usize, step: usize, len: usize) -> Self {
2377 debug_assert!(step > 0);
2378 if len > 0 {
2379 debug_assert!(
2380 start
2381 .checked_add(step.saturating_mul(len.saturating_sub(1)))
2382 .is_some_and(|last| last < data.len())
2383 );
2384 }
2385 Self::LazyStridedFloat64 {
2386 data,
2387 start,
2388 step,
2389 len,
2390 expanded: OnceLock::new(),
2391 values: OnceLock::new(),
2392 }
2393 }
2394
2395 fn lazy_all_valid_float64_slice(data: Arc<[f64]>, start: usize, len: usize) -> Self {
2396 Self::lazy_all_valid_float64_slice_with_finite(data, start, len, None)
2397 }
2398
2399 fn lazy_all_valid_float64_slice_with_finite(
2400 data: Arc<[f64]>,
2401 start: usize,
2402 len: usize,
2403 all_finite: Option<bool>,
2404 ) -> Self {
2405 debug_assert!(
2406 start.checked_add(len).is_some_and(|end| end <= data.len()),
2407 "Float64 view window must lie within source data"
2408 );
2409 Self::LazyAllValidFloat64Slice {
2410 data,
2411 start,
2412 len,
2413 all_finite: Self::bool_once_lock(all_finite),
2414 values: OnceLock::new(),
2415 }
2416 }
2417
2418 fn lazy_all_valid_float64_dot(
2419 a_cols: Arc<[Float64DotInput]>,
2420 b_col: Arc<[f64]>,
2421 len: usize,
2422 ) -> Self {
2423 debug_assert_eq!(a_cols.len(), b_col.len());
2424 Self::LazyAllValidFloat64Dot {
2425 a_cols,
2426 b_col,
2427 len,
2428 data: OnceLock::new(),
2429 values: OnceLock::new(),
2430 }
2431 }
2432
2433 fn lazy_all_valid_float64_pairwise_stat_matrix_column(
2434 plan: Arc<Float64PairwiseStatMatrixPlan>,
2435 col: usize,
2436 ) -> Self {
2437 debug_assert!(col < plan.column_len());
2438 Self::LazyAllValidFloat64PairwiseStatMatrixColumn {
2439 plan,
2440 col,
2441 data: OnceLock::new(),
2442 values: OnceLock::new(),
2443 }
2444 }
2445
2446 fn lazy_combine_first_float64(
2447 left: Arc<[f64]>,
2448 right: Arc<[f64]>,
2449 left_validity_words: Arc<[u64]>,
2450 len: usize,
2451 ) -> Self {
2452 debug_assert!(left.len() >= len);
2453 debug_assert!(right.len() >= len);
2454 Self::LazyCombineFirstFloat64 {
2455 left,
2456 right,
2457 left_validity_words,
2458 len,
2459 data: OnceLock::new(),
2460 values: OnceLock::new(),
2461 }
2462 }
2463
2464 fn lazy_nullable_float64(data: Vec<f64>, validity: ValidityMask) -> Self {
2465 Self::LazyNullableFloat64 {
2466 data,
2467 validity,
2468 values: OnceLock::new(),
2469 }
2470 }
2471
2472 fn lazy_nullable_int64(data: Vec<i64>, validity: ValidityMask) -> Self {
2473 Self::LazyNullableInt64 {
2474 data,
2475 validity,
2476 values: OnceLock::new(),
2477 }
2478 }
2479
2480 fn lazy_nullable_bool(data: Vec<bool>, validity: ValidityMask) -> Self {
2481 Self::LazyNullableBool {
2482 data,
2483 validity,
2484 values: OnceLock::new(),
2485 }
2486 }
2487
2488 fn lazy_all_valid_bool(data: Vec<bool>) -> Self {
2489 Self::lazy_all_valid_bool_arc(Arc::from(data))
2490 }
2491
2492 fn lazy_all_valid_bool_arc(data: Arc<[bool]>) -> Self {
2494 Self::LazyAllValidBool {
2495 data,
2496 affine_selection: OnceLock::new(),
2497 values: OnceLock::new(),
2498 }
2499 }
2500
2501 fn lazy_contiguous_utf8(bytes: Vec<u8>, offsets: Vec<usize>) -> Self {
2502 debug_assert!(!offsets.is_empty(), "offsets must hold n+1 entries");
2503 debug_assert_eq!(*offsets.last().expect("non-empty"), bytes.len());
2504 Self::lazy_contiguous_utf8_arc(Arc::from(bytes), Arc::from(offsets))
2505 }
2506
2507 fn lazy_lower_hex_sequence_utf8(
2508 prefix: &[u8],
2509 start: u64,
2510 len: usize,
2511 hex_width: usize,
2512 ) -> Option<Self> {
2513 if prefix.is_empty() || hex_width == 0 || hex_width > 16 {
2514 return None;
2515 }
2516 if len > 0 {
2517 let last = start.checked_add(u64::try_from(len.checked_sub(1)?).ok()?)?;
2518 if hex_width < 16 && (last >> (hex_width * 4)) != 0 {
2519 return None;
2520 }
2521 }
2522
2523 let _ = prefix.len().checked_add(hex_width)?.checked_mul(len)?;
2524 let _ = len.checked_add(1)?;
2525
2526 Some(Self::LazyLowerHexSequenceUtf8 {
2527 prefix: Arc::from(prefix),
2528 start,
2529 len,
2530 hex_width,
2531 buffers: OnceLock::new(),
2532 values: OnceLock::new(),
2533 })
2534 }
2535
2536 fn materialize_lower_hex_sequence_utf8(
2537 prefix: &[u8],
2538 start: u64,
2539 len: usize,
2540 hex_width: usize,
2541 ) -> Utf8ArcBuffers {
2542 let width = prefix.len() + hex_width;
2543 let mut bytes = Vec::with_capacity(width * len);
2544 let mut offsets = Vec::with_capacity(len + 1);
2545 offsets.push(0);
2546 let mut row_key = Vec::with_capacity(width);
2547 row_key.extend_from_slice(prefix);
2548 push_fixed_width_lower_hex(&mut row_key, start, hex_width);
2549 for row in 0..len {
2550 bytes.extend_from_slice(&row_key);
2551 offsets.push(bytes.len());
2552 if row + 1 < len {
2553 increment_fixed_width_lower_hex(&mut row_key[prefix.len()..]);
2554 }
2555 }
2556 (Arc::from(bytes), Arc::from(offsets))
2557 }
2558
2559 fn materialized_lower_hex_buffers<'a>(
2560 prefix: &[u8],
2561 start: u64,
2562 len: usize,
2563 hex_width: usize,
2564 buffers: &'a OnceLock<Utf8ArcBuffers>,
2565 ) -> &'a Utf8ArcBuffers {
2566 buffers.get_or_init(|| {
2567 Self::materialize_lower_hex_sequence_utf8(prefix, start, len, hex_width)
2568 })
2569 }
2570
2571 fn lower_hex_sequence_witness(
2572 prefix: &[u8],
2573 start: u64,
2574 len: usize,
2575 hex_width: usize,
2576 ) -> (&[u8], Utf8LowerHexSequence, usize) {
2577 (
2578 prefix,
2579 Utf8LowerHexSequence {
2580 prefix_len: prefix.len(),
2581 hex_width,
2582 start,
2583 },
2584 len,
2585 )
2586 }
2587
2588 fn lazy_contiguous_utf8_arc(bytes: Arc<[u8]>, offsets: Arc<[usize]>) -> Self {
2595 debug_assert!(!offsets.is_empty(), "offsets must hold n+1 entries");
2596 debug_assert_eq!(*offsets.last().expect("non-empty"), bytes.len());
2597 Self::LazyContiguousUtf8 {
2598 bytes,
2599 offsets,
2600 strictly_increasing: OnceLock::new(),
2601 fixed_width: OnceLock::new(),
2602 lower_hex_sequence: OnceLock::new(),
2603 factorize_default: OnceLock::new(),
2604 values: OnceLock::new(),
2605 }
2606 }
2607
2608 fn lazy_nullable_utf8(bytes: Vec<u8>, offsets: Vec<usize>, validity: ValidityMask) -> Self {
2609 debug_assert!(!offsets.is_empty(), "offsets must hold n+1 entries");
2610 debug_assert_eq!(*offsets.last().expect("non-empty"), bytes.len());
2611 debug_assert_eq!(offsets.len() - 1, validity.len());
2612 Self::LazyNullableUtf8 {
2613 bytes: Arc::from(bytes),
2614 offsets: Arc::from(offsets),
2615 validity,
2616 values: OnceLock::new(),
2617 }
2618 }
2619
2620 fn lazy_gather_utf8(source: Arc<[Scalar]>, positions: Arc<[usize]>) -> Self {
2625 Self::LazyGatherUtf8 {
2626 source,
2627 positions,
2628 values: OnceLock::new(),
2629 }
2630 }
2631
2632 fn lazy_nullable_utf8_range(
2633 source: Arc<[Scalar]>,
2634 null_prefix: usize,
2635 source_start: usize,
2636 source_len: usize,
2637 null_suffix: usize,
2638 ) -> Self {
2639 debug_assert!(
2640 source_start
2641 .checked_add(source_len)
2642 .is_some_and(|end| end <= source.len())
2643 );
2644 Self::LazyNullableUtf8Range {
2645 source,
2646 null_prefix,
2647 source_start,
2648 source_len,
2649 null_suffix,
2650 values: OnceLock::new(),
2651 }
2652 }
2653
2654 fn eager_arc(&self) -> Option<&Arc<[Scalar]>> {
2657 match self {
2658 Self::Eager(values) => Some(values),
2659 _ => None,
2660 }
2661 }
2662
2663 fn lazy_utf8_slice(bytes: Arc<[u8]>, offsets: Arc<[usize]>, start: usize, len: usize) -> Self {
2668 debug_assert!(
2669 start + len < offsets.len(),
2670 "view window must lie within the source offsets"
2671 );
2672 Self::LazyUtf8Slice {
2673 bytes,
2674 offsets,
2675 start,
2676 len,
2677 values: OnceLock::new(),
2678 }
2679 }
2680
2681 fn lazy_repeat_runs_int64(runs: Vec<(i64, usize)>, total_len: usize) -> Self {
2682 debug_assert_eq!(
2683 runs.iter().map(|&(_, run_len)| run_len).sum::<usize>(),
2684 total_len
2685 );
2686 Self::LazyRepeatRunsInt64 {
2687 runs,
2688 total_len,
2689 data: OnceLock::new(),
2690 values: OnceLock::new(),
2691 }
2692 }
2693
2694 fn lazy_repeat_values_int64(
2695 run_values: Vec<i64>,
2696 run_lens: Arc<[usize]>,
2697 total_len: usize,
2698 ) -> Self {
2699 debug_assert_eq!(run_values.len(), run_lens.len());
2700 debug_assert_eq!(run_lens.iter().sum::<usize>(), total_len);
2701 Self::LazyRepeatValuesInt64 {
2702 run_values,
2703 run_lens,
2704 total_len,
2705 data: OnceLock::new(),
2706 values: OnceLock::new(),
2707 }
2708 }
2709
2710 fn lazy_repeated_slices_int64(
2711 data: Vec<i64>,
2712 segments: Vec<(usize, usize)>,
2713 total_len: usize,
2714 ) -> Self {
2715 Self::lazy_repeated_slices_int64_shared(data, Arc::from(segments), total_len)
2716 }
2717
2718 fn lazy_repeated_slices_int64_shared(
2719 data: Vec<i64>,
2720 segments: Arc<[(usize, usize)]>,
2721 total_len: usize,
2722 ) -> Self {
2723 debug_assert_eq!(
2724 segments.iter().map(|&(_, len)| len).sum::<usize>(),
2725 total_len
2726 );
2727 debug_assert!(
2728 segments
2729 .iter()
2730 .all(|&(start, len)| start.checked_add(len).is_some_and(|end| end <= data.len()))
2731 );
2732 Self::LazyRepeatedSlicesInt64 {
2733 data,
2734 segments,
2735 total_len,
2736 expanded: OnceLock::new(),
2737 values: OnceLock::new(),
2738 }
2739 }
2740
2741 fn lazy_repeat_values_float64(
2742 run_values: Vec<f64>,
2743 run_lens: Arc<[usize]>,
2744 total_len: usize,
2745 ) -> Self {
2746 debug_assert_eq!(run_values.len(), run_lens.len());
2747 debug_assert_eq!(run_lens.iter().sum::<usize>(), total_len);
2748 Self::LazyRepeatValuesFloat64 {
2749 run_values,
2750 run_lens,
2751 total_len,
2752 values: OnceLock::new(),
2753 }
2754 }
2755
2756 fn lazy_repeated_slices_float64_shared(
2757 data: Vec<f64>,
2758 segments: Arc<[(usize, usize)]>,
2759 total_len: usize,
2760 ) -> Self {
2761 debug_assert_eq!(
2762 segments.iter().map(|&(_, len)| len).sum::<usize>(),
2763 total_len
2764 );
2765 debug_assert!(
2766 segments
2767 .iter()
2768 .all(|&(start, len)| start.checked_add(len).is_some_and(|end| end <= data.len()))
2769 );
2770 Self::LazyRepeatedSlicesFloat64 {
2771 data,
2772 segments,
2773 total_len,
2774 expanded: OnceLock::new(),
2775 values: OnceLock::new(),
2776 }
2777 }
2778
2779 fn lazy_nullable_repeated_slices_int64(
2780 data: Vec<i64>,
2781 segments: Arc<[(usize, usize)]>,
2782 total_len: usize,
2783 ) -> Self {
2784 debug_assert_eq!(
2785 segments.iter().map(|&(_, len)| len).sum::<usize>(),
2786 total_len
2787 );
2788 Self::LazyNullableRepeatedSlicesInt64 {
2789 data,
2790 segments,
2791 total_len,
2792 values: OnceLock::new(),
2793 }
2794 }
2795
2796 fn lazy_nullable_repeated_slices_float64(
2797 data: Vec<f64>,
2798 segments: Arc<[(usize, usize)]>,
2799 total_len: usize,
2800 ) -> Self {
2801 debug_assert_eq!(
2802 segments.iter().map(|&(_, len)| len).sum::<usize>(),
2803 total_len
2804 );
2805 Self::LazyNullableRepeatedSlicesFloat64 {
2806 data,
2807 segments,
2808 total_len,
2809 values: OnceLock::new(),
2810 }
2811 }
2812
2813 fn lazy_nullable_repeat_values_float64(
2814 run_values: Vec<f64>,
2815 run_valid: Arc<[bool]>,
2816 run_lens: Arc<[usize]>,
2817 total_len: usize,
2818 ) -> Self {
2819 debug_assert_eq!(run_values.len(), run_lens.len());
2820 debug_assert_eq!(run_valid.len(), run_lens.len());
2821 debug_assert_eq!(run_lens.iter().sum::<usize>(), total_len);
2822 Self::LazyNullableRepeatValuesFloat64 {
2823 run_values,
2824 run_valid,
2825 run_lens,
2826 total_len,
2827 values: OnceLock::new(),
2828 }
2829 }
2830
2831 fn lazy_nullable_repeated_positions_i64_as_float64(
2832 source: Arc<[i64]>,
2833 positions: Arc<[usize]>,
2834 segments: Arc<[(usize, usize)]>,
2835 total_len: usize,
2836 ) -> Self {
2837 debug_assert_eq!(
2838 segments.iter().map(|&(_, len)| len).sum::<usize>(),
2839 total_len
2840 );
2841 debug_assert!(segments.iter().all(|&(start, len)| {
2842 start == usize::MAX
2843 || start
2844 .checked_add(len)
2845 .is_some_and(|end| end <= positions.len())
2846 }));
2847 debug_assert!(positions.iter().all(|&pos| pos < source.len()));
2848 Self::LazyNullableRepeatedPositionsI64AsFloat64 {
2849 source,
2850 positions,
2851 segments,
2852 total_len,
2853 values: OnceLock::new(),
2854 }
2855 }
2856
2857 fn lazy_nullable_dense_cycle_right_i64_as_float64(
2858 source: Arc<[i64]>,
2859 left_witness: Int64DenseCycleWitness,
2860 right_witness: Int64DenseCycleWitness,
2861 min_key: i64,
2862 span: usize,
2863 total_len: usize,
2864 ) -> Self {
2865 debug_assert_eq!(source.len(), right_witness.len);
2866 debug_assert!(span > 0 || total_len == 0);
2867 Self::LazyNullableDenseCycleRightI64AsFloat64 {
2868 source,
2869 left_witness,
2870 right_witness,
2871 min_key,
2872 span,
2873 total_len,
2874 values: OnceLock::new(),
2875 }
2876 }
2877
2878 fn lazy_nullable_dense_cycle_left_i64_as_float64(
2879 source: Arc<[i64]>,
2880 left_witness: Int64DenseCycleWitness,
2881 right_witness: Int64DenseCycleWitness,
2882 min_key: i64,
2883 span: usize,
2884 total_len: usize,
2885 ) -> Self {
2886 debug_assert_eq!(source.len(), left_witness.len);
2887 debug_assert!(span > 0 || total_len == 0);
2888 Self::LazyNullableDenseCycleLeftI64AsFloat64 {
2889 source,
2890 left_witness,
2891 right_witness,
2892 min_key,
2893 span,
2894 total_len,
2895 values: OnceLock::new(),
2896 }
2897 }
2898
2899 fn lazy_dense_cycle_probe_repeat_int64(
2900 source: Arc<[i64]>,
2901 probe_witness: Int64DenseCycleWitness,
2902 build_witness: Int64DenseCycleWitness,
2903 total_len: usize,
2904 ) -> Self {
2905 debug_assert_eq!(source.len(), probe_witness.len);
2906 Self::LazyDenseCycleProbeRepeatInt64 {
2907 source,
2908 probe_witness,
2909 build_witness,
2910 total_len,
2911 data: OnceLock::new(),
2912 values: OnceLock::new(),
2913 }
2914 }
2915
2916 fn lazy_left_join_dense_cycle_left_int64(
2917 source: Arc<[i64]>,
2918 left_witness: Int64DenseCycleWitness,
2919 right_witness: Int64DenseCycleWitness,
2920 total_len: usize,
2921 ) -> Self {
2922 debug_assert_eq!(source.len(), left_witness.len);
2923 Self::LazyLeftJoinDenseCycleLeftInt64 {
2924 source,
2925 left_witness,
2926 right_witness,
2927 total_len,
2928 data: OnceLock::new(),
2929 values: OnceLock::new(),
2930 }
2931 }
2932
2933 fn lazy_nullable_dense_cycle_probe_build_int64(
2934 source: Arc<[i64]>,
2935 probe_witness: Int64DenseCycleWitness,
2936 build_witness: Int64DenseCycleWitness,
2937 total_len: usize,
2938 ) -> Self {
2939 debug_assert_eq!(source.len(), build_witness.len);
2940 Self::LazyNullableDenseCycleProbeBuildInt64 {
2941 source,
2942 probe_witness,
2943 build_witness,
2944 total_len,
2945 values: OnceLock::new(),
2946 }
2947 }
2948
2949 fn lazy_left_join_dense_cycle_right_int64(
2950 source: Arc<[i64]>,
2951 left_witness: Int64DenseCycleWitness,
2952 right_witness: Int64DenseCycleWitness,
2953 total_len: usize,
2954 ) -> Self {
2955 debug_assert_eq!(source.len(), right_witness.len);
2956 Self::LazyLeftJoinDenseCycleRightInt64 {
2957 source,
2958 left_witness,
2959 right_witness,
2960 total_len,
2961 data: OnceLock::new(),
2962 values: OnceLock::new(),
2963 }
2964 }
2965
2966 fn lazy_nullable_repeat_positions_i64_as_float64(
2967 source: Arc<[i64]>,
2968 run_positions: Arc<[usize]>,
2969 run_valid: Arc<[bool]>,
2970 run_lens: Arc<[usize]>,
2971 total_len: usize,
2972 ) -> Self {
2973 debug_assert_eq!(run_positions.len(), run_lens.len());
2974 debug_assert_eq!(run_valid.len(), run_lens.len());
2975 debug_assert_eq!(run_lens.iter().sum::<usize>(), total_len);
2976 debug_assert!(
2977 run_positions
2978 .iter()
2979 .zip(run_valid.iter())
2980 .all(|(&pos, &valid)| !valid || pos < source.len())
2981 );
2982 Self::LazyNullableRepeatPositionsI64AsFloat64 {
2983 source,
2984 run_positions,
2985 run_valid,
2986 run_lens,
2987 total_len,
2988 values: OnceLock::new(),
2989 }
2990 }
2991
2992 fn expand_repeat_values_i64(
2993 run_values: &[i64],
2994 run_lens: &[usize],
2995 total_len: usize,
2996 ) -> Vec<i64> {
2997 const PARALLEL_MIN_VALUES: usize = 1 << 18;
2998 const PARALLEL_MAX_CHUNKS: usize = 16;
2999
3000 debug_assert_eq!(run_values.len(), run_lens.len());
3001 let thread_count = std::thread::available_parallelism()
3002 .map_or(1, usize::from)
3003 .min(PARALLEL_MAX_CHUNKS);
3004 if total_len < PARALLEL_MIN_VALUES || thread_count < 2 || run_values.is_empty() {
3005 let mut out = Vec::with_capacity(total_len);
3006 for (&value, &run_len) in run_values.iter().zip(run_lens.iter()) {
3007 out.resize(out.len() + run_len, value);
3008 }
3009 return out;
3010 }
3011
3012 let target = total_len.div_ceil(thread_count).max(1);
3013 let mut boundaries = vec![(0usize, 0usize)];
3014 let mut cumulative = 0usize;
3015 let mut next_target = target;
3016 for (run_idx, &run_len) in run_lens.iter().enumerate() {
3017 cumulative += run_len;
3018 if cumulative >= next_target && run_idx + 1 < run_lens.len() {
3019 boundaries.push((run_idx + 1, cumulative));
3020 next_target = cumulative.saturating_add(target);
3021 }
3022 }
3023 debug_assert_eq!(cumulative, total_len);
3024 boundaries.push((run_lens.len(), total_len));
3025
3026 let mut out = vec![0i64; total_len];
3027 let mut chunk_slices = Vec::with_capacity(boundaries.len() - 1);
3028 let mut rest: &mut [i64] = out.as_mut_slice();
3029 let mut prev = 0usize;
3030 for window in boundaries.windows(2) {
3031 let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
3032 prev = window[1].1;
3033 rest = tail;
3034 chunk_slices.push(chunk_slice);
3035 }
3036
3037 std::thread::scope(|scope| {
3038 let mut handles = Vec::with_capacity(chunk_slices.len());
3039 for (chunk_idx, chunk_slice) in chunk_slices.into_iter().enumerate() {
3040 let (run_start, _) = boundaries[chunk_idx];
3041 let (run_end, _) = boundaries[chunk_idx + 1];
3042 let run_values = &run_values[run_start..run_end];
3043 let run_lens = &run_lens[run_start..run_end];
3044 handles.push(scope.spawn(move || {
3045 let mut cursor = 0usize;
3046 for (&value, &run_len) in run_values.iter().zip(run_lens.iter()) {
3047 chunk_slice[cursor..cursor + run_len].fill(value);
3048 cursor += run_len;
3049 }
3050 debug_assert_eq!(cursor, chunk_slice.len());
3051 }));
3052 }
3053 for handle in handles {
3054 handle
3055 .join()
3056 .expect("repeat-value expansion worker must not panic");
3057 }
3058 });
3059 out
3060 }
3061
3062 fn expand_repeated_slices_f64(
3063 data: &[f64],
3064 segments: &[(usize, usize)],
3065 total_len: usize,
3066 ) -> Vec<f64> {
3067 const PARALLEL_MIN_VALUES: usize = 1 << 18;
3068 const PARALLEL_MAX_CHUNKS: usize = 16;
3069
3070 if let Some((start, period)) = Self::repeated_prefix_period(segments, total_len, data.len())
3071 {
3072 let mut out = Vec::with_capacity(total_len);
3073 out.extend_from_slice(&data[start..start + period.min(total_len)]);
3074 while out.len() < total_len {
3075 let copy_len = out.len().min(total_len - out.len());
3076 out.extend_from_within(..copy_len);
3077 }
3078 return out;
3079 }
3080
3081 let thread_count = std::thread::available_parallelism()
3082 .map_or(1, usize::from)
3083 .min(PARALLEL_MAX_CHUNKS);
3084 if total_len < PARALLEL_MIN_VALUES || thread_count < 2 || segments.is_empty() {
3085 let mut out = Vec::with_capacity(total_len);
3086 for &(start, len) in segments {
3087 out.extend_from_slice(&data[start..start + len]);
3088 }
3089 return out;
3090 }
3091
3092 let target = total_len.div_ceil(thread_count).max(1);
3093 let mut boundaries = vec![(0usize, 0usize)];
3094 let mut cumulative = 0usize;
3095 let mut next_target = target;
3096 for (segment_idx, &(_, len)) in segments.iter().enumerate() {
3097 cumulative += len;
3098 if cumulative >= next_target && segment_idx + 1 < segments.len() {
3099 boundaries.push((segment_idx + 1, cumulative));
3100 next_target = cumulative.saturating_add(target);
3101 }
3102 }
3103 debug_assert_eq!(cumulative, total_len);
3104 boundaries.push((segments.len(), total_len));
3105
3106 let mut out = vec![0.0f64; total_len];
3107 let mut chunk_slices = Vec::with_capacity(boundaries.len() - 1);
3108 let mut rest: &mut [f64] = out.as_mut_slice();
3109 let mut prev = 0usize;
3110 for window in boundaries.windows(2) {
3111 let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
3112 prev = window[1].1;
3113 rest = tail;
3114 chunk_slices.push(chunk_slice);
3115 }
3116
3117 std::thread::scope(|scope| {
3118 let mut handles = Vec::with_capacity(chunk_slices.len());
3119 for (chunk_idx, chunk_slice) in chunk_slices.into_iter().enumerate() {
3120 let (segment_start, _) = boundaries[chunk_idx];
3121 let (segment_end, _) = boundaries[chunk_idx + 1];
3122 let segments = &segments[segment_start..segment_end];
3123 handles.push(scope.spawn(move || {
3124 let mut cursor = 0usize;
3125 for &(start, len) in segments {
3126 chunk_slice[cursor..cursor + len]
3127 .copy_from_slice(&data[start..start + len]);
3128 cursor += len;
3129 }
3130 debug_assert_eq!(cursor, chunk_slice.len());
3131 }));
3132 }
3133 for handle in handles {
3134 handle
3135 .join()
3136 .expect("repeated-slice expansion worker must not panic");
3137 }
3138 });
3139 out
3140 }
3141
3142 fn repeated_prefix_period(
3143 segments: &[(usize, usize)],
3144 total_len: usize,
3145 data_len: usize,
3146 ) -> Option<(usize, usize)> {
3147 if total_len == 0 {
3148 return segments.is_empty().then_some((0, 0));
3149 }
3150 let &(start, period) = segments.first()?;
3151 if period == 0 || start.checked_add(period)? > data_len {
3152 return None;
3153 }
3154 let mut remaining = total_len;
3155 for (idx, &(segment_start, len)) in segments.iter().enumerate() {
3156 if segment_start != start {
3157 return None;
3158 }
3159 if remaining >= period {
3160 if len != period {
3161 return None;
3162 }
3163 remaining -= period;
3164 } else {
3165 if idx + 1 != segments.len() || len != remaining {
3166 return None;
3167 }
3168 remaining = 0;
3169 }
3170 }
3171 (remaining == 0).then_some((start, period))
3172 }
3173
3174 fn expand_repeated_slices_i64(
3175 data: &[i64],
3176 segments: &[(usize, usize)],
3177 total_len: usize,
3178 ) -> Vec<i64> {
3179 const PARALLEL_MIN_VALUES: usize = 1 << 18;
3180 const PARALLEL_MAX_CHUNKS: usize = 16;
3181
3182 let thread_count = std::thread::available_parallelism()
3183 .map_or(1, usize::from)
3184 .min(PARALLEL_MAX_CHUNKS);
3185 if total_len < PARALLEL_MIN_VALUES || thread_count < 2 || segments.is_empty() {
3186 let mut out = Vec::with_capacity(total_len);
3187 for &(start, len) in segments {
3188 out.extend_from_slice(&data[start..start + len]);
3189 }
3190 return out;
3191 }
3192
3193 let target = total_len.div_ceil(thread_count).max(1);
3194 let mut boundaries = vec![(0usize, 0usize)];
3195 let mut cumulative = 0usize;
3196 let mut next_target = target;
3197 for (segment_idx, &(_, len)) in segments.iter().enumerate() {
3198 cumulative += len;
3199 if cumulative >= next_target && segment_idx + 1 < segments.len() {
3200 boundaries.push((segment_idx + 1, cumulative));
3201 next_target = cumulative.saturating_add(target);
3202 }
3203 }
3204 debug_assert_eq!(cumulative, total_len);
3205 boundaries.push((segments.len(), total_len));
3206
3207 let mut out = vec![0i64; total_len];
3208 let mut chunk_slices = Vec::with_capacity(boundaries.len() - 1);
3209 let mut rest: &mut [i64] = out.as_mut_slice();
3210 let mut prev = 0usize;
3211 for window in boundaries.windows(2) {
3212 let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
3213 prev = window[1].1;
3214 rest = tail;
3215 chunk_slices.push(chunk_slice);
3216 }
3217
3218 std::thread::scope(|scope| {
3219 let mut handles = Vec::with_capacity(chunk_slices.len());
3220 for (chunk_idx, chunk_slice) in chunk_slices.into_iter().enumerate() {
3221 let (segment_start, _) = boundaries[chunk_idx];
3222 let (segment_end, _) = boundaries[chunk_idx + 1];
3223 let segments = &segments[segment_start..segment_end];
3224 handles.push(scope.spawn(move || {
3225 let mut cursor = 0usize;
3226 for &(start, len) in segments {
3227 chunk_slice[cursor..cursor + len]
3228 .copy_from_slice(&data[start..start + len]);
3229 cursor += len;
3230 }
3231 debug_assert_eq!(cursor, chunk_slice.len());
3232 }));
3233 }
3234 for handle in handles {
3235 handle
3236 .join()
3237 .expect("repeated-slice expansion worker must not panic");
3238 }
3239 });
3240 out
3241 }
3242
3243 fn repeat_runs_i64_data(&self) -> Option<&[i64]> {
3251 const PARALLEL_MIN_VALUES: usize = 1 << 18;
3252 const PARALLEL_MAX_CHUNKS: usize = 16;
3253
3254 if let Self::LazyRepeatRunsInt64 {
3255 runs,
3256 total_len,
3257 data,
3258 ..
3259 } = self
3260 {
3261 return Some(
3262 data.get_or_init(|| {
3263 let thread_count = std::thread::available_parallelism()
3264 .map_or(1, usize::from)
3265 .min(PARALLEL_MAX_CHUNKS);
3266 if *total_len < PARALLEL_MIN_VALUES || thread_count < 2 || runs.is_empty() {
3267 let mut out = Vec::with_capacity(*total_len);
3268 for &(value, run_len) in runs {
3269 out.resize(out.len() + run_len, value);
3270 }
3271 return out;
3272 }
3273
3274 let target = total_len.div_ceil(thread_count).max(1);
3277 let mut boundaries = vec![(0usize, 0usize)];
3278 let mut cumulative = 0usize;
3279 let mut next_target = target;
3280 for (run_idx, &(_, run_len)) in runs.iter().enumerate() {
3281 cumulative += run_len;
3282 if cumulative >= next_target && run_idx + 1 < runs.len() {
3283 boundaries.push((run_idx + 1, cumulative));
3284 next_target = cumulative.saturating_add(target);
3285 }
3286 }
3287 debug_assert_eq!(cumulative, *total_len);
3288 boundaries.push((runs.len(), *total_len));
3289
3290 let mut out = vec![0i64; *total_len];
3291 let mut chunk_slices = Vec::with_capacity(boundaries.len() - 1);
3292 let mut rest: &mut [i64] = out.as_mut_slice();
3293 let mut prev = 0usize;
3294 for window in boundaries.windows(2) {
3295 let (chunk_slice, tail) = rest.split_at_mut(window[1].1 - prev);
3296 prev = window[1].1;
3297 rest = tail;
3298 chunk_slices.push(chunk_slice);
3299 }
3300
3301 std::thread::scope(|scope| {
3302 let mut handles = Vec::with_capacity(chunk_slices.len());
3303 for (chunk_idx, chunk_slice) in chunk_slices.into_iter().enumerate() {
3304 let (run_start, _) = boundaries[chunk_idx];
3305 let (run_end, _) = boundaries[chunk_idx + 1];
3306 let runs = &runs[run_start..run_end];
3307 handles.push(scope.spawn(move || {
3308 let mut cursor = 0usize;
3309 for &(value, run_len) in runs {
3310 chunk_slice[cursor..cursor + run_len].fill(value);
3311 cursor += run_len;
3312 }
3313 debug_assert_eq!(cursor, chunk_slice.len());
3314 }));
3315 }
3316 for handle in handles {
3317 handle
3318 .join()
3319 .expect("repeat-run expansion worker must not panic");
3320 }
3321 });
3322 out
3323 })
3324 .as_slice(),
3325 );
3326 }
3327 if let Self::LazyRepeatValuesInt64 {
3328 run_values,
3329 run_lens,
3330 total_len,
3331 data,
3332 ..
3333 } = self
3334 {
3335 return Some(
3336 data.get_or_init(|| {
3337 Self::expand_repeat_values_i64(run_values, run_lens, *total_len)
3338 })
3339 .as_slice(),
3340 );
3341 }
3342 if let Self::LazyDenseCycleProbeRepeatInt64 {
3343 source,
3344 probe_witness,
3345 build_witness,
3346 total_len,
3347 data,
3348 ..
3349 } = self
3350 {
3351 return Some(
3352 data.get_or_init(|| {
3353 Self::expand_dense_cycle_probe_repeat_i64(
3354 source,
3355 *probe_witness,
3356 *build_witness,
3357 *total_len,
3358 )
3359 })
3360 .as_slice(),
3361 );
3362 }
3363 None
3364 }
3365
3366 fn repeated_slices_i64_data(&self) -> Option<&[i64]> {
3367 if let Self::LazyRepeatedSlicesInt64 {
3368 data,
3369 segments,
3370 total_len,
3371 expanded,
3372 ..
3373 } = self
3374 {
3375 return Some(
3376 expanded
3377 .get_or_init(|| Self::expand_repeated_slices_i64(data, segments, *total_len))
3378 .as_slice(),
3379 );
3380 }
3381 None
3382 }
3383
3384 fn repeated_slices_f64_data(&self) -> Option<&[f64]> {
3385 if let Self::LazyRepeatedSlicesFloat64 {
3386 data,
3387 segments,
3388 total_len,
3389 expanded,
3390 ..
3391 } = self
3392 {
3393 return Some(
3394 expanded
3395 .get_or_init(|| Self::expand_repeated_slices_f64(data, segments, *total_len))
3396 .as_slice(),
3397 );
3398 }
3399 None
3400 }
3401
3402 fn dense_cycle_key_at(witness: Int64DenseCycleWitness, row: usize) -> i64 {
3403 witness
3404 .start
3405 .checked_add(
3406 i64::try_from(row % witness.period)
3407 .expect("dense-cycle period offset must fit in i64"),
3408 )
3409 .expect("dense-cycle key offset was prevalidated")
3410 }
3411
3412 fn expand_dense_cycle_probe_repeat_i64(
3413 source: &[i64],
3414 probe_witness: Int64DenseCycleWitness,
3415 build_witness: Int64DenseCycleWitness,
3416 total_len: usize,
3417 ) -> Vec<i64> {
3418 let mut out = Vec::with_capacity(total_len);
3419 for (probe_pos, &value) in source.iter().enumerate().take(probe_witness.len) {
3420 let key = Self::dense_cycle_key_at(probe_witness, probe_pos);
3421 let run_len = build_witness
3422 .offset_count_for_key(key)
3423 .map_or(1, |(_, count)| count);
3424 out.resize(out.len() + run_len, value);
3425 }
3426 debug_assert_eq!(out.len(), total_len);
3427 out
3428 }
3429
3430 fn expand_left_join_dense_cycle_left_i64(
3431 source: &[i64],
3432 left_witness: Int64DenseCycleWitness,
3433 right_witness: Int64DenseCycleWitness,
3434 total_len: usize,
3435 ) -> Vec<i64> {
3436 let mut out = Vec::with_capacity(total_len);
3437 for (left_pos, &value) in source.iter().enumerate().take(left_witness.len) {
3438 let key = Self::dense_cycle_key_at(left_witness, left_pos);
3439 let run_len = right_witness
3440 .offset_count_for_key(key)
3441 .map_or(1, |(_, count)| count);
3442 out.resize(out.len() + run_len, value);
3443 }
3444 debug_assert_eq!(out.len(), total_len);
3445 out
3446 }
3447
3448 fn expand_left_join_dense_cycle_right_i64(
3449 source: &[i64],
3450 left_witness: Int64DenseCycleWitness,
3451 right_witness: Int64DenseCycleWitness,
3452 total_len: usize,
3453 ) -> Vec<i64> {
3454 let mut out = Vec::with_capacity(total_len);
3455 for left_pos in 0..left_witness.len {
3456 let key = Self::dense_cycle_key_at(left_witness, left_pos);
3457 if let Some((mut right_pos, right_count)) = right_witness.offset_count_for_key(key) {
3458 for _ in 0..right_count {
3459 out.push(source[right_pos]);
3460 right_pos += right_witness.period;
3461 }
3462 } else {
3463 out.push(0);
3464 }
3465 }
3466 debug_assert_eq!(out.len(), total_len);
3467 out
3468 }
3469
3470 fn left_join_dense_cycle_i64_data(&self) -> Option<&[i64]> {
3471 match self {
3472 Self::LazyLeftJoinDenseCycleLeftInt64 {
3473 source,
3474 left_witness,
3475 right_witness,
3476 total_len,
3477 data,
3478 ..
3479 } => Some(
3480 data.get_or_init(|| {
3481 Self::expand_left_join_dense_cycle_left_i64(
3482 source,
3483 *left_witness,
3484 *right_witness,
3485 *total_len,
3486 )
3487 })
3488 .as_slice(),
3489 ),
3490 Self::LazyLeftJoinDenseCycleRightInt64 {
3491 source,
3492 left_witness,
3493 right_witness,
3494 total_len,
3495 data,
3496 ..
3497 } => Some(
3498 data.get_or_init(|| {
3499 Self::expand_left_join_dense_cycle_right_i64(
3500 source,
3501 *left_witness,
3502 *right_witness,
3503 *total_len,
3504 )
3505 })
3506 .as_slice(),
3507 ),
3508 _ => None,
3509 }
3510 }
3511
3512 fn expand_strided_float64(data: &[f64], start: usize, step: usize, len: usize) -> Vec<f64> {
3513 let mut out = Vec::with_capacity(len);
3514 for idx in 0..len {
3515 let source_idx = start + idx * step;
3516 out.push(data[source_idx]);
3517 }
3518 out
3519 }
3520
3521 fn strided_float64_data(&self) -> Option<&[f64]> {
3522 if let Self::LazyStridedFloat64 {
3523 data,
3524 start,
3525 step,
3526 len,
3527 expanded,
3528 ..
3529 } = self
3530 {
3531 return Some(
3532 expanded
3533 .get_or_init(|| Self::expand_strided_float64(data, *start, *step, *len))
3534 .as_slice(),
3535 );
3536 }
3537 None
3538 }
3539
3540 fn materialize_float64_dot(a_cols: &[Float64DotInput], b_col: &[f64], len: usize) -> Vec<f64> {
3541 debug_assert_eq!(a_cols.len(), b_col.len());
3542 let mut out = Vec::with_capacity(len);
3543 for row in 0..len {
3544 let mut acc = 0.0_f64;
3545 for (a_col, &b) in a_cols.iter().zip(b_col.iter()) {
3546 acc += a_col.value_at(row) * b;
3547 }
3548 out.push(acc);
3549 }
3550 out
3551 }
3552
3553 fn dot_float64_data(&self) -> Option<&[f64]> {
3554 if let Self::LazyAllValidFloat64Dot {
3555 a_cols,
3556 b_col,
3557 len,
3558 data,
3559 ..
3560 } = self
3561 {
3562 return Some(
3563 data.get_or_init(|| Self::materialize_float64_dot(a_cols, b_col, *len))
3564 .as_slice(),
3565 );
3566 }
3567 None
3568 }
3569
3570 fn pairwise_stat_float64_data(&self) -> Option<&[f64]> {
3571 if let Self::LazyAllValidFloat64PairwiseStatMatrixColumn {
3572 plan, col, data, ..
3573 } = self
3574 {
3575 return Some(
3576 data.get_or_init(|| plan.materialize_column(*col))
3577 .as_slice(),
3578 );
3579 }
3580 None
3581 }
3582
3583 fn materialize_float64_chunks(chunks: &[Float64Chunk], len: usize) -> Vec<f64> {
3584 let mut out = Vec::with_capacity(len);
3585 for chunk in chunks {
3586 out.extend_from_slice(chunk.as_slice());
3587 }
3588 debug_assert_eq!(out.len(), len);
3589 out
3590 }
3591
3592 fn chunks_float64_data(&self) -> Option<&[f64]> {
3593 if let Self::LazyAllValidFloat64Chunks {
3594 chunks, len, data, ..
3595 } = self
3596 {
3597 return Some(
3598 data.get_or_init(|| Self::materialize_float64_chunks(chunks, *len))
3599 .as_slice(),
3600 );
3601 }
3602 None
3603 }
3604
3605 fn materialize_int64_chunks(chunks: &[Int64Chunk], len: usize) -> Vec<i64> {
3606 let mut out = Vec::with_capacity(len);
3607 for chunk in chunks {
3608 out.extend_from_slice(chunk.as_slice());
3609 }
3610 debug_assert_eq!(out.len(), len);
3611 out
3612 }
3613
3614 fn chunks_i64_data(&self) -> Option<&[i64]> {
3615 if let Self::LazyAllValidInt64Chunks {
3616 chunks, len, data, ..
3617 } = self
3618 {
3619 return Some(
3620 data.get_or_init(|| Self::materialize_int64_chunks(chunks, *len))
3621 .as_slice(),
3622 );
3623 }
3624 None
3625 }
3626
3627 fn materialize_combine_first_float64(
3628 left: &[f64],
3629 right: &[f64],
3630 left_validity_words: &[u64],
3631 len: usize,
3632 ) -> Vec<f64> {
3633 let mut out = left[..len].to_vec();
3634 for (word_idx, out_chunk) in out.chunks_mut(64).enumerate() {
3635 let valid_word = left_validity_words.get(word_idx).copied().unwrap_or(0);
3636 let base = word_idx * 64;
3637 let len_mask = if out_chunk.len() == 64 {
3638 u64::MAX
3639 } else {
3640 (1_u64 << out_chunk.len()) - 1
3641 };
3642
3643 let mut invalid_bits = !valid_word & len_mask;
3644 while invalid_bits != 0 {
3645 let offset = invalid_bits.trailing_zeros() as usize;
3646 out_chunk[offset] = right[base + offset];
3647 invalid_bits &= invalid_bits - 1;
3648 }
3649
3650 let mut valid_bits = valid_word & len_mask;
3651 while valid_bits != 0 {
3652 let offset = valid_bits.trailing_zeros() as usize;
3653 if out_chunk[offset].is_nan() {
3654 out_chunk[offset] = right[base + offset];
3655 }
3656 valid_bits &= valid_bits - 1;
3657 }
3658 }
3659 out
3660 }
3661
3662 fn combine_first_float64_data(&self) -> Option<&[f64]> {
3663 if let Self::LazyCombineFirstFloat64 {
3664 left,
3665 right,
3666 left_validity_words,
3667 len,
3668 data,
3669 ..
3670 } = self
3671 {
3672 return Some(
3673 data.get_or_init(|| {
3674 Self::materialize_combine_first_float64(left, right, left_validity_words, *len)
3675 })
3676 .as_slice(),
3677 );
3678 }
3679 None
3680 }
3681
3682 fn as_slice(&self) -> &[Scalar] {
3683 match self {
3684 Self::Eager(values) => values,
3685 Self::LazyAllValidInt64 { data, values, .. } => values
3686 .get_or_init(|| data.iter().copied().map(Scalar::Int64).collect())
3687 .as_slice(),
3688 Self::LazyAllValidInt64Chunks { chunks, values, .. } => values
3689 .get_or_init(|| {
3690 chunks
3691 .iter()
3692 .flat_map(Int64Chunk::as_slice)
3693 .copied()
3694 .map(Scalar::Int64)
3695 .collect()
3696 })
3697 .as_slice(),
3698 Self::LazyAllValidDatetime64 { data, values } => values
3699 .get_or_init(|| data.iter().copied().map(Scalar::Datetime64).collect())
3700 .as_slice(),
3701 Self::LazyAllValidFloat64 { data, values, .. } => values
3702 .get_or_init(|| data.iter().copied().map(Scalar::Float64).collect())
3703 .as_slice(),
3704 Self::LazyAllValidFloat64Chunks { chunks, values, .. } => values
3705 .get_or_init(|| {
3706 chunks
3707 .iter()
3708 .flat_map(Float64Chunk::as_slice)
3709 .copied()
3710 .map(Scalar::Float64)
3711 .collect()
3712 })
3713 .as_slice(),
3714 Self::LazyAllValidFloat64Slice {
3715 data,
3716 start,
3717 len,
3718 values,
3719 ..
3720 } => values
3721 .get_or_init(|| {
3722 data[*start..*start + *len]
3723 .iter()
3724 .copied()
3725 .map(Scalar::Float64)
3726 .collect()
3727 })
3728 .as_slice(),
3729 Self::LazyAllValidFloat64Dot {
3730 a_cols,
3731 b_col,
3732 len,
3733 data,
3734 values,
3735 } => values
3736 .get_or_init(|| {
3737 data.get_or_init(|| Self::materialize_float64_dot(a_cols, b_col, *len))
3738 .iter()
3739 .copied()
3740 .map(Scalar::Float64)
3741 .collect()
3742 })
3743 .as_slice(),
3744 Self::LazyAllValidFloat64PairwiseStatMatrixColumn {
3745 plan,
3746 col,
3747 data,
3748 values,
3749 } => values
3750 .get_or_init(|| {
3751 data.get_or_init(|| plan.materialize_column(*col))
3752 .iter()
3753 .copied()
3754 .map(Scalar::Float64)
3755 .collect()
3756 })
3757 .as_slice(),
3758 Self::LazyCombineFirstFloat64 {
3759 left,
3760 right,
3761 left_validity_words,
3762 len,
3763 data,
3764 values,
3765 } => values
3766 .get_or_init(|| {
3767 data.get_or_init(|| {
3768 Self::materialize_combine_first_float64(
3769 left,
3770 right,
3771 left_validity_words,
3772 *len,
3773 )
3774 })
3775 .iter()
3776 .copied()
3777 .map(Scalar::Float64)
3778 .collect()
3779 })
3780 .as_slice(),
3781 Self::LazyStridedFloat64 {
3782 data,
3783 start,
3784 step,
3785 len,
3786 expanded,
3787 values,
3788 } => values
3789 .get_or_init(|| {
3790 expanded
3791 .get_or_init(|| Self::expand_strided_float64(data, *start, *step, *len))
3792 .iter()
3793 .copied()
3794 .map(Scalar::Float64)
3795 .collect()
3796 })
3797 .as_slice(),
3798 Self::LazyNullableFloat64 {
3799 data,
3800 validity,
3801 values,
3802 } => values
3803 .get_or_init(|| {
3804 data.iter()
3805 .enumerate()
3806 .map(|(idx, value)| {
3807 if validity.get(idx) || value.is_nan() {
3808 Scalar::Float64(*value)
3809 } else {
3810 Scalar::Null(NullKind::NaN)
3811 }
3812 })
3813 .collect()
3814 })
3815 .as_slice(),
3816 Self::LazyAllValidBool { data, values, .. } => values
3817 .get_or_init(|| data.iter().copied().map(Scalar::Bool).collect())
3818 .as_slice(),
3819 Self::LazyContiguousUtf8 {
3820 bytes,
3821 offsets,
3822 values,
3823 ..
3824 } => values
3825 .get_or_init(|| {
3826 offsets
3827 .windows(2)
3828 .map(|w| {
3829 Scalar::Utf8(
3830 std::str::from_utf8(&bytes[w[0]..w[1]])
3831 .expect("contiguous utf8 buffer is valid by construction")
3832 .to_owned(),
3833 )
3834 })
3835 .collect()
3836 })
3837 .as_slice(),
3838 Self::LazyLowerHexSequenceUtf8 {
3839 prefix,
3840 start,
3841 len,
3842 hex_width,
3843 buffers,
3844 values,
3845 } => values
3846 .get_or_init(|| {
3847 let (bytes, offsets) = Self::materialized_lower_hex_buffers(
3848 prefix, *start, *len, *hex_width, buffers,
3849 );
3850 offsets
3851 .windows(2)
3852 .map(|w| {
3853 Scalar::Utf8(
3854 std::str::from_utf8(&bytes[w[0]..w[1]])
3855 .expect("lower-hex utf8 buffer is valid by construction")
3856 .to_owned(),
3857 )
3858 })
3859 .collect()
3860 })
3861 .as_slice(),
3862 Self::LazyNullableUtf8 {
3863 bytes,
3864 offsets,
3865 validity,
3866 values,
3867 } => values
3868 .get_or_init(|| {
3869 offsets
3870 .windows(2)
3871 .enumerate()
3872 .map(|(idx, w)| {
3873 if validity.get(idx) {
3874 Scalar::Utf8(
3875 std::str::from_utf8(&bytes[w[0]..w[1]])
3876 .expect("nullable utf8 buffer is valid by construction")
3877 .to_owned(),
3878 )
3879 } else {
3880 Scalar::Null(NullKind::Null)
3881 }
3882 })
3883 .collect()
3884 })
3885 .as_slice(),
3886 Self::LazyGatherUtf8 {
3887 source,
3888 positions,
3889 values,
3890 } => values
3891 .get_or_init(|| {
3892 positions
3893 .iter()
3894 .map(|&pos| {
3895 if pos == usize::MAX {
3896 Scalar::Null(NullKind::Null)
3901 } else {
3902 source[pos].clone()
3903 }
3904 })
3905 .collect()
3906 })
3907 .as_slice(),
3908 Self::LazyNullableUtf8Range {
3909 source,
3910 null_prefix,
3911 source_start,
3912 source_len,
3913 null_suffix,
3914 values,
3915 } => values
3916 .get_or_init(|| {
3917 let total_len = null_prefix + source_len + null_suffix;
3918 (0..total_len)
3919 .map(|out_idx| {
3920 if out_idx < *null_prefix
3921 || out_idx >= null_prefix.saturating_add(*source_len)
3922 {
3923 Scalar::Null(NullKind::Null)
3924 } else {
3925 source[source_start + out_idx - null_prefix].clone()
3926 }
3927 })
3928 .collect()
3929 })
3930 .as_slice(),
3931 Self::LazyNullableInt64 {
3932 data,
3933 validity,
3934 values,
3935 } => values
3936 .get_or_init(|| {
3937 data.iter()
3938 .enumerate()
3939 .map(|(idx, value)| {
3940 if validity.get(idx) {
3941 Scalar::Int64(*value)
3942 } else {
3943 Scalar::Null(NullKind::Null)
3944 }
3945 })
3946 .collect()
3947 })
3948 .as_slice(),
3949 Self::LazyNullableBool {
3950 data,
3951 validity,
3952 values,
3953 } => values
3954 .get_or_init(|| {
3955 data.iter()
3956 .enumerate()
3957 .map(|(idx, value)| {
3958 if validity.get(idx) {
3959 Scalar::Bool(*value)
3960 } else {
3961 Scalar::Null(NullKind::Null)
3962 }
3963 })
3964 .collect()
3965 })
3966 .as_slice(),
3967 Self::LazyRepeatRunsInt64 {
3968 runs,
3969 total_len,
3970 values,
3971 ..
3972 } => values
3973 .get_or_init(|| {
3974 let mut out = Vec::with_capacity(*total_len);
3975 for &(value, run_len) in runs {
3976 out.resize(out.len() + run_len, Scalar::Int64(value));
3977 }
3978 out
3979 })
3980 .as_slice(),
3981 Self::LazyRepeatValuesInt64 {
3982 run_values,
3983 run_lens,
3984 total_len,
3985 values,
3986 ..
3987 } => values
3988 .get_or_init(|| {
3989 let mut out = Vec::with_capacity(*total_len);
3990 for (&value, &run_len) in run_values.iter().zip(run_lens.iter()) {
3991 out.resize(out.len() + run_len, Scalar::Int64(value));
3992 }
3993 out
3994 })
3995 .as_slice(),
3996 Self::LazyRepeatedSlicesInt64 {
3997 data,
3998 segments,
3999 total_len,
4000 values,
4001 ..
4002 } => values
4003 .get_or_init(|| {
4004 Self::expand_repeated_slices_i64(data, segments, *total_len)
4005 .into_iter()
4006 .map(Scalar::Int64)
4007 .collect()
4008 })
4009 .as_slice(),
4010 Self::LazyRepeatValuesFloat64 {
4011 run_values,
4012 run_lens,
4013 total_len,
4014 values,
4015 } => values
4016 .get_or_init(|| {
4017 let mut out = Vec::with_capacity(*total_len);
4018 for (&value, &run_len) in run_values.iter().zip(run_lens.iter()) {
4019 out.resize(out.len() + run_len, Scalar::Float64(value));
4020 }
4021 out
4022 })
4023 .as_slice(),
4024 Self::LazyRepeatedSlicesFloat64 {
4025 data,
4026 segments,
4027 total_len,
4028 values,
4029 ..
4030 } => values
4031 .get_or_init(|| {
4032 let mut out = Vec::with_capacity(*total_len);
4033 for &(start, len) in segments.iter() {
4034 for &value in &data[start..start + len] {
4035 out.push(Scalar::Float64(value));
4036 }
4037 }
4038 out
4039 })
4040 .as_slice(),
4041 Self::LazyNullableRepeatedSlicesInt64 {
4042 data,
4043 segments,
4044 total_len,
4045 values,
4046 } => values
4047 .get_or_init(|| {
4048 let mut out = Vec::with_capacity(*total_len);
4049 for &(start, len) in segments.iter() {
4050 if start == usize::MAX {
4051 out.resize(out.len() + len, Scalar::Null(NullKind::Null));
4052 } else {
4053 for &value in &data[start..start + len] {
4054 out.push(Scalar::Int64(value));
4055 }
4056 }
4057 }
4058 out
4059 })
4060 .as_slice(),
4061 Self::LazyNullableRepeatedSlicesFloat64 {
4062 data,
4063 segments,
4064 total_len,
4065 values,
4066 } => values
4067 .get_or_init(|| {
4068 let mut out = Vec::with_capacity(*total_len);
4069 for &(start, len) in segments.iter() {
4070 if start == usize::MAX {
4071 out.resize(out.len() + len, Scalar::Null(NullKind::NaN));
4072 } else {
4073 for &value in &data[start..start + len] {
4074 out.push(Scalar::Float64(value));
4075 }
4076 }
4077 }
4078 out
4079 })
4080 .as_slice(),
4081 Self::LazyNullableRepeatValuesFloat64 {
4082 run_values,
4083 run_valid,
4084 run_lens,
4085 total_len,
4086 values,
4087 } => values
4088 .get_or_init(|| {
4089 let mut out = Vec::with_capacity(*total_len);
4090 for ((&value, &valid), &run_len) in
4091 run_values.iter().zip(run_valid.iter()).zip(run_lens.iter())
4092 {
4093 if valid {
4094 out.resize(out.len() + run_len, Scalar::Float64(value));
4095 } else {
4096 out.resize(out.len() + run_len, Scalar::Null(NullKind::NaN));
4097 }
4098 }
4099 out
4100 })
4101 .as_slice(),
4102 Self::LazyNullableRepeatedPositionsI64AsFloat64 {
4103 source,
4104 positions,
4105 segments,
4106 total_len,
4107 values,
4108 } => values
4109 .get_or_init(|| {
4110 let mut out = Vec::with_capacity(*total_len);
4111 for &(start, len) in segments.iter() {
4112 if start == usize::MAX {
4113 out.resize(out.len() + len, Scalar::Null(NullKind::NaN));
4114 } else {
4115 for &source_pos in &positions[start..start + len] {
4116 out.push(Scalar::Float64(source[source_pos] as f64));
4117 }
4118 }
4119 }
4120 out
4121 })
4122 .as_slice(),
4123 Self::LazyNullableDenseCycleRightI64AsFloat64 {
4124 source,
4125 left_witness,
4126 right_witness,
4127 min_key,
4128 span,
4129 total_len,
4130 values,
4131 } => values
4132 .get_or_init(|| {
4133 let mut out = Vec::with_capacity(*total_len);
4134 for bucket in 0..*span {
4135 let key = min_key
4136 .checked_add(i64::try_from(bucket).expect("bucket fits in i64"))
4137 .expect("dense-cycle key span was prevalidated");
4138 let left_span = left_witness.offset_count_for_key(key);
4139 let right_span = right_witness.offset_count_for_key(key);
4140 match (left_span, right_span) {
4141 (Some((_, left_count)), Some((right_start, right_count))) => {
4142 for _ in 0..left_count {
4143 let mut right_pos = right_start;
4144 for _ in 0..right_count {
4145 out.push(Scalar::Float64(source[right_pos] as f64));
4146 right_pos += right_witness.period;
4147 }
4148 }
4149 }
4150 (Some((_, left_count)), None) => {
4151 out.resize(out.len() + left_count, Scalar::Null(NullKind::NaN));
4152 }
4153 (None, Some((mut right_pos, right_count))) => {
4154 for _ in 0..right_count {
4155 out.push(Scalar::Float64(source[right_pos] as f64));
4156 right_pos += right_witness.period;
4157 }
4158 }
4159 (None, None) => {}
4160 }
4161 }
4162 debug_assert_eq!(out.len(), *total_len);
4163 out
4164 })
4165 .as_slice(),
4166 Self::LazyNullableDenseCycleLeftI64AsFloat64 {
4167 source,
4168 left_witness,
4169 right_witness,
4170 min_key,
4171 span,
4172 total_len,
4173 values,
4174 } => values
4175 .get_or_init(|| {
4176 let mut out = Vec::with_capacity(*total_len);
4177 for bucket in 0..*span {
4178 let key = min_key
4179 .checked_add(i64::try_from(bucket).expect("bucket fits in i64"))
4180 .expect("dense-cycle key span was prevalidated");
4181 let left_span = left_witness.offset_count_for_key(key);
4182 let right_span = right_witness.offset_count_for_key(key);
4183 match (left_span, right_span) {
4184 (Some((mut left_pos, left_count)), Some((_, right_count))) => {
4185 for _ in 0..left_count {
4186 out.resize(
4187 out.len() + right_count,
4188 Scalar::Float64(source[left_pos] as f64),
4189 );
4190 left_pos += left_witness.period;
4191 }
4192 }
4193 (Some((mut left_pos, left_count)), None) => {
4194 for _ in 0..left_count {
4195 out.push(Scalar::Float64(source[left_pos] as f64));
4196 left_pos += left_witness.period;
4197 }
4198 }
4199 (None, Some((_, right_count))) => {
4200 out.resize(out.len() + right_count, Scalar::Null(NullKind::NaN));
4201 }
4202 (None, None) => {}
4203 }
4204 }
4205 debug_assert_eq!(out.len(), *total_len);
4206 out
4207 })
4208 .as_slice(),
4209 Self::LazyDenseCycleProbeRepeatInt64 {
4210 source,
4211 probe_witness,
4212 build_witness,
4213 total_len,
4214 values,
4215 ..
4216 } => values
4217 .get_or_init(|| {
4218 Self::expand_dense_cycle_probe_repeat_i64(
4219 source,
4220 *probe_witness,
4221 *build_witness,
4222 *total_len,
4223 )
4224 .into_iter()
4225 .map(Scalar::Int64)
4226 .collect()
4227 })
4228 .as_slice(),
4229 Self::LazyLeftJoinDenseCycleLeftInt64 {
4230 source,
4231 left_witness,
4232 right_witness,
4233 total_len,
4234 values,
4235 ..
4236 } => values
4237 .get_or_init(|| {
4238 Self::expand_left_join_dense_cycle_left_i64(
4239 source,
4240 *left_witness,
4241 *right_witness,
4242 *total_len,
4243 )
4244 .into_iter()
4245 .map(Scalar::Int64)
4246 .collect()
4247 })
4248 .as_slice(),
4249 Self::LazyNullableDenseCycleProbeBuildInt64 {
4250 source,
4251 probe_witness,
4252 build_witness,
4253 total_len,
4254 values,
4255 } => values
4256 .get_or_init(|| {
4257 let mut out = Vec::with_capacity(*total_len);
4258 for probe_pos in 0..probe_witness.len {
4259 let key = Self::dense_cycle_key_at(*probe_witness, probe_pos);
4260 if let Some((mut build_pos, count)) =
4261 build_witness.offset_count_for_key(key)
4262 {
4263 for _ in 0..count {
4264 out.push(Scalar::Int64(source[build_pos]));
4265 build_pos += build_witness.period;
4266 }
4267 } else {
4268 out.push(Scalar::Null(NullKind::Null));
4269 }
4270 }
4271 debug_assert_eq!(out.len(), *total_len);
4272 out
4273 })
4274 .as_slice(),
4275 Self::LazyLeftJoinDenseCycleRightInt64 {
4276 source,
4277 left_witness,
4278 right_witness,
4279 total_len,
4280 values,
4281 ..
4282 } => values
4283 .get_or_init(|| {
4284 let mut out = Vec::with_capacity(*total_len);
4285 for left_pos in 0..left_witness.len {
4286 let key = Self::dense_cycle_key_at(*left_witness, left_pos);
4287 if let Some((mut right_pos, right_count)) =
4288 right_witness.offset_count_for_key(key)
4289 {
4290 for _ in 0..right_count {
4291 out.push(Scalar::Int64(source[right_pos]));
4292 right_pos += right_witness.period;
4293 }
4294 } else {
4295 out.push(Scalar::Null(NullKind::Null));
4296 }
4297 }
4298 debug_assert_eq!(out.len(), *total_len);
4299 out
4300 })
4301 .as_slice(),
4302 Self::LazyNullableRepeatPositionsI64AsFloat64 {
4303 source,
4304 run_positions,
4305 run_valid,
4306 run_lens,
4307 total_len,
4308 values,
4309 } => values
4310 .get_or_init(|| {
4311 let mut out = Vec::with_capacity(*total_len);
4312 for ((&source_pos, &valid), &run_len) in run_positions
4313 .iter()
4314 .zip(run_valid.iter())
4315 .zip(run_lens.iter())
4316 {
4317 if valid {
4318 out.resize(
4319 out.len() + run_len,
4320 Scalar::Float64(source[source_pos] as f64),
4321 );
4322 } else {
4323 out.resize(out.len() + run_len, Scalar::Null(NullKind::NaN));
4324 }
4325 }
4326 out
4327 })
4328 .as_slice(),
4329 Self::LazyUtf8Slice {
4330 bytes,
4331 offsets,
4332 start,
4333 len,
4334 values,
4335 } => values
4336 .get_or_init(|| {
4337 (0..*len)
4338 .map(|i| {
4339 let lo = offsets[start + i];
4340 let hi = offsets[start + i + 1];
4341 Scalar::Utf8(
4342 std::str::from_utf8(&bytes[lo..hi])
4343 .expect("contiguous utf8 buffer is valid by construction")
4344 .to_owned(),
4345 )
4346 })
4347 .collect()
4348 })
4349 .as_slice(),
4350 }
4351 }
4352
4353 fn len(&self) -> usize {
4354 match self {
4355 Self::Eager(values) => values.len(),
4356 Self::LazyAllValidInt64 { data, .. } => data.len(),
4357 Self::LazyAllValidInt64Chunks { len, .. } => *len,
4358 Self::LazyAllValidDatetime64 { data, .. } => data.len(),
4359 Self::LazyAllValidFloat64 { data, .. } => data.len(),
4360 Self::LazyAllValidFloat64Chunks { len, .. } => *len,
4361 Self::LazyAllValidFloat64Slice { len, .. } => *len,
4362 Self::LazyAllValidFloat64Dot { len, .. } => *len,
4363 Self::LazyAllValidFloat64PairwiseStatMatrixColumn { plan, .. } => plan.column_len(),
4364 Self::LazyCombineFirstFloat64 { len, .. } => *len,
4365 Self::LazyStridedFloat64 { len, .. } => *len,
4366 Self::LazyNullableFloat64 { data, .. } => data.len(),
4367 Self::LazyAllValidBool { data, .. } => data.len(),
4368 Self::LazyContiguousUtf8 { offsets, .. } => offsets.len() - 1,
4369 Self::LazyLowerHexSequenceUtf8 { len, .. } => *len,
4370 Self::LazyNullableUtf8 { offsets, .. } => offsets.len() - 1,
4371 Self::LazyGatherUtf8 { positions, .. } => positions.len(),
4372 Self::LazyNullableUtf8Range {
4373 null_prefix,
4374 source_len,
4375 null_suffix,
4376 ..
4377 } => null_prefix + source_len + null_suffix,
4378 Self::LazyNullableInt64 { data, .. } => data.len(),
4379 Self::LazyNullableBool { data, .. } => data.len(),
4380 Self::LazyRepeatRunsInt64 { total_len, .. } => *total_len,
4381 Self::LazyRepeatValuesInt64 { total_len, .. } => *total_len,
4382 Self::LazyRepeatedSlicesInt64 { total_len, .. } => *total_len,
4383 Self::LazyRepeatValuesFloat64 { total_len, .. } => *total_len,
4384 Self::LazyRepeatedSlicesFloat64 { total_len, .. } => *total_len,
4385 Self::LazyNullableRepeatedSlicesInt64 { total_len, .. } => *total_len,
4386 Self::LazyNullableRepeatedSlicesFloat64 { total_len, .. } => *total_len,
4387 Self::LazyNullableRepeatValuesFloat64 { total_len, .. } => *total_len,
4388 Self::LazyNullableRepeatedPositionsI64AsFloat64 { total_len, .. } => *total_len,
4389 Self::LazyNullableDenseCycleRightI64AsFloat64 { total_len, .. } => *total_len,
4390 Self::LazyNullableDenseCycleLeftI64AsFloat64 { total_len, .. } => *total_len,
4391 Self::LazyDenseCycleProbeRepeatInt64 { total_len, .. } => *total_len,
4392 Self::LazyNullableDenseCycleProbeBuildInt64 { total_len, .. } => *total_len,
4393 Self::LazyLeftJoinDenseCycleLeftInt64 { total_len, .. } => *total_len,
4394 Self::LazyLeftJoinDenseCycleRightInt64 { total_len, .. } => *total_len,
4395 Self::LazyNullableRepeatPositionsI64AsFloat64 { total_len, .. } => *total_len,
4396 Self::LazyUtf8Slice { len, .. } => *len,
4397 }
4398 }
4399
4400 fn is_empty(&self) -> bool {
4401 self.len() == 0
4402 }
4403}
4404
4405fn contiguous_utf8_offsets_are_strictly_increasing(bytes: &[u8], offsets: &[usize]) -> bool {
4406 let Some(n) = offsets.len().checked_sub(1) else {
4407 return false;
4408 };
4409 if n < 2 {
4410 return true;
4411 }
4412
4413 let mut previous = &bytes[offsets[0]..offsets[1]];
4414 for pos in 1..n {
4415 let current = &bytes[offsets[pos]..offsets[pos + 1]];
4416 if previous >= current {
4417 return false;
4418 }
4419 previous = current;
4420 }
4421 true
4422}
4423
4424fn contiguous_utf8_fixed_width(offsets: &[usize]) -> Option<usize> {
4425 let n = offsets.len().checked_sub(1)?;
4426 if n == 0 {
4427 return Some(0);
4428 }
4429 let width = offsets[1].checked_sub(offsets[0])?;
4430 for pos in 1..n {
4431 if offsets[pos + 1].checked_sub(offsets[pos])? != width {
4432 return None;
4433 }
4434 }
4435 Some(width)
4436}
4437
4438fn lower_hex_value(byte: u8) -> Option<u8> {
4439 match byte {
4440 b'0'..=b'9' => Some(byte - b'0'),
4441 b'a'..=b'f' => Some(byte - b'a' + 10),
4442 _ => None,
4443 }
4444}
4445
4446fn parse_fixed_width_lower_hex(bytes: &[u8]) -> Option<u64> {
4447 let mut value = 0_u64;
4448 for &byte in bytes {
4449 value = value.checked_mul(16)?;
4450 value = value.checked_add(u64::from(lower_hex_value(byte)?))?;
4451 }
4452 Some(value)
4453}
4454
4455fn push_fixed_width_lower_hex(bytes: &mut Vec<u8>, value: u64, width: usize) {
4456 debug_assert!(width <= 16, "u64 lower-hex width cannot exceed 16");
4457 for shift in (0..width).rev() {
4458 let nibble = ((value >> (shift * 4)) & 0x0f) as u8;
4459 bytes.push(if nibble < 10 {
4460 b'0' + nibble
4461 } else {
4462 b'a' + (nibble - 10)
4463 });
4464 }
4465}
4466
4467fn increment_fixed_width_lower_hex(digits: &mut [u8]) {
4468 for byte in digits.iter_mut().rev() {
4469 match *byte {
4470 b'0'..=b'8' | b'a'..=b'e' => {
4471 *byte += 1;
4472 return;
4473 }
4474 b'9' => {
4475 *byte = b'a';
4476 return;
4477 }
4478 b'f' => *byte = b'0',
4479 _ => return,
4480 }
4481 }
4482}
4483
4484fn contiguous_utf8_lower_hex_sequence(
4485 bytes: &[u8],
4486 offsets: &[usize],
4487 width: usize,
4488) -> Option<Utf8LowerHexSequence> {
4489 let n = offsets.len().checked_sub(1)?;
4490 if n == 0 || width == 0 || width > 64 {
4491 return None;
4492 }
4493
4494 let first = &bytes[offsets[0]..offsets[1]];
4495 let mut hex_start = first.len();
4496 while hex_start > 0 && lower_hex_value(first[hex_start - 1]).is_some() {
4497 hex_start -= 1;
4498 }
4499 let hex_width = first.len().checked_sub(hex_start)?;
4500 if hex_width == 0 || hex_width == first.len() {
4501 return None;
4502 }
4503
4504 let prefix = &first[..hex_start];
4505 let start = parse_fixed_width_lower_hex(&first[hex_start..])?;
4506 for row in 1..n {
4507 let span = &bytes[offsets[row]..offsets[row + 1]];
4508 if span.len() != width || &span[..hex_start] != prefix {
4509 return None;
4510 }
4511 let value = parse_fixed_width_lower_hex(&span[hex_start..])?;
4512 if value != start.checked_add(row as u64)? {
4513 return None;
4514 }
4515 }
4516
4517 Some(Utf8LowerHexSequence {
4518 prefix_len: hex_start,
4519 hex_width,
4520 start,
4521 })
4522}
4523
4524fn contiguous_ascending_start(positions: &[usize]) -> Option<usize> {
4530 let first = *positions.first()?;
4531 for (i, &pos) in positions.iter().enumerate() {
4532 if pos != first + i {
4533 return None;
4534 }
4535 }
4536 Some(first)
4537}
4538
4539impl Clone for ScalarValues {
4540 fn clone(&self) -> Self {
4541 match self {
4542 Self::Eager(values) => Self::Eager(values.clone()),
4543 Self::LazyAllValidInt64 { data, .. } => {
4544 Self::lazy_all_valid_int64_arc(Arc::clone(data))
4545 }
4546 Self::LazyAllValidInt64Chunks {
4547 chunks,
4548 len,
4549 dense_cycle,
4550 ..
4551 } => {
4552 let cloned = Self::lazy_all_valid_int64_chunks(Arc::clone(chunks), *len);
4553 if let Self::LazyAllValidInt64Chunks {
4554 dense_cycle: cloned_cycle,
4555 ..
4556 } = &cloned
4557 && let Some(value) = dense_cycle.get().copied()
4558 {
4559 let _ = cloned_cycle.set(value);
4560 }
4561 cloned
4562 }
4563 Self::LazyAllValidDatetime64 { data, .. } => {
4564 Self::lazy_all_valid_datetime64_arc(Arc::clone(data))
4565 }
4566 Self::LazyAllValidFloat64 {
4567 data, all_finite, ..
4568 } => Self::lazy_all_valid_float64_arc_with_finite(
4569 Arc::clone(data),
4570 all_finite.get().copied(),
4571 ),
4572 Self::LazyAllValidFloat64Chunks {
4573 chunks,
4574 len,
4575 all_finite,
4576 ..
4577 } => {
4578 let cloned = Self::lazy_all_valid_float64_chunks(Arc::clone(chunks), *len);
4579 if let Self::LazyAllValidFloat64Chunks {
4580 all_finite: cloned_finite,
4581 ..
4582 } = &cloned
4583 && let Some(value) = all_finite.get().copied()
4584 {
4585 let _ = cloned_finite.set(value);
4586 }
4587 cloned
4588 }
4589 Self::LazyAllValidFloat64Slice {
4590 data,
4591 start,
4592 len,
4593 all_finite,
4594 ..
4595 } => Self::lazy_all_valid_float64_slice_with_finite(
4596 Arc::clone(data),
4597 *start,
4598 *len,
4599 all_finite.get().copied(),
4600 ),
4601 Self::LazyAllValidFloat64Dot {
4602 a_cols, b_col, len, ..
4603 } => Self::lazy_all_valid_float64_dot(Arc::clone(a_cols), Arc::clone(b_col), *len),
4604 Self::LazyAllValidFloat64PairwiseStatMatrixColumn { plan, col, .. } => {
4605 Self::lazy_all_valid_float64_pairwise_stat_matrix_column(Arc::clone(plan), *col)
4606 }
4607 Self::LazyCombineFirstFloat64 {
4608 left,
4609 right,
4610 left_validity_words,
4611 len,
4612 ..
4613 } => Self::lazy_combine_first_float64(
4614 Arc::clone(left),
4615 Arc::clone(right),
4616 Arc::clone(left_validity_words),
4617 *len,
4618 ),
4619 Self::LazyStridedFloat64 {
4620 data,
4621 start,
4622 step,
4623 len,
4624 ..
4625 } => Self::lazy_strided_float64(Arc::clone(data), *start, *step, *len),
4626 Self::LazyNullableFloat64 { data, validity, .. } => {
4627 Self::lazy_nullable_float64(data.clone(), validity.clone())
4628 }
4629 Self::LazyAllValidBool { data, .. } => Self::lazy_all_valid_bool_arc(Arc::clone(data)),
4630 Self::LazyContiguousUtf8 { bytes, offsets, .. } => {
4631 Self::lazy_contiguous_utf8_arc(Arc::clone(bytes), Arc::clone(offsets))
4632 }
4633 Self::LazyLowerHexSequenceUtf8 {
4634 prefix,
4635 start,
4636 len,
4637 hex_width,
4638 ..
4639 } => Self::LazyLowerHexSequenceUtf8 {
4640 prefix: Arc::clone(prefix),
4641 start: *start,
4642 len: *len,
4643 hex_width: *hex_width,
4644 buffers: OnceLock::new(),
4645 values: OnceLock::new(),
4646 },
4647 Self::LazyNullableUtf8 {
4648 bytes,
4649 offsets,
4650 validity,
4651 ..
4652 } => Self::LazyNullableUtf8 {
4653 bytes: Arc::clone(bytes),
4654 offsets: Arc::clone(offsets),
4655 validity: validity.clone(),
4656 values: OnceLock::new(),
4657 },
4658 Self::LazyGatherUtf8 {
4659 source, positions, ..
4660 } => Self::lazy_gather_utf8(Arc::clone(source), Arc::clone(positions)),
4661 Self::LazyNullableUtf8Range {
4662 source,
4663 null_prefix,
4664 source_start,
4665 source_len,
4666 null_suffix,
4667 ..
4668 } => Self::lazy_nullable_utf8_range(
4669 Arc::clone(source),
4670 *null_prefix,
4671 *source_start,
4672 *source_len,
4673 *null_suffix,
4674 ),
4675 Self::LazyNullableInt64 { data, validity, .. } => {
4676 Self::lazy_nullable_int64(data.clone(), validity.clone())
4677 }
4678 Self::LazyNullableBool { data, validity, .. } => {
4679 Self::lazy_nullable_bool(data.clone(), validity.clone())
4680 }
4681 Self::LazyRepeatRunsInt64 {
4682 runs, total_len, ..
4683 } => Self::lazy_repeat_runs_int64(runs.clone(), *total_len),
4684 Self::LazyRepeatValuesInt64 {
4685 run_values,
4686 run_lens,
4687 total_len,
4688 ..
4689 } => {
4690 Self::lazy_repeat_values_int64(run_values.clone(), Arc::clone(run_lens), *total_len)
4691 }
4692 Self::LazyRepeatedSlicesInt64 {
4693 data,
4694 segments,
4695 total_len,
4696 ..
4697 } => Self::lazy_repeated_slices_int64_shared(
4698 data.clone(),
4699 Arc::clone(segments),
4700 *total_len,
4701 ),
4702 Self::LazyRepeatValuesFloat64 {
4703 run_values,
4704 run_lens,
4705 total_len,
4706 ..
4707 } => Self::lazy_repeat_values_float64(
4708 run_values.clone(),
4709 Arc::clone(run_lens),
4710 *total_len,
4711 ),
4712 Self::LazyRepeatedSlicesFloat64 {
4713 data,
4714 segments,
4715 total_len,
4716 ..
4717 } => Self::lazy_repeated_slices_float64_shared(
4718 data.clone(),
4719 Arc::clone(segments),
4720 *total_len,
4721 ),
4722 Self::LazyNullableRepeatedSlicesInt64 {
4723 data,
4724 segments,
4725 total_len,
4726 ..
4727 } => Self::lazy_nullable_repeated_slices_int64(
4728 data.clone(),
4729 Arc::clone(segments),
4730 *total_len,
4731 ),
4732 Self::LazyNullableRepeatedSlicesFloat64 {
4733 data,
4734 segments,
4735 total_len,
4736 ..
4737 } => Self::lazy_nullable_repeated_slices_float64(
4738 data.clone(),
4739 Arc::clone(segments),
4740 *total_len,
4741 ),
4742 Self::LazyNullableRepeatValuesFloat64 {
4743 run_values,
4744 run_valid,
4745 run_lens,
4746 total_len,
4747 ..
4748 } => Self::lazy_nullable_repeat_values_float64(
4749 run_values.clone(),
4750 Arc::clone(run_valid),
4751 Arc::clone(run_lens),
4752 *total_len,
4753 ),
4754 Self::LazyNullableRepeatedPositionsI64AsFloat64 {
4755 source,
4756 positions,
4757 segments,
4758 total_len,
4759 ..
4760 } => Self::lazy_nullable_repeated_positions_i64_as_float64(
4761 Arc::clone(source),
4762 Arc::clone(positions),
4763 Arc::clone(segments),
4764 *total_len,
4765 ),
4766 Self::LazyNullableDenseCycleRightI64AsFloat64 {
4767 source,
4768 left_witness,
4769 right_witness,
4770 min_key,
4771 span,
4772 total_len,
4773 ..
4774 } => Self::lazy_nullable_dense_cycle_right_i64_as_float64(
4775 Arc::clone(source),
4776 *left_witness,
4777 *right_witness,
4778 *min_key,
4779 *span,
4780 *total_len,
4781 ),
4782 Self::LazyNullableDenseCycleLeftI64AsFloat64 {
4783 source,
4784 left_witness,
4785 right_witness,
4786 min_key,
4787 span,
4788 total_len,
4789 ..
4790 } => Self::lazy_nullable_dense_cycle_left_i64_as_float64(
4791 Arc::clone(source),
4792 *left_witness,
4793 *right_witness,
4794 *min_key,
4795 *span,
4796 *total_len,
4797 ),
4798 Self::LazyDenseCycleProbeRepeatInt64 {
4799 source,
4800 probe_witness,
4801 build_witness,
4802 total_len,
4803 ..
4804 } => Self::lazy_dense_cycle_probe_repeat_int64(
4805 Arc::clone(source),
4806 *probe_witness,
4807 *build_witness,
4808 *total_len,
4809 ),
4810 Self::LazyNullableDenseCycleProbeBuildInt64 {
4811 source,
4812 probe_witness,
4813 build_witness,
4814 total_len,
4815 ..
4816 } => Self::lazy_nullable_dense_cycle_probe_build_int64(
4817 Arc::clone(source),
4818 *probe_witness,
4819 *build_witness,
4820 *total_len,
4821 ),
4822 Self::LazyLeftJoinDenseCycleLeftInt64 {
4823 source,
4824 left_witness,
4825 right_witness,
4826 total_len,
4827 ..
4828 } => Self::lazy_left_join_dense_cycle_left_int64(
4829 Arc::clone(source),
4830 *left_witness,
4831 *right_witness,
4832 *total_len,
4833 ),
4834 Self::LazyLeftJoinDenseCycleRightInt64 {
4835 source,
4836 left_witness,
4837 right_witness,
4838 total_len,
4839 ..
4840 } => Self::lazy_left_join_dense_cycle_right_int64(
4841 Arc::clone(source),
4842 *left_witness,
4843 *right_witness,
4844 *total_len,
4845 ),
4846 Self::LazyNullableRepeatPositionsI64AsFloat64 {
4847 source,
4848 run_positions,
4849 run_valid,
4850 run_lens,
4851 total_len,
4852 ..
4853 } => Self::lazy_nullable_repeat_positions_i64_as_float64(
4854 Arc::clone(source),
4855 Arc::clone(run_positions),
4856 Arc::clone(run_valid),
4857 Arc::clone(run_lens),
4858 *total_len,
4859 ),
4860 Self::LazyUtf8Slice {
4861 bytes,
4862 offsets,
4863 start,
4864 len,
4865 ..
4866 } => Self::lazy_utf8_slice(Arc::clone(bytes), Arc::clone(offsets), *start, *len),
4867 }
4868 }
4869}
4870
4871impl std::ops::Deref for ScalarValues {
4872 type Target = [Scalar];
4873
4874 fn deref(&self) -> &Self::Target {
4875 self.as_slice()
4876 }
4877}
4878
4879impl<'a> IntoIterator for &'a ScalarValues {
4880 type Item = &'a Scalar;
4881 type IntoIter = std::slice::Iter<'a, Scalar>;
4882
4883 fn into_iter(self) -> Self::IntoIter {
4884 self.as_slice().iter()
4885 }
4886}
4887
4888impl PartialEq for ScalarValues {
4889 fn eq(&self, other: &Self) -> bool {
4890 self.as_slice() == other.as_slice()
4891 }
4892}
4893
4894impl std::fmt::Debug for ScalarValues {
4895 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4896 self.as_slice().fmt(f)
4897 }
4898}
4899
4900impl Serialize for ScalarValues {
4901 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4902 self.as_slice().serialize(serializer)
4903 }
4904}
4905
4906impl<'de> Deserialize<'de> for ScalarValues {
4907 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4908 Vec::<Scalar>::deserialize(deserializer).map(|v| Self::Eager(Arc::from(v)))
4909 }
4910}
4911
4912#[derive(Serialize, Deserialize)]
4913pub struct Column {
4914 dtype: DType,
4915 values: ScalarValues,
4916 validity: ValidityMask,
4917 #[serde(skip)]
4918 data: Option<ColumnData>,
4919}
4920
4921impl Clone for Column {
4922 fn clone(&self) -> Self {
4923 Self {
4924 dtype: self.dtype,
4925 values: self
4926 .clone_dense_values_from_cache()
4927 .unwrap_or_else(|| self.values.clone()),
4928 validity: self.validity.clone(),
4929 data: None,
4930 }
4931 }
4932}
4933
4934impl PartialEq for Column {
4935 fn eq(&self, other: &Self) -> bool {
4936 self.dtype == other.dtype && self.values == other.values && self.validity == other.validity
4937 }
4938}
4939
4940impl std::fmt::Debug for Column {
4941 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4942 f.debug_struct("Column")
4943 .field("dtype", &self.dtype)
4944 .field("values", &self.values)
4945 .field("validity", &self.validity)
4946 .finish()
4947 }
4948}
4949
4950#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
4951pub struct SparseColumn {
4952 dtype: SparseDType,
4953 len: usize,
4954 indices: Vec<usize>,
4955 values: Vec<Scalar>,
4956}
4957
4958#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4959#[serde(rename_all = "snake_case")]
4960pub enum ArithmeticOp {
4961 Add,
4962 Sub,
4963 Mul,
4964 Div,
4965 Mod,
4966 Pow,
4967 FloorDiv,
4968}
4969
4970#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4975#[serde(rename_all = "snake_case")]
4976pub enum ComparisonOp {
4977 Gt,
4978 Lt,
4979 Eq,
4980 Ne,
4981 Ge,
4982 Le,
4983}
4984
4985fn nkeep_impl(col: &Column, n: usize, keep: &str, ascending: bool) -> Result<Column, ColumnError> {
4986 if !matches!(keep, "first" | "last" | "all") {
4987 return Err(ColumnError::Type(TypeError::NonNumericValue {
4988 value: keep.to_string(),
4989 dtype: col.dtype(),
4990 }));
4991 }
4992 let mut indexed: Vec<(usize, &Scalar)> = col.values().iter().enumerate().collect();
4996 indexed.sort_by(|a, b| {
4997 let primary = compare_scalars_na_last(a.1, b.1, ascending);
4998 match (primary, keep) {
4999 (std::cmp::Ordering::Equal, "last") => b.0.cmp(&a.0),
5001 (std::cmp::Ordering::Equal, _) => a.0.cmp(&b.0),
5002 _ => primary,
5003 }
5004 });
5005 let take = n.min(indexed.len());
5006 let mut end = take;
5007 if keep == "all" && take > 0 && take < indexed.len() {
5008 let boundary = indexed[take - 1].1;
5009 while end < indexed.len() {
5010 let same = compare_scalars_na_last(indexed[end].1, boundary, ascending).is_eq();
5011 if !same {
5012 break;
5013 }
5014 end += 1;
5015 }
5016 }
5017 let values: Vec<Scalar> = indexed[..end].iter().map(|(_, v)| (*v).clone()).collect();
5018 Column::new(col.dtype(), values)
5019}
5020
5021fn is_monotonic_in_direction(values: &[Scalar], increasing: bool) -> bool {
5022 let mut prev: Option<&Scalar> = None;
5023 for v in values {
5024 if v.is_missing() {
5025 continue;
5026 }
5027 if let Some(p) = prev {
5028 let ord = compare_scalars_na_last(p, v, true);
5029 let ok = matches!(
5033 (ord, increasing),
5034 (std::cmp::Ordering::Less, true)
5035 | (std::cmp::Ordering::Equal, _)
5036 | (std::cmp::Ordering::Greater, false)
5037 );
5038 if !ok {
5039 return false;
5040 }
5041 }
5042 prev = Some(v);
5043 }
5044 true
5045}
5046
5047fn compare_scalars_na_last(left: &Scalar, right: &Scalar, ascending: bool) -> std::cmp::Ordering {
5048 use std::cmp::Ordering;
5049 match (left.is_missing(), right.is_missing()) {
5050 (true, true) => Ordering::Equal,
5051 (true, false) => Ordering::Greater,
5053 (false, true) => Ordering::Less,
5054 (false, false) => {
5055 let ord = match (left, right) {
5056 (Scalar::Int64(a), Scalar::Int64(b)) => a.cmp(b),
5057 (Scalar::Float64(a), Scalar::Float64(b)) => {
5058 a.partial_cmp(b).unwrap_or(Ordering::Equal)
5059 }
5060 (Scalar::Bool(a), Scalar::Bool(b)) => a.cmp(b),
5061 (Scalar::Utf8(a), Scalar::Utf8(b)) => a.cmp(b),
5062 (Scalar::Timedelta64(a), Scalar::Timedelta64(b)) => a.cmp(b),
5063 (a, b) => match (a.to_f64(), b.to_f64()) {
5064 (Ok(af), Ok(bf)) => af.partial_cmp(&bf).unwrap_or(Ordering::Equal),
5065 _ => Ordering::Equal,
5066 },
5067 };
5068 if ascending { ord } else { ord.reverse() }
5069 }
5070 }
5071}
5072
5073#[derive(Clone, Copy)]
5075enum DupPolicy {
5076 First,
5077 Last,
5078 None,
5079}
5080
5081fn duplicated_flags_typed<T>(keys: &[T], policy: DupPolicy) -> Vec<bool>
5087where
5088 T: std::hash::Hash + Eq + Copy,
5089{
5090 let n = keys.len();
5091 let mut flags = vec![false; n];
5092 match policy {
5093 DupPolicy::First => {
5094 let mut seen: FxHashSet<T> = FxHashSet::with_capacity_and_hasher(n, Default::default());
5095 for (idx, &k) in keys.iter().enumerate() {
5096 flags[idx] = !seen.insert(k);
5097 }
5098 }
5099 DupPolicy::Last => {
5100 let mut seen: FxHashSet<T> = FxHashSet::with_capacity_and_hasher(n, Default::default());
5101 for (idx, &k) in keys.iter().enumerate().rev() {
5102 flags[idx] = !seen.insert(k);
5103 }
5104 }
5105 DupPolicy::None => {
5106 let mut seen_once: FxHashSet<T> =
5107 FxHashSet::with_capacity_and_hasher(n, Default::default());
5108 let mut seen_multiple: FxHashSet<T> = FxHashSet::default();
5109 for &k in keys {
5110 if !seen_once.insert(k) {
5111 seen_multiple.insert(k);
5112 }
5113 }
5114 for (idx, &k) in keys.iter().enumerate() {
5115 flags[idx] = seen_multiple.contains(&k);
5116 }
5117 }
5118 }
5119 flags
5120}
5121
5122const DUP_DIRECT_ADDRESS_CAP: u128 = 1 << 24;
5127
5128fn i64_direct_address_range(data: &[i64]) -> Option<(i64, usize)> {
5133 let mut min = data.first().copied()?;
5134 let mut max = min;
5135 for &v in &data[1..] {
5136 if v < min {
5137 min = v;
5138 } else if v > max {
5139 max = v;
5140 }
5141 }
5142 let range = (max as i128 - min as i128 + 1) as u128;
5143 if range <= DUP_DIRECT_ADDRESS_CAP && range <= (data.len() as u128).saturating_mul(16) {
5144 Some((min, range as usize))
5145 } else {
5146 None
5147 }
5148}
5149
5150fn duplicated_flags_i64_direct(
5155 data: &[i64],
5156 min: i64,
5157 range: usize,
5158 policy: DupPolicy,
5159) -> Vec<bool> {
5160 let n = data.len();
5161 let mut flags = vec![false; n];
5162 let slot = |v: i64| (v as i128 - min as i128) as usize;
5163 match policy {
5164 DupPolicy::First => {
5165 let mut seen = vec![false; range];
5166 for (idx, &v) in data.iter().enumerate() {
5167 let s = slot(v);
5168 flags[idx] = seen[s];
5169 seen[s] = true;
5170 }
5171 }
5172 DupPolicy::Last => {
5173 let mut seen = vec![false; range];
5174 for (idx, &v) in data.iter().enumerate().rev() {
5175 let s = slot(v);
5176 flags[idx] = seen[s];
5177 seen[s] = true;
5178 }
5179 }
5180 DupPolicy::None => {
5181 let mut count = vec![0u8; range];
5183 for &v in data {
5184 let s = slot(v);
5185 if count[s] < 2 {
5186 count[s] += 1;
5187 }
5188 }
5189 for (idx, &v) in data.iter().enumerate() {
5190 flags[idx] = count[slot(v)] > 1;
5191 }
5192 }
5193 }
5194 flags
5195}
5196
5197#[inline]
5200fn i64_radix_key(value: i64) -> u64 {
5201 (value as u64) ^ (1u64 << 63)
5202}
5203
5204#[inline]
5212fn f64_radix_key(value: f64) -> u64 {
5213 let bits = (if value == 0.0 { 0.0 } else { value }).to_bits();
5214 if bits & (1u64 << 63) != 0 {
5215 !bits
5216 } else {
5217 bits | (1u64 << 63)
5218 }
5219}
5220
5221fn radix_argsort_u64(keys: &[u64]) -> Vec<usize> {
5228 let n = keys.len();
5229 let mut idx: Vec<usize> = (0..n).collect();
5230 if n < 2 {
5231 return idx;
5232 }
5233 let mut scratch: Vec<usize> = vec![0; n];
5234 for shift in (0..64).step_by(8) {
5235 let mut count = [0usize; 256];
5236 for &k in keys {
5237 count[((k >> shift) & 0xff) as usize] += 1;
5238 }
5239 if count.contains(&n) {
5242 continue;
5243 }
5244 let mut running = 0usize;
5245 for slot in &mut count {
5246 let c = *slot;
5247 *slot = running;
5248 running += c;
5249 }
5250 for &i in &idx {
5251 let bucket = ((keys[i] >> shift) & 0xff) as usize;
5252 scratch[count[bucket]] = i;
5253 count[bucket] += 1;
5254 }
5255 std::mem::swap(&mut idx, &mut scratch);
5256 }
5257 idx
5258}
5259
5260#[must_use]
5268pub fn radix_argsort_i64(values: &[i64], ascending: bool) -> Vec<usize> {
5269 let keys: Vec<u64> = if ascending {
5270 values.iter().map(|&v| i64_radix_key(v)).collect()
5271 } else {
5272 values.iter().map(|&v| !i64_radix_key(v)).collect()
5273 };
5274 radix_argsort_u64(&keys)
5275}
5276
5277#[must_use]
5284pub fn radix_argsort_f64(values: &[f64], ascending: bool) -> Vec<usize> {
5285 let keys: Vec<u64> = if ascending {
5286 values.iter().map(|&v| f64_radix_key(v)).collect()
5287 } else {
5288 values.iter().map(|&v| !f64_radix_key(v)).collect()
5289 };
5290 radix_argsort_u64(&keys)
5291}
5292
5293pub fn radix_argsort_multi_u64(keys_by_col: &[Vec<u64>]) -> Vec<usize> {
5303 let n = keys_by_col.first().map_or(0, Vec::len);
5304 let mut idx: Vec<usize> = (0..n).collect();
5305 if n < 2 || keys_by_col.is_empty() {
5306 return idx;
5307 }
5308 let mut scratch: Vec<usize> = vec![0; n];
5309 for keys in keys_by_col.iter().rev() {
5310 for shift in (0..64).step_by(8) {
5311 let mut count = [0usize; 256];
5312 for &k in keys {
5313 count[((k >> shift) & 0xff) as usize] += 1;
5314 }
5315 if count.contains(&n) {
5316 continue;
5317 }
5318 let mut running = 0usize;
5319 for slot in &mut count {
5320 let c = *slot;
5321 *slot = running;
5322 running += c;
5323 }
5324 for &i in &idx {
5325 let bucket = ((keys[i] >> shift) & 0xff) as usize;
5326 scratch[count[bucket]] = i;
5327 count[bucket] += 1;
5328 }
5329 std::mem::swap(&mut idx, &mut scratch);
5330 }
5331 }
5332 idx
5333}
5334
5335pub fn utf8_msd_argsort(strs: &[&str], ascending: bool) -> Vec<usize> {
5347 let spans: Vec<&[u8]> = strs.iter().map(|s| s.as_bytes()).collect();
5348 utf8_msd_argsort_bytes(&spans, ascending)
5349}
5350
5351#[must_use]
5358pub fn utf8_msd_argsort_bytes(spans: &[&[u8]], ascending: bool) -> Vec<usize> {
5359 let n = spans.len();
5360 let mut idx: Vec<usize> = (0..n).collect();
5361 if n <= 1 {
5362 return idx;
5363 }
5364 let mut aux: Vec<usize> = vec![0; n];
5365 const PAR_MIN: usize = 1 << 15;
5366 let workers = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
5367 if n >= PAR_MIN && workers >= 2 {
5368 utf8_msd_sort_range_par(spans, &mut idx, &mut aux, 0, ascending, workers);
5369 } else {
5370 utf8_msd_sort_range(spans, &mut idx, &mut aux, 0, n, 0, ascending);
5371 }
5372 idx
5373}
5374
5375fn utf8_msd_sort_range_par(
5385 spans: &[&[u8]],
5386 idx: &mut [usize],
5387 aux: &mut [usize],
5388 depth: usize,
5389 ascending: bool,
5390 workers: usize,
5391) {
5392 const CUTOFF: usize = 48;
5393 const MAX_DEPTH: usize = 1024;
5394 const PAR_MIN: usize = 1 << 15;
5395 let n = idx.len();
5396 if n <= CUTOFF || depth >= MAX_DEPTH || n < PAR_MIN {
5397 utf8_msd_sort_range(spans, idx, aux, 0, n, depth, ascending);
5398 return;
5399 }
5400 let key = |b: &[u8]| -> usize {
5402 if depth < b.len() {
5403 if ascending {
5404 b[depth] as usize + 1
5405 } else {
5406 255 - b[depth] as usize
5407 }
5408 } else if ascending {
5409 0
5410 } else {
5411 256
5412 }
5413 };
5414 let eos_bucket = if ascending { 0 } else { 256 };
5415 let mut counts = [0usize; 258];
5416 for &i in idx.iter() {
5417 counts[key(spans[i]) + 1] += 1;
5418 }
5419 {
5425 let mut only: Option<usize> = None;
5426 let mut multi = false;
5427 for k in 0..=256usize {
5428 if counts[k + 1] != 0 {
5429 if only.is_some() {
5430 multi = true;
5431 break;
5432 }
5433 only = Some(k);
5434 }
5435 }
5436 if !multi {
5437 if let Some(k) = only
5438 && k != eos_bucket
5439 {
5440 utf8_msd_sort_range_par(spans, idx, aux, depth + 1, ascending, workers);
5441 }
5442 return;
5443 }
5444 }
5445 for k in 1..258 {
5446 counts[k] += counts[k - 1];
5447 }
5448 let mut offsets = counts;
5449 for &i in idx.iter() {
5450 let k = key(spans[i]);
5451 aux[offsets[k]] = i;
5452 offsets[k] += 1;
5453 }
5454 idx.copy_from_slice(aux);
5455 let mut buckets: Vec<(usize, usize)> = Vec::new();
5458 for k in 0..257 {
5459 if k == eos_bucket {
5460 continue;
5461 }
5462 let lo = counts[k];
5463 let hi = counts[k + 1];
5464 if hi - lo > 1 {
5465 buckets.push((lo, hi));
5466 }
5467 }
5468 if buckets.len() <= 1 {
5469 if let Some(&(lo, hi)) = buckets.first() {
5471 utf8_msd_sort_range_par(
5472 spans,
5473 &mut idx[lo..hi],
5474 &mut aux[lo..hi],
5475 depth + 1,
5476 ascending,
5477 workers,
5478 );
5479 }
5480 return;
5481 }
5482 let mut bounds: Vec<usize> = Vec::with_capacity(buckets.len() * 2 + 2);
5487 bounds.push(0);
5488 for &(lo, hi) in &buckets {
5489 if *bounds.last().expect("non-empty") != lo {
5490 bounds.push(lo);
5491 }
5492 bounds.push(hi);
5493 }
5494 if *bounds.last().expect("non-empty") != n {
5495 bounds.push(n);
5496 }
5497 let mut seg_idx: Vec<&mut [usize]> = Vec::with_capacity(bounds.len() - 1);
5499 let mut seg_aux: Vec<&mut [usize]> = Vec::with_capacity(bounds.len() - 1);
5500 let mut rem_idx: &mut [usize] = idx;
5501 let mut rem_aux: &mut [usize] = aux;
5502 let mut prev = 0usize;
5503 for &b in &bounds[1..] {
5504 let take = b - prev;
5505 prev = b;
5506 let (a, rest_i) = rem_idx.split_at_mut(take);
5507 rem_idx = rest_i;
5508 let (c, rest_a) = rem_aux.split_at_mut(take);
5509 rem_aux = rest_a;
5510 seg_idx.push(a);
5511 seg_aux.push(c);
5512 }
5513 let sortable: std::collections::HashSet<(usize, usize)> = buckets.iter().copied().collect();
5515 let mut items: Vec<(&mut [usize], &mut [usize])> = Vec::new();
5516 let mut seg_start = 0usize;
5517 for (si, (si_slice, sa_slice)) in seg_idx.into_iter().zip(seg_aux).enumerate() {
5518 let len = bounds[si + 1] - bounds[si];
5519 let span_range = (seg_start, seg_start + len);
5520 seg_start += len;
5521 if sortable.contains(&span_range) {
5522 items.push((si_slice, sa_slice));
5523 }
5524 }
5525 let wc = workers.min(items.len()).max(1);
5528 let mut groups: Vec<Vec<(&mut [usize], &mut [usize])>> = (0..wc).map(|_| Vec::new()).collect();
5529 for (i, item) in items.into_iter().enumerate() {
5530 groups[i % wc].push(item);
5531 }
5532 std::thread::scope(|scope| {
5533 for group in groups {
5534 scope.spawn(move || {
5535 for (si, sa) in group {
5536 let len = si.len();
5537 utf8_msd_sort_range(spans, si, sa, 0, len, depth + 1, ascending);
5538 }
5539 });
5540 }
5541 });
5542}
5543
5544fn utf8_msd_sort_range(
5545 spans: &[&[u8]],
5546 idx: &mut [usize],
5547 aux: &mut [usize],
5548 lo: usize,
5549 hi: usize,
5550 depth: usize,
5551 ascending: bool,
5552) {
5553 let n = hi - lo;
5554 if n <= 1 {
5555 return;
5556 }
5557 const CUTOFF: usize = 48;
5562 const MAX_DEPTH: usize = 1024;
5563 if n <= CUTOFF || depth >= MAX_DEPTH {
5564 idx[lo..hi].sort_by(|&a, &b| {
5565 let ord = spans[a][depth..].cmp(&spans[b][depth..]);
5566 if ascending { ord } else { ord.reverse() }
5567 });
5568 return;
5569 }
5570 let key = |b: &[u8]| -> usize {
5574 if depth < b.len() {
5575 if ascending {
5576 b[depth] as usize + 1
5577 } else {
5578 255 - b[depth] as usize
5579 }
5580 } else if ascending {
5581 0
5582 } else {
5583 256
5584 }
5585 };
5586 let eos_bucket = if ascending { 0 } else { 256 };
5587 let mut counts = [0usize; 258];
5588 for &i in idx[lo..hi].iter() {
5589 counts[key(spans[i]) + 1] += 1;
5590 }
5591 {
5602 let mut only: Option<usize> = None;
5603 let mut multi = false;
5604 for k in 0..=256usize {
5605 if counts[k + 1] != 0 {
5606 if only.is_some() {
5607 multi = true;
5608 break;
5609 }
5610 only = Some(k);
5611 }
5612 }
5613 if !multi {
5614 if let Some(k) = only
5615 && k != eos_bucket
5616 {
5617 utf8_msd_sort_range(spans, idx, aux, lo, hi, depth + 1, ascending);
5618 }
5619 return;
5620 }
5621 }
5622 for k in 1..258 {
5623 counts[k] += counts[k - 1];
5624 }
5625 let mut offsets = counts;
5627 for &i in idx[lo..hi].iter() {
5628 let k = key(spans[i]);
5629 aux[lo + offsets[k]] = i;
5630 offsets[k] += 1;
5631 }
5632 idx[lo..hi].copy_from_slice(&aux[lo..hi]);
5633 for k in 0..257 {
5637 if k == eos_bucket {
5638 continue;
5639 }
5640 let b_lo = lo + counts[k];
5641 let b_hi = lo + counts[k + 1];
5642 if b_hi - b_lo > 1 {
5643 utf8_msd_sort_range(spans, idx, aux, b_lo, b_hi, depth + 1, ascending);
5644 }
5645 }
5646}
5647
5648fn normalized_float_bits(value: f64) -> u64 {
5649 let normalized = if value == 0.0 { 0.0 } else { value };
5650 normalized.to_bits()
5651}
5652
5653fn interval_key(interval: &Interval) -> (u64, u64, IntervalClosed) {
5654 (
5655 normalized_float_bits(interval.left),
5656 normalized_float_bits(interval.right),
5657 interval.closed,
5658 )
5659}
5660
5661#[derive(Hash, PartialEq, Eq)]
5670enum SetMemberKey<'a> {
5671 Bool(bool),
5672 Int64(i64),
5673 FloatBits(u64),
5674 Utf8(&'a str),
5675 Timedelta64(i64),
5676 Datetime64(i64),
5677 Period(i64, PeriodFreq),
5678 Interval(u64, u64, IntervalClosed),
5679}
5680
5681fn set_member_key(v: &Scalar) -> Option<SetMemberKey<'_>> {
5682 Some(match v {
5683 Scalar::Bool(b) => SetMemberKey::Bool(*b),
5684 Scalar::Int64(i) => SetMemberKey::Int64(*i),
5685 Scalar::Float64(f) => {
5686 let norm = if *f == 0.0 { 0.0 } else { *f };
5687 SetMemberKey::FloatBits(norm.to_bits())
5688 }
5689 Scalar::Utf8(s) => SetMemberKey::Utf8(s.as_str()),
5690 Scalar::Timedelta64(v) => SetMemberKey::Timedelta64(*v),
5691 Scalar::Datetime64(v) => SetMemberKey::Datetime64(*v),
5692 Scalar::Period(p) => SetMemberKey::Period(p.ordinal, p.freq),
5693 Scalar::Interval(v) => {
5694 let (left, right, closed) = interval_key(v);
5695 SetMemberKey::Interval(left, right, closed)
5696 }
5697 Scalar::Null(_) => return None,
5698 })
5699}
5700
5701#[derive(Debug, Error, Clone, PartialEq)]
5702pub enum ColumnError {
5703 #[error("column length mismatch: left={left}, right={right}")]
5704 LengthMismatch { left: usize, right: usize },
5705 #[error("{operation} requires exactly {expected} element(s), got {actual}")]
5706 InvalidLength {
5707 operation: &'static str,
5708 expected: usize,
5709 actual: usize,
5710 },
5711 #[error("invalid sorter permutation for column of length {len}: {reason}")]
5712 InvalidSorter { len: usize, reason: String },
5713 #[error("mask must be Bool dtype; found {dtype:?}")]
5714 InvalidMaskType { dtype: DType },
5715 #[error("column dtype mismatch: left={left:?}, right={right:?}")]
5716 DTypeMismatch { left: DType, right: DType },
5717 #[error("Integers to negative integer powers are not allowed.")]
5718 NegativeIntegerPower,
5719 #[error(transparent)]
5720 Type(#[from] TypeError),
5721}
5722
5723impl SparseColumn {
5724 pub fn from_dense(dtype: SparseDType, values: Vec<Scalar>) -> Result<Self, ColumnError> {
5725 let len = values.len();
5726 let value_dtype = dtype.value_dtype;
5727 let fill_value = dtype.fill_value.clone();
5728 let mut indices = Vec::new();
5729 let mut sparse_values = Vec::new();
5730
5731 for (idx, value) in values.into_iter().enumerate() {
5732 let value = if value.dtype() == value_dtype || value.dtype() == DType::Null {
5733 Column::normalize_missing_for_dtype(value, value_dtype)
5734 } else {
5735 cast_scalar_owned(value, value_dtype)?
5736 };
5737
5738 if !value.semantic_eq(&fill_value) {
5739 indices.push(idx);
5740 sparse_values.push(value);
5741 }
5742 }
5743
5744 Ok(Self {
5745 dtype,
5746 len,
5747 indices,
5748 values: sparse_values,
5749 })
5750 }
5751
5752 pub fn from_dense_column(dtype: SparseDType, column: &Column) -> Result<Self, ColumnError> {
5753 Self::from_dense(dtype, column.values().to_vec())
5754 }
5755
5756 #[must_use]
5757 pub fn sparse_dtype(&self) -> &SparseDType {
5758 &self.dtype
5759 }
5760
5761 #[must_use]
5762 pub fn value_dtype(&self) -> DType {
5763 self.dtype.value_dtype
5764 }
5765
5766 #[must_use]
5767 pub fn fill_value(&self) -> &Scalar {
5768 &self.dtype.fill_value
5769 }
5770
5771 #[must_use]
5772 pub fn len(&self) -> usize {
5773 self.len
5774 }
5775
5776 #[must_use]
5777 pub fn is_empty(&self) -> bool {
5778 self.len == 0
5779 }
5780
5781 #[must_use]
5782 pub fn indices(&self) -> &[usize] {
5783 &self.indices
5784 }
5785
5786 #[must_use]
5787 pub fn stored_values(&self) -> &[Scalar] {
5788 &self.values
5789 }
5790
5791 #[must_use]
5792 pub fn npoints(&self) -> usize {
5793 self.values.len()
5794 }
5795
5796 #[must_use]
5797 pub fn density(&self) -> f64 {
5798 if self.len == 0 {
5799 0.0
5800 } else {
5801 self.values.len() as f64 / self.len as f64
5802 }
5803 }
5804
5805 #[must_use]
5806 pub fn to_dense_values(&self) -> Vec<Scalar> {
5807 let mut values = vec![self.dtype.fill_value.clone(); self.len];
5808 for (&idx, value) in self.indices.iter().zip(self.values.iter()) {
5809 values[idx] = value.clone();
5810 }
5811 values
5812 }
5813
5814 pub fn to_dense_column(&self) -> Result<Column, ColumnError> {
5815 Column::new(self.dtype.value_dtype, self.to_dense_values())
5816 }
5817}
5818
5819fn saturating_i64_to_usize(value: i64) -> usize {
5820 if value <= 0 {
5821 0
5822 } else {
5823 usize::try_from(value).unwrap_or(usize::MAX)
5824 }
5825}
5826
5827fn saturating_i64_abs_to_usize(value: i64) -> usize {
5828 usize::try_from(value.unsigned_abs()).unwrap_or(usize::MAX)
5829}
5830
5831fn normalize_head_take(n: i64, len: usize) -> usize {
5832 if n >= 0 {
5833 saturating_i64_to_usize(n).min(len)
5834 } else {
5835 len.saturating_sub(saturating_i64_abs_to_usize(n))
5836 }
5837}
5838
5839fn normalize_tail_window(n: i64, len: usize) -> (usize, usize) {
5840 if n >= 0 {
5841 let take = saturating_i64_to_usize(n).min(len);
5842 (len - take, take)
5843 } else {
5844 let skip = saturating_i64_abs_to_usize(n).min(len);
5845 (skip, len - skip)
5846 }
5847}
5848
5849fn round_i64_negative_decimals(value: i64, decimals: i32) -> i64 {
5850 debug_assert!(decimals < 0);
5851 let factor = match 10_i128.checked_pow(decimals.unsigned_abs()) {
5852 Some(factor) => factor,
5853 None => return 0,
5854 };
5855 let magnitude = i128::from(value).abs();
5856 let quotient = magnitude / factor;
5857 let remainder = magnitude % factor;
5858 let rounded_magnitude = match (remainder * 2).cmp(&factor) {
5859 std::cmp::Ordering::Less => quotient * factor,
5860 std::cmp::Ordering::Greater => (quotient + 1) * factor,
5861 std::cmp::Ordering::Equal if quotient % 2 == 0 => quotient * factor,
5862 std::cmp::Ordering::Equal => (quotient + 1) * factor,
5863 };
5864 let rounded = if value < 0 {
5865 -rounded_magnitude
5866 } else {
5867 rounded_magnitude
5868 };
5869 match i64::try_from(rounded) {
5870 Ok(value) => value,
5871 Err(_) if rounded < 0 => i64::MIN,
5872 Err(_) => i64::MAX,
5873 }
5874}
5875
5876impl Column {
5877 fn clone_dense_values_from_cache(&self) -> Option<ScalarValues> {
5878 if self.validity.len() != self.values.len()
5879 || self.validity.count_valid() != self.values.len()
5880 {
5881 return None;
5882 }
5883
5884 match (&self.data, self.dtype) {
5885 (Some(ColumnData::Bool(data)), DType::Bool) if data.len() == self.values.len() => {
5886 Some(ScalarValues::lazy_all_valid_bool_arc(Arc::clone(data)))
5895 }
5896 (Some(ColumnData::Int64(data)), DType::Int64) if data.len() == self.values.len() => {
5897 Some(ScalarValues::lazy_all_valid_int64_arc(Arc::clone(data)))
5907 }
5908 (Some(ColumnData::Float64(data)), DType::Float64)
5909 if data.len() == self.values.len() =>
5910 {
5911 Some(ScalarValues::lazy_all_valid_float64_arc_with_finite(
5912 Arc::clone(data),
5913 Some(data.iter().all(|value| value.is_finite())),
5914 ))
5915 }
5916 (Some(ColumnData::Timedelta64(data)), DType::Timedelta64)
5917 if data.len() == self.values.len() =>
5918 {
5919 Some(ScalarValues::from_vec(
5920 data.iter().copied().map(Scalar::Timedelta64).collect(),
5921 ))
5922 }
5923 (Some(ColumnData::Datetime64(data)), DType::Datetime64)
5924 if data.len() == self.values.len() =>
5925 {
5926 Some(ScalarValues::from_vec(
5927 data.iter().copied().map(Scalar::Datetime64).collect(),
5928 ))
5929 }
5930 (Some(ColumnData::Period(data, freq)), DType::Period)
5931 if data.len() == self.values.len() =>
5932 {
5933 let freq = *freq;
5934 Some(ScalarValues::from_vec(
5935 data.iter()
5936 .copied()
5937 .map(|ord| Scalar::Period(Period::new(ord, freq)))
5938 .collect(),
5939 ))
5940 }
5941 _ => None,
5942 }
5943 }
5944
5945 fn cached_data_for_values(dtype: DType, values: &[Scalar]) -> Option<ColumnData> {
5946 match dtype {
5947 DType::Bool
5948 | DType::BoolNullable
5949 | DType::Int64
5950 | DType::Int64Nullable
5951 | DType::Float64
5952 | DType::Timedelta64
5953 | DType::Datetime64
5954 | DType::Period => Some(ColumnData::from_scalars(values, dtype)),
5955 _ => None,
5956 }
5957 }
5958
5959 fn normalize_missing_for_dtype(value: Scalar, dtype: DType) -> Scalar {
5960 match value {
5961 Scalar::Null(NullKind::NaN) => Scalar::Null(NullKind::NaN),
5962 Scalar::Null(NullKind::NaT) => Scalar::Null(NullKind::NaT),
5963 Scalar::Null(_) => Scalar::missing_for_dtype(dtype),
5964 other => other,
5965 }
5966 }
5967
5968 fn from_object_values(values: Vec<Scalar>) -> Self {
5969 let validity = ValidityMask::from_values(&values);
5970 Self {
5971 dtype: DType::Utf8,
5972 values: ScalarValues::from_vec(values),
5973 validity,
5974 data: None,
5975 }
5976 }
5977
5978 pub fn new(dtype: DType, values: Vec<Scalar>) -> Result<Self, ColumnError> {
5982 let preserve_utf8_object_bucket = matches!(dtype, DType::Utf8)
5983 && values.iter().any(|value| matches!(value, Scalar::Utf8(_)))
5984 && values
5985 .iter()
5986 .any(|value| !matches!(value, Scalar::Utf8(_) | Scalar::Null(_)));
5987 let needs_coercion = values.iter().any(|v| {
5988 let d = v.dtype();
5989 d != dtype && d != DType::Null
5990 }) && !preserve_utf8_object_bucket;
5991
5992 let coerced = if preserve_utf8_object_bucket {
5993 values
5994 .into_iter()
5995 .map(|value| Self::normalize_missing_for_dtype(value, dtype))
5996 .collect()
5997 } else if needs_coercion {
5998 values
5999 .into_iter()
6000 .map(|value| {
6001 if matches!(dtype, DType::Int64 | DType::Int64Nullable)
6009 && let Scalar::Float64(v) = &value
6010 && v.is_finite()
6011 && v.fract() != 0.0
6012 {
6013 return Err(TypeError::LossyFloatToInt { value: *v });
6014 }
6015 cast_scalar_owned(value, dtype)
6016 })
6017 .collect::<Result<Vec<_>, _>>()?
6018 } else {
6019 values
6022 .into_iter()
6023 .map(|value| Self::normalize_missing_for_dtype(value, dtype))
6024 .collect()
6025 };
6026
6027 let validity = ValidityMask::from_values(&coerced);
6028 let data = Self::cached_data_for_values(dtype, &coerced);
6029 let values = match (&data, dtype, validity.all()) {
6030 (Some(ColumnData::Bool(data)), DType::Bool, true) => {
6031 ScalarValues::lazy_all_valid_bool_arc(Arc::clone(data))
6032 }
6033 (Some(ColumnData::Int64(data)), DType::Int64, true) => {
6034 ScalarValues::lazy_all_valid_int64_arc(Arc::clone(data))
6035 }
6036 _ => ScalarValues::from_vec(coerced),
6037 };
6038
6039 Ok(Self {
6040 dtype,
6041 validity,
6042 data,
6043 values,
6044 })
6045 }
6046
6047 fn from_inferred_float64_values(values: Vec<Scalar>) -> Result<Self, ColumnError> {
6048 let coerced = values
6049 .into_iter()
6050 .map(|value| match value {
6051 Scalar::Null(kind) => Ok(Scalar::Null(kind)),
6052 other => cast_scalar_owned(other, DType::Float64),
6053 })
6054 .collect::<Result<Vec<_>, _>>()?;
6055 let validity = ValidityMask::from_values(&coerced);
6056 let data = Self::cached_data_for_values(DType::Float64, &coerced);
6057 let values = match (&data, validity.all()) {
6058 (Some(ColumnData::Float64(data)), true) => {
6059 ScalarValues::lazy_all_valid_float64_arc_with_finite(
6060 Arc::clone(data),
6061 Some(data.iter().all(|value| value.is_finite())),
6062 )
6063 }
6064 _ => ScalarValues::from_vec(coerced),
6065 };
6066
6067 Ok(Self {
6068 dtype: DType::Float64,
6069 validity,
6070 data,
6071 values,
6072 })
6073 }
6074
6075 pub fn from_values(values: Vec<Scalar>) -> Result<Self, ColumnError> {
6076 if matches!(values.first(), Some(Scalar::Float64(_))) {
6077 let mut data = Vec::with_capacity(values.len());
6078 let mut all_float64 = true;
6079 let mut has_nan = false;
6080 let mut all_finite = true;
6081 for value in &values {
6082 let Scalar::Float64(value) = value else {
6083 all_float64 = false;
6084 break;
6085 };
6086 has_nan |= value.is_nan();
6087 all_finite &= value.is_finite();
6088 data.push(*value);
6089 }
6090 if all_float64 {
6091 return Ok(Self::from_f64_values_with_finite_witness(
6092 data, has_nan, all_finite,
6093 ));
6094 }
6095 }
6096
6097 let dtype = match infer_dtype(&values) {
6098 Ok(dtype) => dtype,
6099 Err(TypeError::IncompatibleDtypes { .. }) => {
6100 return Ok(Self::from_object_values(values));
6101 }
6102 Err(err) => return Err(ColumnError::Type(err)),
6103 };
6104 if dtype == DType::Float64 {
6105 return Self::from_inferred_float64_values(values);
6106 }
6107 Self::new(dtype, values)
6108 }
6109
6110 #[must_use]
6116 pub fn from_i64_values(data: Vec<i64>) -> Self {
6117 let len = data.len();
6118 Self {
6119 dtype: DType::Int64,
6120 values: ScalarValues::lazy_all_valid_int64(data),
6121 validity: ValidityMask::all_valid(len),
6122 data: None,
6123 }
6124 }
6125
6126 #[doc(hidden)]
6131 #[must_use]
6132 pub fn from_i64_all_valid_chunks(chunks: Vec<(Arc<[i64]>, usize, usize)>, len: usize) -> Self {
6133 debug_assert_eq!(
6134 chunks
6135 .iter()
6136 .map(|(_, _, chunk_len)| *chunk_len)
6137 .sum::<usize>(),
6138 len
6139 );
6140 let chunks: Vec<Int64Chunk> = chunks
6141 .into_iter()
6142 .map(|(data, start, chunk_len)| Int64Chunk::new(data, start, chunk_len))
6143 .collect();
6144 Self {
6145 dtype: DType::Int64,
6146 values: ScalarValues::lazy_all_valid_int64_chunks(Arc::from(chunks), len),
6147 validity: ValidityMask::all_valid(len),
6148 data: None,
6149 }
6150 }
6151
6152 #[must_use]
6158 #[doc(hidden)]
6159 pub fn from_datetime64_values(data: Vec<i64>) -> Self {
6160 let len = data.len();
6161 Self {
6162 dtype: DType::Datetime64,
6163 values: ScalarValues::lazy_all_valid_datetime64(data),
6164 validity: ValidityMask::all_valid(len),
6165 data: None,
6166 }
6167 }
6168
6169 #[must_use]
6177 #[doc(hidden)]
6178 pub fn from_utf8_contiguous(bytes: Vec<u8>, offsets: Vec<usize>) -> Self {
6179 let len = offsets.len().saturating_sub(1);
6180 Self {
6181 dtype: DType::Utf8,
6182 values: ScalarValues::lazy_contiguous_utf8(bytes, offsets),
6183 validity: ValidityMask::all_valid(len),
6184 data: None,
6185 }
6186 }
6187
6188 #[must_use]
6196 #[doc(hidden)]
6197 pub fn from_lower_hex_sequence_utf8(
6198 prefix: &[u8],
6199 start: u64,
6200 len: usize,
6201 hex_width: usize,
6202 ) -> Option<Self> {
6203 let values = ScalarValues::lazy_lower_hex_sequence_utf8(prefix, start, len, hex_width)?;
6204 Some(Self {
6205 dtype: DType::Utf8,
6206 values,
6207 validity: ValidityMask::all_valid(len),
6208 data: None,
6209 })
6210 }
6211
6212 #[must_use]
6218 #[doc(hidden)]
6219 pub fn from_i64_repeat_runs(runs: Vec<(i64, usize)>) -> Self {
6220 let total_len = runs.iter().map(|&(_, run_len)| run_len).sum();
6221 Self {
6222 dtype: DType::Int64,
6223 values: ScalarValues::lazy_repeat_runs_int64(runs, total_len),
6224 validity: ValidityMask::all_valid(total_len),
6225 data: None,
6226 }
6227 }
6228
6229 #[must_use]
6234 #[doc(hidden)]
6235 pub fn from_i64_repeat_values_run_lengths(
6236 run_values: Vec<i64>,
6237 run_lens: Arc<[usize]>,
6238 ) -> Self {
6239 let total_len = run_lens.iter().sum();
6240 Self {
6241 dtype: DType::Int64,
6242 values: ScalarValues::lazy_repeat_values_int64(run_values, run_lens, total_len),
6243 validity: ValidityMask::all_valid(total_len),
6244 data: None,
6245 }
6246 }
6247
6248 #[must_use]
6253 #[doc(hidden)]
6254 pub fn from_i64_repeated_slices(data: Vec<i64>, segments: Vec<(usize, usize)>) -> Self {
6255 let total_len = segments.iter().map(|&(_, len)| len).sum();
6256 Self {
6257 dtype: DType::Int64,
6258 values: ScalarValues::lazy_repeated_slices_int64(data, segments, total_len),
6259 validity: ValidityMask::all_valid(total_len),
6260 data: None,
6261 }
6262 }
6263
6264 #[must_use]
6267 #[doc(hidden)]
6268 pub fn from_i64_repeated_slices_shared(
6269 data: Vec<i64>,
6270 segments: Arc<[(usize, usize)]>,
6271 total_len: usize,
6272 ) -> Self {
6273 Self {
6274 dtype: DType::Int64,
6275 values: ScalarValues::lazy_repeated_slices_int64_shared(data, segments, total_len),
6276 validity: ValidityMask::all_valid(total_len),
6277 data: None,
6278 }
6279 }
6280
6281 #[must_use]
6287 #[doc(hidden)]
6288 pub fn from_f64_repeat_values_run_lengths(
6289 run_values: Vec<f64>,
6290 run_lens: Arc<[usize]>,
6291 ) -> Self {
6292 let total_len = run_lens.iter().sum();
6293 Self {
6294 dtype: DType::Float64,
6295 values: ScalarValues::lazy_repeat_values_float64(run_values, run_lens, total_len),
6296 validity: ValidityMask::all_valid(total_len),
6297 data: None,
6298 }
6299 }
6300
6301 #[must_use]
6306 #[doc(hidden)]
6307 pub fn from_f64_repeated_slices_shared(
6308 data: Vec<f64>,
6309 segments: Arc<[(usize, usize)]>,
6310 total_len: usize,
6311 ) -> Self {
6312 Self {
6313 dtype: DType::Float64,
6314 values: ScalarValues::lazy_repeated_slices_float64_shared(data, segments, total_len),
6315 validity: ValidityMask::all_valid(total_len),
6316 data: None,
6317 }
6318 }
6319
6320 fn nullable_repeated_slices_validity(
6324 segments: &[(usize, usize)],
6325 total_len: usize,
6326 ) -> ValidityMask {
6327 let mut invalid_ranges = Vec::new();
6328 let mut pos = 0usize;
6329 for &(start, len) in segments {
6330 if start == usize::MAX && len > 0 {
6331 invalid_ranges.push((pos, len));
6332 }
6333 pos += len;
6334 }
6335 ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), total_len)
6336 }
6337
6338 fn nullable_repeat_values_validity(
6339 run_valid: &[bool],
6340 run_lens: &[usize],
6341 total_len: usize,
6342 ) -> ValidityMask {
6343 let mut invalid_ranges = Vec::new();
6344 let mut pos = 0usize;
6345 for (&valid, &run_len) in run_valid.iter().zip(run_lens.iter()) {
6346 if !valid && run_len > 0 {
6347 invalid_ranges.push((pos, run_len));
6348 }
6349 pos += run_len;
6350 }
6351 ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), total_len)
6352 }
6353
6354 #[must_use]
6360 #[doc(hidden)]
6361 pub fn from_i64_nullable_repeated_slices_shared(
6362 data: Vec<i64>,
6363 segments: Arc<[(usize, usize)]>,
6364 total_len: usize,
6365 ) -> Self {
6366 let validity = Self::nullable_repeated_slices_validity(&segments, total_len);
6367 Self {
6368 dtype: DType::Int64,
6369 values: ScalarValues::lazy_nullable_repeated_slices_int64(data, segments, total_len),
6370 validity,
6371 data: None,
6372 }
6373 }
6374
6375 #[must_use]
6378 #[doc(hidden)]
6379 pub fn from_f64_nullable_repeated_slices_shared(
6380 data: Vec<f64>,
6381 segments: Arc<[(usize, usize)]>,
6382 total_len: usize,
6383 ) -> Self {
6384 let validity = Self::nullable_repeated_slices_validity(&segments, total_len);
6385 Self::from_f64_nullable_repeated_slices_shared_with_sparse_validity(
6386 data, segments, validity, total_len,
6387 )
6388 }
6389
6390 #[must_use]
6394 #[doc(hidden)]
6395 pub fn from_f64_nullable_repeated_slices_shared_with_sparse_validity(
6396 data: Vec<f64>,
6397 segments: Arc<[(usize, usize)]>,
6398 validity: ValidityMask,
6399 total_len: usize,
6400 ) -> Self {
6401 debug_assert_eq!(validity.len(), total_len);
6402 Self {
6403 dtype: DType::Float64,
6404 values: ScalarValues::lazy_nullable_repeated_slices_float64(data, segments, total_len),
6405 validity,
6406 data: None,
6407 }
6408 }
6409
6410 #[must_use]
6416 #[doc(hidden)]
6417 pub fn from_f64_nullable_repeat_values_run_lengths(
6418 run_values: Vec<f64>,
6419 run_valid: Arc<[bool]>,
6420 run_lens: Arc<[usize]>,
6421 total_len: usize,
6422 ) -> Self {
6423 let validity = Self::nullable_repeat_values_validity(&run_valid, &run_lens, total_len);
6424 Self::from_f64_nullable_repeat_values_run_lengths_with_sparse_validity(
6425 run_values, run_valid, run_lens, validity, total_len,
6426 )
6427 }
6428
6429 #[must_use]
6432 #[doc(hidden)]
6433 pub fn from_f64_nullable_repeat_values_run_lengths_with_sparse_validity(
6434 run_values: Vec<f64>,
6435 run_valid: Arc<[bool]>,
6436 run_lens: Arc<[usize]>,
6437 validity: ValidityMask,
6438 total_len: usize,
6439 ) -> Self {
6440 debug_assert_eq!(validity.len(), total_len);
6441 Self {
6442 dtype: DType::Float64,
6443 values: ScalarValues::lazy_nullable_repeat_values_float64(
6444 run_values, run_valid, run_lens, total_len,
6445 ),
6446 validity,
6447 data: None,
6448 }
6449 }
6450
6451 #[must_use]
6457 #[doc(hidden)]
6458 pub fn from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
6459 source: Arc<[i64]>,
6460 positions: Arc<[usize]>,
6461 segments: Arc<[(usize, usize)]>,
6462 validity: ValidityMask,
6463 total_len: usize,
6464 ) -> Self {
6465 debug_assert_eq!(validity.len(), total_len);
6466 Self {
6467 dtype: DType::Float64,
6468 values: ScalarValues::lazy_nullable_repeated_positions_i64_as_float64(
6469 source, positions, segments, total_len,
6470 ),
6471 validity,
6472 data: None,
6473 }
6474 }
6475
6476 #[must_use]
6481 #[doc(hidden)]
6482 pub fn from_i64_nullable_dense_cycle_right_as_f64_with_sparse_validity(
6483 source: Arc<[i64]>,
6484 left_witness: Int64DenseCycleWitness,
6485 right_witness: Int64DenseCycleWitness,
6486 min_key: i64,
6487 span: usize,
6488 validity: ValidityMask,
6489 total_len: usize,
6490 ) -> Self {
6491 debug_assert_eq!(validity.len(), total_len);
6492 Self {
6493 dtype: DType::Float64,
6494 values: ScalarValues::lazy_nullable_dense_cycle_right_i64_as_float64(
6495 source,
6496 left_witness,
6497 right_witness,
6498 min_key,
6499 span,
6500 total_len,
6501 ),
6502 validity,
6503 data: None,
6504 }
6505 }
6506
6507 #[must_use]
6513 #[doc(hidden)]
6514 pub fn from_i64_nullable_dense_cycle_left_as_f64_with_sparse_validity(
6515 source: Arc<[i64]>,
6516 left_witness: Int64DenseCycleWitness,
6517 right_witness: Int64DenseCycleWitness,
6518 min_key: i64,
6519 span: usize,
6520 validity: ValidityMask,
6521 total_len: usize,
6522 ) -> Self {
6523 debug_assert_eq!(validity.len(), total_len);
6524 Self {
6525 dtype: DType::Float64,
6526 values: ScalarValues::lazy_nullable_dense_cycle_left_i64_as_float64(
6527 source,
6528 left_witness,
6529 right_witness,
6530 min_key,
6531 span,
6532 total_len,
6533 ),
6534 validity,
6535 data: None,
6536 }
6537 }
6538
6539 #[must_use]
6543 #[doc(hidden)]
6544 pub fn from_i64_dense_cycle_probe_repeat(
6545 source: Arc<[i64]>,
6546 probe_witness: Int64DenseCycleWitness,
6547 build_witness: Int64DenseCycleWitness,
6548 total_len: usize,
6549 ) -> Self {
6550 Self {
6551 dtype: DType::Int64,
6552 values: ScalarValues::lazy_dense_cycle_probe_repeat_int64(
6553 source,
6554 probe_witness,
6555 build_witness,
6556 total_len,
6557 ),
6558 validity: ValidityMask::all_valid(total_len),
6559 data: None,
6560 }
6561 }
6562
6563 #[must_use]
6567 #[doc(hidden)]
6568 pub fn from_i64_left_join_dense_cycle_left(
6569 source: Arc<[i64]>,
6570 left_witness: Int64DenseCycleWitness,
6571 right_witness: Int64DenseCycleWitness,
6572 total_len: usize,
6573 ) -> Self {
6574 debug_assert_eq!(source.len(), left_witness.len);
6575 Self {
6576 dtype: DType::Int64,
6577 values: ScalarValues::lazy_left_join_dense_cycle_left_int64(
6578 source,
6579 left_witness,
6580 right_witness,
6581 total_len,
6582 ),
6583 validity: ValidityMask::all_valid(total_len),
6584 data: None,
6585 }
6586 }
6587
6588 #[must_use]
6592 #[doc(hidden)]
6593 pub fn from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
6594 source: Arc<[i64]>,
6595 probe_witness: Int64DenseCycleWitness,
6596 build_witness: Int64DenseCycleWitness,
6597 validity: ValidityMask,
6598 total_len: usize,
6599 ) -> Self {
6600 debug_assert_eq!(validity.len(), total_len);
6601 Self {
6602 dtype: DType::Int64,
6603 values: ScalarValues::lazy_nullable_dense_cycle_probe_build_int64(
6604 source,
6605 probe_witness,
6606 build_witness,
6607 total_len,
6608 ),
6609 validity,
6610 data: None,
6611 }
6612 }
6613
6614 #[must_use]
6618 #[doc(hidden)]
6619 pub fn from_i64_left_join_dense_cycle_right_nullable(
6620 source: Arc<[i64]>,
6621 left_witness: Int64DenseCycleWitness,
6622 right_witness: Int64DenseCycleWitness,
6623 validity: ValidityMask,
6624 total_len: usize,
6625 ) -> Self {
6626 debug_assert_eq!(source.len(), right_witness.len);
6627 debug_assert_eq!(validity.len(), total_len);
6628 Self {
6629 dtype: DType::Int64,
6630 values: ScalarValues::lazy_left_join_dense_cycle_right_int64(
6631 source,
6632 left_witness,
6633 right_witness,
6634 total_len,
6635 ),
6636 validity,
6637 data: None,
6638 }
6639 }
6640
6641 #[must_use]
6646 #[doc(hidden)]
6647 pub fn from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
6648 source: Arc<[i64]>,
6649 run_positions: Arc<[usize]>,
6650 run_valid: Arc<[bool]>,
6651 run_lens: Arc<[usize]>,
6652 validity: ValidityMask,
6653 total_len: usize,
6654 ) -> Self {
6655 debug_assert_eq!(validity.len(), total_len);
6656 Self {
6657 dtype: DType::Float64,
6658 values: ScalarValues::lazy_nullable_repeat_positions_i64_as_float64(
6659 source,
6660 run_positions,
6661 run_valid,
6662 run_lens,
6663 total_len,
6664 ),
6665 validity,
6666 data: None,
6667 }
6668 }
6669
6670 #[must_use]
6676 #[doc(hidden)]
6681 pub fn from_f64_values_all_valid_unchecked(data: Vec<f64>) -> Self {
6682 let len = data.len();
6683 Self {
6684 dtype: DType::Float64,
6685 values: ScalarValues::lazy_all_valid_float64(data),
6686 validity: ValidityMask::all_valid(len),
6687 data: None,
6688 }
6689 }
6690
6691 #[must_use]
6692 #[doc(hidden)]
6693 pub fn from_f64_combine_first_all_valid(
6694 left: Arc<[f64]>,
6695 right: Arc<[f64]>,
6696 left_validity: &ValidityMask,
6697 ) -> Self {
6698 let len = left_validity.len();
6699 debug_assert!(left.len() >= len);
6700 debug_assert!(right.len() >= len);
6701 Self {
6702 dtype: DType::Float64,
6703 values: ScalarValues::lazy_combine_first_float64(
6704 left,
6705 right,
6706 Arc::from(left_validity.packed_words_for_scan()),
6707 len,
6708 ),
6709 validity: ValidityMask::all_valid(len),
6710 data: None,
6711 }
6712 }
6713
6714 pub fn from_f64_values(data: Vec<f64>) -> Self {
6715 let mut has_nan = false;
6716 let mut all_finite = true;
6717 for value in &data {
6718 has_nan |= value.is_nan();
6719 all_finite &= value.is_finite();
6720 }
6721 Self::from_f64_values_with_finite_witness(data, has_nan, all_finite)
6722 }
6723
6724 fn from_f64_values_with_finite_witness(
6725 data: Vec<f64>,
6726 has_nan: bool,
6727 all_finite: bool,
6728 ) -> Self {
6729 let len = data.len();
6730 let validity = if has_nan {
6738 ValidityMask::from_f64(&data)
6739 } else {
6740 ValidityMask::all_valid(len)
6741 };
6742 Self {
6743 dtype: DType::Float64,
6744 values: ScalarValues::lazy_all_valid_float64_with_finite(data, Some(all_finite)),
6745 validity,
6746 data: None,
6747 }
6748 }
6749
6750 fn f64_finite_witness(&self) -> Option<bool> {
6755 self.values.all_valid_float64_finite_witness()
6756 }
6757
6758 fn from_f64_all_valid_with_finite_opt(data: Vec<f64>, all_finite: Option<bool>) -> Self {
6763 let len = data.len();
6764 Self {
6765 dtype: DType::Float64,
6766 values: ScalarValues::lazy_all_valid_float64_with_finite(data, all_finite),
6767 validity: ValidityMask::all_valid(len),
6768 data: None,
6769 }
6770 }
6771
6772 #[doc(hidden)]
6777 #[must_use]
6778 pub fn from_f64_all_valid_chunks(chunks: Vec<(Arc<[f64]>, usize, usize)>, len: usize) -> Self {
6779 debug_assert_eq!(
6780 chunks
6781 .iter()
6782 .map(|(_, _, chunk_len)| *chunk_len)
6783 .sum::<usize>(),
6784 len
6785 );
6786 let chunks: Vec<Float64Chunk> = chunks
6787 .into_iter()
6788 .map(|(data, start, chunk_len)| Float64Chunk::new(data, start, chunk_len))
6789 .collect();
6790 Self {
6791 dtype: DType::Float64,
6792 values: ScalarValues::lazy_all_valid_float64_chunks(Arc::from(chunks), len),
6793 validity: ValidityMask::all_valid(len),
6794 data: None,
6795 }
6796 }
6797
6798 #[doc(hidden)]
6805 #[must_use]
6806 pub fn from_f64_all_valid_dot_product(
6807 a_cols: Vec<(Arc<[f64]>, usize)>,
6808 b_col: Arc<[f64]>,
6809 len: usize,
6810 ) -> Self {
6811 debug_assert_eq!(a_cols.len(), b_col.len());
6812 let a_cols: Vec<Float64DotInput> = a_cols
6813 .into_iter()
6814 .map(|(data, start)| Float64DotInput::new(data, start, len))
6815 .collect();
6816 Self {
6817 dtype: DType::Float64,
6818 values: ScalarValues::lazy_all_valid_float64_dot(Arc::from(a_cols), b_col, len),
6819 validity: ValidityMask::all_valid(len),
6820 data: None,
6821 }
6822 }
6823
6824 #[doc(hidden)]
6833 #[must_use]
6834 pub fn from_f64_all_valid_pairwise_stat_matrix_columns(
6835 cols: Vec<(Arc<[f64]>, usize)>,
6836 row_len: usize,
6837 stat: PairwiseFloat64Stat,
6838 min_periods: usize,
6839 ) -> Vec<Self> {
6840 let inputs: Vec<Float64PairwiseStatInput> = cols
6841 .into_iter()
6842 .map(|(data, start)| Float64PairwiseStatInput::new(data, start, row_len))
6843 .collect();
6844 let plan = Arc::new(Float64PairwiseStatMatrixPlan::new(
6845 Arc::from(inputs),
6846 row_len,
6847 stat,
6848 min_periods,
6849 ));
6850 let n = plan.column_len();
6851 (0..n)
6852 .map(|col| Self {
6853 dtype: DType::Float64,
6854 values: ScalarValues::lazy_all_valid_float64_pairwise_stat_matrix_column(
6855 Arc::clone(&plan),
6856 col,
6857 ),
6858 validity: ValidityMask::all_valid(n),
6859 data: None,
6860 })
6861 .collect()
6862 }
6863
6864 #[doc(hidden)]
6868 pub fn from_f64_values_with_validity(data: Vec<f64>, validity: ValidityMask) -> Self {
6869 debug_assert_eq!(data.len(), validity.len());
6870 if validity.all() {
6871 return Self::from_f64_values(data);
6872 }
6873 Self {
6874 dtype: DType::Float64,
6875 values: ScalarValues::lazy_nullable_float64(data, validity.clone()),
6876 validity,
6877 data: None,
6878 }
6879 }
6880
6881 #[doc(hidden)]
6887 pub fn from_i64_values_with_validity(data: Vec<i64>, validity: ValidityMask) -> Self {
6888 debug_assert_eq!(data.len(), validity.len());
6889 if validity.all() {
6890 return Self::from_i64_values(data);
6891 }
6892 Self {
6893 dtype: DType::Int64,
6894 values: ScalarValues::lazy_nullable_int64(data, validity.clone()),
6895 validity,
6896 data: None,
6897 }
6898 }
6899
6900 #[must_use]
6909 pub fn from_bool_values_with_validity(data: Vec<bool>, validity: ValidityMask) -> Self {
6910 debug_assert_eq!(data.len(), validity.len());
6911 if validity.all() {
6912 return Self::from_bool_values(data);
6913 }
6914 Self {
6915 dtype: DType::Bool,
6916 values: ScalarValues::lazy_nullable_bool(data, validity.clone()),
6917 validity,
6918 data: None,
6919 }
6920 }
6921
6922 #[doc(hidden)]
6930 pub fn from_utf8_values_with_validity(
6931 bytes: Vec<u8>,
6932 offsets: Vec<usize>,
6933 validity: ValidityMask,
6934 ) -> Self {
6935 debug_assert_eq!(offsets.len() - 1, validity.len());
6936 if validity.all() {
6937 return Self::from_utf8_contiguous(bytes, offsets);
6938 }
6939 Self {
6940 dtype: DType::Utf8,
6941 values: ScalarValues::lazy_nullable_utf8(bytes, offsets, validity.clone()),
6942 validity,
6943 data: None,
6944 }
6945 }
6946
6947 fn from_utf8_lazy_gather(
6955 source: Arc<[Scalar]>,
6956 positions: Arc<[usize]>,
6957 validity: ValidityMask,
6958 ) -> Self {
6959 debug_assert_eq!(positions.len(), validity.len());
6960 Self {
6961 dtype: DType::Utf8,
6962 values: ScalarValues::lazy_gather_utf8(source, positions),
6963 validity,
6964 data: None,
6965 }
6966 }
6967
6968 #[doc(hidden)]
6974 pub fn reindex_eager_utf8_with_shared_plan(
6975 &self,
6976 positions: Arc<[usize]>,
6977 validity: ValidityMask,
6978 ) -> Option<Self> {
6979 debug_assert_eq!(positions.len(), validity.len());
6980 if self.dtype != DType::Utf8 || !self.validity.all() {
6981 return None;
6982 }
6983 let source = self.values.eager_arc()?;
6984 debug_assert!(
6985 positions
6986 .iter()
6987 .all(|&pos| pos == usize::MAX || pos < source.len())
6988 );
6989 Some(Self::from_utf8_lazy_gather(
6990 Arc::clone(source),
6991 positions,
6992 validity,
6993 ))
6994 }
6995
6996 #[doc(hidden)]
7000 pub fn reindex_eager_utf8_with_nullable_range(
7001 &self,
7002 null_prefix: usize,
7003 source_start: usize,
7004 source_len: usize,
7005 null_suffix: usize,
7006 ) -> Option<Self> {
7007 if self.dtype != DType::Utf8 || !self.validity.all() {
7008 return None;
7009 }
7010 let source = self.values.eager_arc()?;
7011 source_start
7012 .checked_add(source_len)
7013 .filter(|&end| end <= source.len())?;
7014 let len = null_prefix
7015 .checked_add(source_len)?
7016 .checked_add(null_suffix)?;
7017 let mut invalid_ranges = Vec::with_capacity(2);
7018 if null_prefix > 0 {
7019 invalid_ranges.push((0, null_prefix));
7020 }
7021 if null_suffix > 0 {
7022 invalid_ranges.push((null_prefix + source_len, null_suffix));
7023 }
7024 Some(Self {
7025 dtype: DType::Utf8,
7026 values: ScalarValues::lazy_nullable_utf8_range(
7027 Arc::clone(source),
7028 null_prefix,
7029 source_start,
7030 source_len,
7031 null_suffix,
7032 ),
7033 validity: ValidityMask::from_invalid_ranges(Arc::from(invalid_ranges), len),
7034 data: None,
7035 })
7036 }
7037
7038 #[must_use]
7051 #[doc(hidden)]
7052 pub fn reindex_promote_float64_by_optional_positions(
7053 &self,
7054 positions: &[Option<usize>],
7055 ) -> Option<Self> {
7056 enum TypedSource<'a> {
7057 Int64(&'a [i64]),
7058 Float64(&'a [f64]),
7059 }
7060 let source = if let Some(slice) = self.as_i64_slice() {
7061 TypedSource::Int64(slice)
7062 } else {
7063 let slice = self.as_f64_slice()?;
7064 TypedSource::Float64(slice)
7065 };
7066
7067 let n = positions.len();
7068 let len = self.len();
7069 let mut data = Vec::with_capacity(n);
7070 let mut words = vec![0_u64; n.div_ceil(64)];
7071 for (out_idx, slot) in positions.iter().enumerate() {
7072 match slot {
7073 Some(idx) if *idx < len => {
7074 let value = match source {
7075 TypedSource::Int64(slice) => slice[*idx] as f64,
7076 TypedSource::Float64(slice) => slice[*idx],
7077 };
7078 data.push(value);
7079 words[out_idx / 64] |= 1_u64 << (out_idx % 64);
7082 }
7083 _ => data.push(0.0),
7084 }
7085 }
7086 Some(Self::from_f64_values_with_validity(
7087 data,
7088 ValidityMask::from_words(words, n),
7089 ))
7090 }
7091
7092 #[must_use]
7099 pub fn as_f64_slice_with_validity(&self) -> Option<(&[f64], &ValidityMask)> {
7109 if self.dtype != DType::Float64 {
7110 return None;
7111 }
7112 let data: &[f64] = match &self.values {
7113 ScalarValues::LazyAllValidFloat64 { data, .. } => data.as_ref(),
7114 ScalarValues::LazyNullableFloat64 { data, .. } => data.as_slice(),
7115 _ => match &self.data {
7116 Some(ColumnData::Float64(data)) => data.as_ref(),
7117 _ => return None,
7118 },
7119 };
7120 if data.len() != self.validity.len() {
7121 return None;
7122 }
7123 Some((data, &self.validity))
7124 }
7125
7126 #[must_use]
7127 #[doc(hidden)]
7128 pub fn shared_f64_data_with_validity(&self) -> Option<(Arc<[f64]>, &ValidityMask)> {
7129 if self.dtype != DType::Float64 {
7130 return None;
7131 }
7132 match &self.values {
7133 ScalarValues::LazyAllValidFloat64 { data, .. } if data.len() == self.validity.len() => {
7134 Some((Arc::clone(data), &self.validity))
7135 }
7136 _ => None,
7137 }
7138 }
7139
7140 pub fn as_f64_slice(&self) -> Option<&[f64]> {
7141 if self.dtype == DType::Float64 && self.validity.all() {
7142 if let Some(ColumnData::Float64(data)) = &self.data {
7143 return Some(data.as_ref());
7144 }
7145 if let ScalarValues::LazyAllValidFloat64 { data, .. } = &self.values {
7146 return Some(data.as_ref());
7147 }
7148 if let ScalarValues::LazyAllValidFloat64Slice {
7149 data, start, len, ..
7150 } = &self.values
7151 {
7152 let end = start.checked_add(*len)?;
7153 return data.get(*start..end);
7154 }
7155 if let Some(data) = self.values.chunks_float64_data() {
7156 return Some(data);
7157 }
7158 if let Some(data) = self.values.dot_float64_data() {
7159 return Some(data);
7160 }
7161 if let Some(data) = self.values.pairwise_stat_float64_data() {
7162 return Some(data);
7163 }
7164 if let Some(data) = self.values.combine_first_float64_data() {
7165 return Some(data);
7166 }
7167 if let Some(data) = self.values.strided_float64_data() {
7168 return Some(data);
7169 }
7170 if let Some(data) = self.values.repeated_slices_f64_data() {
7171 return Some(data);
7172 }
7173 }
7174 None
7175 }
7176
7177 #[must_use]
7178 #[doc(hidden)]
7179 pub fn all_valid_f64_to_vec(&self) -> Option<Vec<f64>> {
7180 if self.dtype != DType::Float64 || !self.validity.all() {
7181 return None;
7182 }
7183 if let ScalarValues::LazyRepeatedSlicesFloat64 {
7184 data,
7185 segments,
7186 total_len,
7187 expanded,
7188 ..
7189 } = &self.values
7190 {
7191 return Some(expanded.get().map_or_else(
7192 || ScalarValues::expand_repeated_slices_f64(data, segments, *total_len),
7193 Clone::clone,
7194 ));
7195 }
7196 self.as_f64_slice().map(<[f64]>::to_vec)
7197 }
7198
7199 #[must_use]
7202 pub fn as_i64_slice(&self) -> Option<&[i64]> {
7203 if self.dtype == DType::Int64 && self.validity.all() {
7204 if let Some(ColumnData::Int64(data)) = &self.data {
7205 return Some(data.as_ref());
7206 }
7207 if let ScalarValues::LazyAllValidInt64 { data, .. } = &self.values {
7208 return Some(data.as_ref());
7209 }
7210 if let Some(data) = self.values.chunks_i64_data() {
7211 return Some(data);
7212 }
7213 if let Some(data) = self.values.repeat_runs_i64_data() {
7214 return Some(data);
7215 }
7216 if let Some(data) = self.values.repeated_slices_i64_data() {
7217 return Some(data);
7218 }
7219 if let Some(data) = self.values.left_join_dense_cycle_i64_data() {
7220 return Some(data);
7221 }
7222 }
7223 None
7224 }
7225
7226 #[must_use]
7228 #[doc(hidden)]
7229 pub fn as_datetime64_slice(&self) -> Option<&[i64]> {
7230 if self.dtype != DType::Datetime64 {
7231 return None;
7232 }
7233 if let ScalarValues::LazyAllValidDatetime64 { data, .. } = &self.values {
7238 return Some(data.as_ref());
7239 }
7240 if let Some(ColumnData::Datetime64(data)) = &self.data {
7241 return Some(data.as_slice());
7242 }
7243 None
7244 }
7245
7246 pub fn as_timedelta64_slice(&self) -> Option<&[i64]> {
7252 if self.dtype != DType::Timedelta64 {
7253 return None;
7254 }
7255 if let Some(ColumnData::Timedelta64(data)) = &self.data {
7256 return Some(data.as_slice());
7257 }
7258 None
7259 }
7260
7261 #[must_use]
7265 #[doc(hidden)]
7266 pub fn as_i64_arc(&self) -> Option<Arc<[i64]>> {
7267 if self.dtype == DType::Int64 && self.validity.all() {
7268 if let ScalarValues::LazyAllValidInt64 { data, .. } = &self.values {
7269 return Some(Arc::clone(data));
7270 }
7271 if let Some(ColumnData::Int64(data)) = &self.data {
7272 return Some(Arc::clone(data));
7273 }
7274 return self.as_i64_slice().map(Arc::from);
7275 }
7276 None
7277 }
7278
7279 #[must_use]
7284 #[doc(hidden)]
7285 pub fn as_i64_arc_view_source(&self) -> Option<(Arc<[i64]>, usize)> {
7286 if self.dtype != DType::Int64 || !self.validity.all() {
7287 return None;
7288 }
7289 match &self.values {
7290 ScalarValues::LazyAllValidInt64 { data, .. } => Some((Arc::clone(data), 0)),
7291 _ => match &self.data {
7292 Some(ColumnData::Int64(data)) => Some((Arc::clone(data), 0)),
7293 _ => None,
7294 },
7295 }
7296 }
7297
7298 #[must_use]
7304 #[doc(hidden)]
7305 pub fn int64_dense_cycle_witness(&self) -> Option<Int64DenseCycleWitness> {
7306 if self.dtype == DType::Int64
7307 && self.validity.all()
7308 && let ScalarValues::LazyAllValidInt64 {
7309 data, dense_cycle, ..
7310 } = &self.values
7311 {
7312 return *dense_cycle.get_or_init(|| certify_int64_dense_cycle(data.as_ref()));
7313 }
7314 if self.dtype == DType::Int64
7315 && self.validity.all()
7316 && let ScalarValues::LazyAllValidInt64Chunks {
7317 chunks,
7318 len,
7319 data,
7320 dense_cycle,
7321 ..
7322 } = &self.values
7323 {
7324 return *dense_cycle.get_or_init(|| {
7325 let values =
7326 data.get_or_init(|| ScalarValues::materialize_int64_chunks(chunks, *len));
7327 certify_int64_dense_cycle(values.as_slice())
7328 });
7329 }
7330 None
7331 }
7332
7333 #[must_use]
7339 pub fn from_bool_values(data: Vec<bool>) -> Self {
7340 let len = data.len();
7341 Self {
7342 dtype: DType::Bool,
7343 values: ScalarValues::lazy_all_valid_bool(data),
7344 validity: ValidityMask::all_valid(len),
7345 data: None,
7346 }
7347 }
7348
7349 #[must_use]
7357 #[doc(hidden)]
7358 pub fn as_utf8_contiguous(&self) -> Option<(&[u8], &[usize])> {
7359 if self.dtype != DType::Utf8 || !self.validity.all() {
7360 return None;
7361 }
7362 match &self.values {
7363 ScalarValues::LazyContiguousUtf8 { bytes, offsets, .. } => {
7364 Some((bytes.as_ref(), offsets.as_ref()))
7365 }
7366 ScalarValues::LazyLowerHexSequenceUtf8 {
7367 prefix,
7368 start,
7369 len,
7370 hex_width,
7371 buffers,
7372 ..
7373 } => {
7374 let (bytes, offsets) = ScalarValues::materialized_lower_hex_buffers(
7375 prefix, *start, *len, *hex_width, buffers,
7376 );
7377 Some((bytes.as_ref(), offsets.as_ref()))
7378 }
7379 _ => None,
7380 }
7381 }
7382
7383 #[must_use]
7392 #[doc(hidden)]
7393 pub fn utf8_default_factorize_columns(&self) -> Option<(Self, Self)> {
7394 if self.dtype != DType::Utf8 || !self.validity.all() {
7395 return None;
7396 }
7397 let witness = match &self.values {
7398 ScalarValues::LazyContiguousUtf8 {
7399 bytes,
7400 offsets,
7401 factorize_default,
7402 ..
7403 } => factorize_default
7404 .get_or_init(|| build_utf8_factorize_default_witness(bytes, offsets)),
7405 _ => return None,
7406 };
7407
7408 let codes_len = witness.codes.len();
7409 let unique_len = witness.unique_offsets.len().saturating_sub(1);
7410 let codes = Self {
7411 dtype: DType::Int64,
7412 values: ScalarValues::lazy_all_valid_int64_arc(Arc::clone(&witness.codes)),
7413 validity: ValidityMask::all_valid(codes_len),
7414 data: None,
7415 };
7416 let uniques = Self {
7417 dtype: DType::Utf8,
7418 values: ScalarValues::lazy_contiguous_utf8_arc(
7419 Arc::clone(&witness.unique_bytes),
7420 Arc::clone(&witness.unique_offsets),
7421 ),
7422 validity: ValidityMask::all_valid(unique_len),
7423 data: None,
7424 };
7425 Some((codes, uniques))
7426 }
7427
7428 fn utf8_arc_view_source(&self) -> Option<Utf8ArcViewSource> {
7434 if self.dtype != DType::Utf8 || !self.validity.all() {
7435 return None;
7436 }
7437 match &self.values {
7438 ScalarValues::LazyContiguousUtf8 { bytes, offsets, .. } => {
7439 Some((Arc::clone(bytes), Arc::clone(offsets), 0))
7440 }
7441 ScalarValues::LazyUtf8Slice {
7442 bytes,
7443 offsets,
7444 start,
7445 ..
7446 } => Some((Arc::clone(bytes), Arc::clone(offsets), *start)),
7447 _ => None,
7448 }
7449 }
7450
7451 fn float64_arc_view_source(&self) -> Option<(Arc<[f64]>, usize)> {
7452 if self.dtype != DType::Float64 || !self.validity.all() {
7453 return None;
7454 }
7455 match &self.values {
7456 ScalarValues::LazyAllValidFloat64 { data, .. } => Some((Arc::clone(data), 0)),
7457 ScalarValues::LazyAllValidFloat64Slice { data, start, .. } => {
7458 Some((Arc::clone(data), *start))
7459 }
7460 _ => match &self.data {
7461 Some(ColumnData::Float64(data)) => Some((Arc::clone(data), 0)),
7462 _ => None,
7463 },
7464 }
7465 }
7466
7467 fn finite_float64_arc_view_source(&self, row_len: usize) -> Option<(Arc<[f64]>, usize)> {
7468 if self.dtype != DType::Float64 || !self.validity.all() {
7469 return None;
7470 }
7471 match &self.values {
7472 ScalarValues::LazyAllValidFloat64 {
7473 data, all_finite, ..
7474 } => {
7475 let slice = data.get(..row_len)?;
7476 let finite = if row_len == data.len() {
7477 *all_finite.get_or_init(|| data.iter().all(|value| value.is_finite()))
7478 } else {
7479 slice.iter().all(|value| value.is_finite())
7480 };
7481 finite.then(|| (Arc::clone(data), 0))
7482 }
7483 ScalarValues::LazyAllValidFloat64Slice {
7484 data,
7485 start,
7486 len,
7487 all_finite,
7488 ..
7489 } => {
7490 if *len != row_len {
7491 return None;
7492 }
7493 let end = start.checked_add(row_len)?;
7494 let slice = data.get(*start..end)?;
7495 let finite =
7496 *all_finite.get_or_init(|| slice.iter().all(|value| value.is_finite()));
7497 finite.then(|| (Arc::clone(data), *start))
7498 }
7499 ScalarValues::LazyAllValidFloat64Chunks {
7500 chunks,
7501 len,
7502 all_finite,
7503 ..
7504 } => {
7505 if *len != row_len {
7506 return None;
7507 }
7508 let finite = *all_finite.get_or_init(|| {
7509 chunks
7510 .iter()
7511 .flat_map(Float64Chunk::as_slice)
7512 .all(|value| value.is_finite())
7513 });
7514 if !finite || chunks.len() != 1 {
7515 return None;
7516 }
7517 let chunk = &chunks[0];
7518 Some((Arc::clone(&chunk.data), chunk.start))
7519 }
7520 _ => match &self.data {
7521 Some(ColumnData::Float64(data)) => {
7522 let slice = data.get(..row_len)?;
7523 slice
7524 .iter()
7525 .all(|value| value.is_finite())
7526 .then(|| (Arc::clone(data), 0))
7527 }
7528 _ => None,
7529 },
7530 }
7531 }
7532
7533 #[must_use]
7536 #[doc(hidden)]
7537 pub fn as_f64_arc_view_source(&self) -> Option<(Arc<[f64]>, usize)> {
7538 self.float64_arc_view_source()
7539 }
7540
7541 #[must_use]
7544 #[doc(hidden)]
7545 pub fn as_f64_finite_arc_view_source(&self, row_len: usize) -> Option<(Arc<[f64]>, usize)> {
7546 self.finite_float64_arc_view_source(row_len)
7547 }
7548
7549 #[must_use]
7553 #[doc(hidden)]
7554 pub fn as_strictly_increasing_utf8_contiguous(&self) -> Option<(&[u8], &[usize])> {
7555 if self.dtype != DType::Utf8 || !self.validity.all() {
7556 return None;
7557 }
7558 match &self.values {
7559 ScalarValues::LazyContiguousUtf8 {
7560 bytes,
7561 offsets,
7562 strictly_increasing,
7563 ..
7564 } if *strictly_increasing.get_or_init(|| {
7565 contiguous_utf8_offsets_are_strictly_increasing(bytes, offsets)
7566 }) =>
7567 {
7568 Some((bytes.as_ref(), offsets.as_ref()))
7569 }
7570 ScalarValues::LazyLowerHexSequenceUtf8 {
7571 prefix,
7572 start,
7573 len,
7574 hex_width,
7575 buffers,
7576 ..
7577 } => {
7578 let (bytes, offsets) = ScalarValues::materialized_lower_hex_buffers(
7579 prefix, *start, *len, *hex_width, buffers,
7580 );
7581 Some((bytes.as_ref(), offsets.as_ref()))
7582 }
7583 _ => None,
7584 }
7585 }
7586
7587 #[must_use]
7593 pub fn as_fixed_width_strictly_increasing_utf8_contiguous(
7594 &self,
7595 ) -> Option<(&[u8], &[usize], usize)> {
7596 if self.dtype != DType::Utf8 || !self.validity.all() {
7597 return None;
7598 }
7599 match &self.values {
7600 ScalarValues::LazyContiguousUtf8 {
7601 bytes,
7602 offsets,
7603 strictly_increasing,
7604 fixed_width,
7605 ..
7606 } if *strictly_increasing.get_or_init(|| {
7607 contiguous_utf8_offsets_are_strictly_increasing(bytes, offsets)
7608 }) =>
7609 {
7610 let width = fixed_width
7611 .get_or_init(|| contiguous_utf8_fixed_width(offsets))
7612 .as_ref()
7613 .copied()?;
7614 Some((bytes.as_ref(), offsets.as_ref(), width))
7615 }
7616 ScalarValues::LazyLowerHexSequenceUtf8 {
7617 prefix,
7618 start,
7619 len,
7620 hex_width,
7621 buffers,
7622 ..
7623 } => {
7624 let (bytes, offsets) = ScalarValues::materialized_lower_hex_buffers(
7625 prefix, *start, *len, *hex_width, buffers,
7626 );
7627 Some((bytes.as_ref(), offsets.as_ref(), prefix.len() + *hex_width))
7628 }
7629 _ => None,
7630 }
7631 }
7632
7633 #[must_use]
7641 #[doc(hidden)]
7642 pub fn as_lower_hex_sequence_utf8_contiguous(
7643 &self,
7644 ) -> Option<(&[u8], &[usize], Utf8LowerHexSequence)> {
7645 if self.dtype != DType::Utf8 || !self.validity.all() {
7646 return None;
7647 }
7648 match &self.values {
7649 ScalarValues::LazyContiguousUtf8 {
7650 bytes,
7651 offsets,
7652 strictly_increasing,
7653 fixed_width,
7654 lower_hex_sequence,
7655 ..
7656 } if *strictly_increasing.get_or_init(|| {
7657 contiguous_utf8_offsets_are_strictly_increasing(bytes, offsets)
7658 }) =>
7659 {
7660 let width = fixed_width
7661 .get_or_init(|| contiguous_utf8_fixed_width(offsets))
7662 .as_ref()
7663 .copied()?;
7664 let certificate = lower_hex_sequence
7665 .get_or_init(|| contiguous_utf8_lower_hex_sequence(bytes, offsets, width))
7666 .as_ref()
7667 .copied()?;
7668 Some((bytes.as_ref(), offsets.as_ref(), certificate))
7669 }
7670 ScalarValues::LazyLowerHexSequenceUtf8 {
7671 prefix,
7672 start,
7673 len,
7674 hex_width,
7675 buffers,
7676 ..
7677 } => {
7678 let (bytes, offsets) = ScalarValues::materialized_lower_hex_buffers(
7679 prefix, *start, *len, *hex_width, buffers,
7680 );
7681 if *len == 0 {
7682 return None;
7683 }
7684 let (_, certificate, _) =
7685 ScalarValues::lower_hex_sequence_witness(prefix, *start, *len, *hex_width);
7686 Some((bytes.as_ref(), offsets.as_ref(), certificate))
7687 }
7688 _ => None,
7689 }
7690 }
7691
7692 #[must_use]
7695 #[doc(hidden)]
7696 pub fn as_lower_hex_sequence_utf8(&self) -> Option<(&[u8], Utf8LowerHexSequence, usize)> {
7697 if self.dtype != DType::Utf8 || !self.validity.all() {
7698 return None;
7699 }
7700 match &self.values {
7701 ScalarValues::LazyLowerHexSequenceUtf8 {
7702 prefix,
7703 start,
7704 len,
7705 hex_width,
7706 ..
7707 } => Some(ScalarValues::lower_hex_sequence_witness(
7708 prefix, *start, *len, *hex_width,
7709 )),
7710 ScalarValues::LazyContiguousUtf8 {
7711 bytes,
7712 offsets,
7713 strictly_increasing,
7714 fixed_width,
7715 lower_hex_sequence,
7716 ..
7717 } if *strictly_increasing.get_or_init(|| {
7718 contiguous_utf8_offsets_are_strictly_increasing(bytes, offsets)
7719 }) =>
7720 {
7721 let width = fixed_width
7722 .get_or_init(|| contiguous_utf8_fixed_width(offsets))
7723 .as_ref()
7724 .copied()?;
7725 let certificate = lower_hex_sequence
7726 .get_or_init(|| contiguous_utf8_lower_hex_sequence(bytes, offsets, width))
7727 .as_ref()
7728 .copied()?;
7729 let n = offsets.len().checked_sub(1)?;
7730 let first_start = *offsets.first()?;
7731 let prefix_end = first_start.checked_add(certificate.prefix_len())?;
7732 let first_end = *offsets.get(1)?;
7733 (prefix_end <= first_end && first_end <= bytes.len())
7734 .then(|| (&bytes[first_start..prefix_end], certificate, n))
7735 }
7736 _ => None,
7737 }
7738 }
7739
7740 #[must_use]
7743 pub fn as_bool_slice(&self) -> Option<&[bool]> {
7744 if self.dtype == DType::Bool && self.validity.all() {
7745 if let Some(ColumnData::Bool(data)) = &self.data {
7746 return Some(data.as_ref());
7747 }
7748 if let ScalarValues::LazyAllValidBool { data, .. } = &self.values {
7749 return Some(data.as_ref());
7750 }
7751 }
7752 None
7753 }
7754
7755 #[must_use]
7761 #[doc(hidden)]
7762 pub fn bool_affine_selection_witness(&self) -> Option<BoolAffineSelectionWitness> {
7763 if self.dtype == DType::Bool
7764 && self.validity.all()
7765 && let ScalarValues::LazyAllValidBool {
7766 data,
7767 affine_selection,
7768 ..
7769 } = &self.values
7770 {
7771 return *affine_selection.get_or_init(|| certify_bool_affine_selection(data.as_ref()));
7772 }
7773 None
7774 }
7775
7776 #[must_use]
7795 pub fn take_positions(&self, positions: &[usize]) -> Self {
7796 let n = positions.len();
7797 if self.validity.all() {
7798 if n >= 64
7809 && let Some((src_data, src_start)) = self.float64_arc_view_source()
7810 && let Some(range_start) = contiguous_ascending_start(positions)
7811 && let Some(view_start) = src_start.checked_add(range_start)
7812 && view_start
7813 .checked_add(n)
7814 .is_some_and(|end| end <= src_data.len())
7815 {
7816 return Self {
7817 dtype: self.dtype,
7818 values: ScalarValues::lazy_all_valid_float64_slice(src_data, view_start, n),
7819 validity: ValidityMask::all_valid(n),
7820 data: None,
7821 };
7822 }
7823
7824 if let Some(column) = self.take_strided_all_valid_float64_positions(positions) {
7825 return column;
7826 }
7827
7828 if let Some(data) = self.take_cached_all_valid_float64_positions(positions) {
7829 return Self {
7830 dtype: self.dtype,
7831 values: ScalarValues::lazy_all_valid_float64(data),
7832 validity: ValidityMask::all_valid(n),
7833 data: None,
7834 };
7835 }
7836
7837 if let Some(data) = self.take_cached_all_valid_int64_positions(positions) {
7843 return Self {
7844 dtype: self.dtype,
7845 values: ScalarValues::lazy_all_valid_int64(data),
7846 validity: ValidityMask::all_valid(n),
7847 data: None,
7848 };
7849 }
7850
7851 if n >= 64
7866 && let Some((src_bytes, src_offsets, src_start)) = self.utf8_arc_view_source()
7867 && let Some(range_start) = contiguous_ascending_start(positions)
7868 {
7869 return Self {
7870 dtype: self.dtype,
7871 values: ScalarValues::lazy_utf8_slice(
7872 src_bytes,
7873 src_offsets,
7874 src_start + range_start,
7875 n,
7876 ),
7877 validity: ValidityMask::all_valid(n),
7878 data: None,
7879 };
7880 }
7881
7882 if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
7890 let total: usize = positions
7891 .iter()
7892 .map(|&pos| offsets[pos + 1] - offsets[pos])
7893 .sum();
7894 let mut new_bytes = Vec::with_capacity(total);
7895 let mut new_offsets = Vec::with_capacity(n + 1);
7896 new_offsets.push(0);
7897 for &pos in positions {
7898 new_bytes.extend_from_slice(&bytes[offsets[pos]..offsets[pos + 1]]);
7899 new_offsets.push(new_bytes.len());
7900 }
7901 return Self {
7902 dtype: self.dtype,
7903 values: ScalarValues::lazy_contiguous_utf8(new_bytes, new_offsets),
7904 validity: ValidityMask::all_valid(n),
7905 data: None,
7906 };
7907 }
7908
7909 if self.dtype == DType::Utf8
7922 && let Some(strs) = self.as_all_valid_str_vec()
7923 {
7924 let total: usize = positions.iter().map(|&pos| strs[pos].len()).sum();
7925 let mut new_bytes = Vec::with_capacity(total);
7926 let mut new_offsets = Vec::with_capacity(n + 1);
7927 new_offsets.push(0);
7928 for &pos in positions {
7929 new_bytes.extend_from_slice(strs[pos].as_bytes());
7930 new_offsets.push(new_bytes.len());
7931 }
7932 return Self {
7933 dtype: self.dtype,
7934 values: ScalarValues::lazy_contiguous_utf8(new_bytes, new_offsets),
7935 validity: ValidityMask::all_valid(n),
7936 data: None,
7937 };
7938 }
7939
7940 let values = self
7941 .take_all_valid_primitive_positions(positions)
7942 .unwrap_or_else(|| {
7943 positions
7944 .iter()
7945 .map(|&pos| self.values[pos].clone())
7946 .collect()
7947 });
7948 return Self {
7949 dtype: self.dtype,
7950 values: ScalarValues::from_vec(values),
7951 validity: ValidityMask::all_valid(n),
7952 data: None,
7953 };
7954 }
7955
7956 let typed_f64: Option<&[f64]> = match &self.values {
7980 ScalarValues::LazyNullableFloat64 { data, .. } => Some(data.as_slice()),
7981 ScalarValues::LazyAllValidFloat64 { data, .. } => Some(data.as_ref()),
7982 _ => None,
7983 };
7984 if let Some(src) = typed_f64 {
7985 let mut data = Vec::with_capacity(n);
7986 let mut words = vec![0_u64; n.div_ceil(64)];
7987 for (out_idx, &pos) in positions.iter().enumerate() {
7988 let x = src[pos];
7989 data.push(x);
7990 if self.validity.get(pos) && !x.is_nan() {
7991 words[out_idx / 64] |= 1_u64 << (out_idx % 64);
7992 }
7993 }
7994 return Self::from_f64_values_with_validity(data, ValidityMask::from_words(words, n));
7995 }
7996
7997 let mut values = Vec::with_capacity(n);
7998 let mut words = vec![0_u64; n.div_ceil(64)];
7999 for (out_idx, &pos) in positions.iter().enumerate() {
8000 let value = self.values[pos].clone();
8001 if !value.is_missing() {
8002 words[out_idx / 64] |= 1_u64 << (out_idx % 64);
8003 }
8004 values.push(value);
8005 }
8006 Self {
8007 dtype: self.dtype,
8008 values: ScalarValues::from_vec(values),
8009 validity: ValidityMask::from_words(words, n),
8010 data: None,
8011 }
8012 }
8013
8014 #[must_use]
8017 #[doc(hidden)]
8018 pub fn supports_fast_position_run_gather(&self) -> bool {
8019 if self.validity.all()
8020 && (self.as_f64_slice().is_some()
8021 || self.as_i64_slice().is_some()
8022 || self.as_bool_slice().is_some())
8023 {
8024 return true;
8025 }
8026
8027 matches!(
8028 &self.values,
8029 ScalarValues::LazyNullableFloat64 { .. } | ScalarValues::LazyAllValidFloat64 { .. }
8030 )
8031 }
8032
8033 #[must_use]
8039 #[doc(hidden)]
8040 pub fn take_position_runs(&self, runs: &[(usize, usize)], out_len: usize) -> Self {
8041 debug_assert_eq!(runs.iter().map(|&(_, len)| len).sum::<usize>(), out_len);
8042 for &(start, len) in runs {
8043 let end = start
8044 .checked_add(len)
8045 .expect("position run end must not overflow");
8046 assert!(end <= self.len(), "position run end must be in bounds");
8047 }
8048
8049 if out_len == 0 {
8050 return self.take_positions(&[]);
8051 }
8052
8053 if runs.len() == 1 {
8054 let (start, len) = runs[0];
8055 return self.take_contiguous_range(start, len);
8056 }
8057
8058 if self.validity.all() {
8059 if let Some(src) = self.as_f64_slice() {
8060 let mut data = Vec::with_capacity(out_len);
8061 for &(start, len) in runs {
8062 data.extend_from_slice(&src[start..start + len]);
8063 }
8064 return Self {
8065 dtype: self.dtype,
8066 values: ScalarValues::lazy_all_valid_float64(data),
8067 validity: ValidityMask::all_valid(out_len),
8068 data: None,
8069 };
8070 }
8071
8072 if let Some(src) = self.as_i64_slice() {
8073 let mut data = Vec::with_capacity(out_len);
8074 for &(start, len) in runs {
8075 data.extend_from_slice(&src[start..start + len]);
8076 }
8077 return Self {
8078 dtype: self.dtype,
8079 values: ScalarValues::lazy_all_valid_int64(data),
8080 validity: ValidityMask::all_valid(out_len),
8081 data: None,
8082 };
8083 }
8084
8085 if let Some(src) = self.as_bool_slice() {
8086 let mut data = Vec::with_capacity(out_len);
8087 for &(start, len) in runs {
8088 data.extend_from_slice(&src[start..start + len]);
8089 }
8090 return Self {
8091 dtype: self.dtype,
8092 values: ScalarValues::lazy_all_valid_bool(data),
8093 validity: ValidityMask::all_valid(out_len),
8094 data: None,
8095 };
8096 }
8097 }
8098
8099 let typed_f64: Option<&[f64]> = match &self.values {
8100 ScalarValues::LazyNullableFloat64 { data, .. } => Some(data.as_slice()),
8101 ScalarValues::LazyAllValidFloat64 { data, .. } => Some(data.as_ref()),
8102 _ => None,
8103 };
8104 if let Some(src) = typed_f64 {
8105 let mut data = Vec::with_capacity(out_len);
8106 let mut words: Option<Vec<u64>> = None;
8107 let mut out_idx = 0usize;
8108 for &(start, len) in runs {
8109 let end = start + len;
8110 data.extend_from_slice(&src[start..end]);
8111 for (offset, &x) in src[start..end].iter().enumerate() {
8112 let pos = start + offset;
8113 let is_valid = self.validity.get(pos) && !x.is_nan();
8114 if let Some(words) = &mut words {
8115 if is_valid {
8116 words[out_idx / 64] |= 1_u64 << (out_idx % 64);
8117 }
8118 } else if !is_valid {
8119 let mut initialized = vec![0_u64; out_len.div_ceil(64)];
8120 let full_words = out_idx / 64;
8121 initialized[..full_words].fill(u64::MAX);
8122 let partial_bits = out_idx % 64;
8123 if partial_bits != 0 {
8124 initialized[full_words] = (1_u64 << partial_bits) - 1;
8125 }
8126 words = Some(initialized);
8127 }
8128 out_idx += 1;
8129 }
8130 }
8131 if let Some(words) = words {
8132 return Self::from_f64_values_with_validity(
8133 data,
8134 ValidityMask::from_words(words, out_len),
8135 );
8136 }
8137 return Self::from_f64_values_all_valid_unchecked(data);
8138 }
8139
8140 let mut positions = Vec::with_capacity(out_len);
8141 for &(start, len) in runs {
8142 positions.extend(start..start + len);
8143 }
8144 self.take_positions(&positions)
8145 }
8146
8147 #[must_use]
8151 #[doc(hidden)]
8152 pub fn take_position_runs_all_valid_f64_unchecked(
8153 &self,
8154 runs: &[(usize, usize)],
8155 out_len: usize,
8156 ) -> Option<Self> {
8157 debug_assert_eq!(runs.iter().map(|&(_, len)| len).sum::<usize>(), out_len);
8158 let (data, base, source_len) = match &self.values {
8159 ScalarValues::LazyAllValidFloat64 { data, .. } => (Arc::clone(data), 0, data.len()),
8160 ScalarValues::LazyAllValidFloat64Slice {
8161 data, start, len, ..
8162 } => (Arc::clone(data), *start, *len),
8163 _ => return None,
8164 };
8165
8166 debug_assert!(
8167 runs.iter()
8168 .all(|&(start, len)| start.checked_add(len).is_some_and(|end| end <= source_len))
8169 );
8170 debug_assert!(runs.iter().all(|&(start, len)| {
8171 (start..start + len).all(|row| self.validity.get(row) && !data[base + row].is_nan())
8172 }));
8173
8174 if out_len == 0 {
8175 return Some(Self::from_f64_values_all_valid_unchecked(Vec::new()));
8176 }
8177
8178 let chunks = runs
8179 .iter()
8180 .map(|&(start, len)| (Arc::clone(&data), base + start, len))
8181 .collect();
8182 Some(Self::from_f64_all_valid_chunks(chunks, out_len))
8183 }
8184
8185 #[must_use]
8191 pub fn take_contiguous_range(&self, start: usize, len: usize) -> Self {
8192 let end = start
8193 .checked_add(len)
8194 .expect("contiguous range end must not overflow");
8195 assert!(
8196 end <= self.len(),
8197 "contiguous range end must be within column length"
8198 );
8199
8200 if self.validity.all() {
8201 if let Some((src_data, src_start)) = self.float64_arc_view_source()
8202 && let Some(view_start) = src_start.checked_add(start)
8203 && view_start
8204 .checked_add(len)
8205 .is_some_and(|view_end| view_end <= src_data.len())
8206 {
8207 return Self {
8208 dtype: self.dtype,
8209 values: ScalarValues::lazy_all_valid_float64_slice(src_data, view_start, len),
8210 validity: ValidityMask::all_valid(len),
8211 data: None,
8212 };
8213 }
8214
8215 if let Some(values) = self.as_f64_slice() {
8216 return Self::from_f64_values(values[start..end].to_vec());
8217 }
8218
8219 if let Some(values) = self.as_i64_slice() {
8220 return Self::from_i64_values(values[start..end].to_vec());
8221 }
8222
8223 if let Some((src_bytes, src_offsets, src_start)) = self.utf8_arc_view_source() {
8224 return Self {
8225 dtype: self.dtype,
8226 values: ScalarValues::lazy_utf8_slice(
8227 src_bytes,
8228 src_offsets,
8229 src_start + start,
8230 len,
8231 ),
8232 validity: ValidityMask::all_valid(len),
8233 data: None,
8234 };
8235 }
8236
8237 if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
8238 let byte_start = offsets[start];
8239 let byte_end = offsets[end];
8240 let mut new_offsets = Vec::with_capacity(len + 1);
8241 for &offset in &offsets[start..=end] {
8242 new_offsets.push(offset - byte_start);
8243 }
8244 return Self {
8245 dtype: self.dtype,
8246 values: ScalarValues::lazy_contiguous_utf8(
8247 bytes[byte_start..byte_end].to_vec(),
8248 new_offsets,
8249 ),
8250 validity: ValidityMask::all_valid(len),
8251 data: None,
8252 };
8253 }
8254 }
8255
8256 let positions: Vec<usize> = (start..end).collect();
8257 self.take_positions(&positions)
8258 }
8259
8260 fn bounded_arithmetic_progression_positions(
8261 positions: &[usize],
8262 source_len: usize,
8263 ) -> Option<(usize, usize)> {
8264 match positions {
8265 [] => None,
8266 [start] if *start < source_len => Some((*start, 1)),
8267 [_] => None,
8268 [start, second, rest @ ..] => {
8269 let step = second.checked_sub(*start)?;
8270 if step == 0 {
8271 return None;
8272 }
8273 let last = start.checked_add(step.checked_mul(positions.len() - 1)?)?;
8274 if last >= source_len {
8275 return None;
8276 }
8277 let mut expected = *second;
8278 for &pos in rest {
8279 expected += step;
8280 if pos != expected {
8281 return None;
8282 }
8283 }
8284 Some((*start, step))
8285 }
8286 }
8287 }
8288
8289 #[must_use]
8300 #[doc(hidden)]
8301 pub fn take_positions_with_affine_certificate(
8302 &self,
8303 positions: &[usize],
8304 start: usize,
8305 step: usize,
8306 ) -> Self {
8307 if let Some(column) =
8308 self.take_affine_all_valid_float64_positions(positions.len(), start, step)
8309 {
8310 return column;
8311 }
8312 self.take_positions(positions)
8313 }
8314
8315 #[must_use]
8321 #[doc(hidden)]
8322 pub fn take_affine_positions_without_materialized_positions(
8323 &self,
8324 start: usize,
8325 step: usize,
8326 len: usize,
8327 ) -> Option<Self> {
8328 self.take_affine_all_valid_float64_positions(len, start, step)
8329 }
8330
8331 fn take_affine_all_valid_float64_positions(
8332 &self,
8333 len: usize,
8334 start: usize,
8335 step: usize,
8336 ) -> Option<Self> {
8337 if self.dtype != DType::Float64
8338 || !self.validity.all()
8339 || len < STRIDED_FLOAT64_MIN_LEN
8340 || step == 0
8341 {
8342 return None;
8343 }
8344
8345 let data = match &self.values {
8346 ScalarValues::LazyAllValidFloat64 { data, .. } => Arc::clone(data),
8347 _ => match &self.data {
8348 Some(ColumnData::Float64(data)) => Arc::clone(data),
8349 _ => return None,
8350 },
8351 };
8352
8353 let last = start.checked_add(step.checked_mul(len - 1)?)?;
8354 if last >= data.len() {
8355 return None;
8356 }
8357
8358 Some(Self {
8359 dtype: self.dtype,
8360 values: ScalarValues::lazy_strided_float64(data, start, step, len),
8361 validity: ValidityMask::all_valid(len),
8362 data: None,
8363 })
8364 }
8365
8366 fn take_strided_all_valid_float64_positions(&self, positions: &[usize]) -> Option<Self> {
8367 if self.dtype != DType::Float64 || positions.len() < STRIDED_FLOAT64_MIN_LEN {
8368 return None;
8369 }
8370
8371 let data = match &self.values {
8372 ScalarValues::LazyAllValidFloat64 { data, .. } => Arc::clone(data),
8373 _ => match &self.data {
8374 Some(ColumnData::Float64(data)) => Arc::clone(data),
8375 _ => return None,
8376 },
8377 };
8378
8379 let (start, step) = Self::bounded_arithmetic_progression_positions(positions, data.len())?;
8380
8381 Some(Self {
8382 dtype: self.dtype,
8383 values: ScalarValues::lazy_strided_float64(data, start, step, positions.len()),
8384 validity: ValidityMask::all_valid(positions.len()),
8385 data: None,
8386 })
8387 }
8388
8389 fn take_cached_all_valid_float64_positions(&self, positions: &[usize]) -> Option<Vec<f64>> {
8390 let data = self.as_f64_slice()?;
8391 let mut values = Vec::with_capacity(positions.len());
8392 for &pos in positions {
8393 values.push(data[pos]);
8394 }
8395 Some(values)
8396 }
8397
8398 fn take_cached_all_valid_int64_positions(&self, positions: &[usize]) -> Option<Vec<i64>> {
8399 let data = self.as_i64_slice()?;
8400 let mut values = Vec::with_capacity(positions.len());
8401 for &pos in positions {
8402 values.push(data[pos]);
8403 }
8404 Some(values)
8405 }
8406
8407 fn take_all_valid_primitive_positions(&self, positions: &[usize]) -> Option<Vec<Scalar>> {
8408 if let Some(values) = self.take_cached_all_valid_primitive_positions(positions) {
8409 return Some(values);
8410 }
8411
8412 let mut values = Vec::with_capacity(positions.len());
8413 match self.dtype {
8414 DType::Bool | DType::BoolNullable => {
8415 for &pos in positions {
8416 match &self.values[pos] {
8417 Scalar::Bool(value) => values.push(Scalar::Bool(*value)),
8418 _ => return None,
8419 }
8420 }
8421 }
8422 DType::Int64 | DType::Int64Nullable => {
8423 for &pos in positions {
8424 match &self.values[pos] {
8425 Scalar::Int64(value) => values.push(Scalar::Int64(*value)),
8426 _ => return None,
8427 }
8428 }
8429 }
8430 DType::Float64 => {
8431 for &pos in positions {
8432 match &self.values[pos] {
8433 Scalar::Float64(value) => values.push(Scalar::Float64(*value)),
8434 _ => return None,
8435 }
8436 }
8437 }
8438 DType::Timedelta64 => {
8439 for &pos in positions {
8440 match &self.values[pos] {
8441 Scalar::Timedelta64(value) => values.push(Scalar::Timedelta64(*value)),
8442 _ => return None,
8443 }
8444 }
8445 }
8446 DType::Datetime64 => {
8447 for &pos in positions {
8448 match &self.values[pos] {
8449 Scalar::Datetime64(value) => values.push(Scalar::Datetime64(*value)),
8450 _ => return None,
8451 }
8452 }
8453 }
8454 DType::Period => {
8455 for &pos in positions {
8456 match &self.values[pos] {
8457 Scalar::Period(value) => values.push(Scalar::Period(*value)),
8458 _ => return None,
8459 }
8460 }
8461 }
8462 _ => return None,
8463 }
8464 Some(values)
8465 }
8466
8467 fn take_cached_all_valid_primitive_positions(
8468 &self,
8469 positions: &[usize],
8470 ) -> Option<Vec<Scalar>> {
8471 match self.dtype {
8472 DType::Bool => {
8473 if let Some(data) = self.as_bool_slice() {
8474 let mut values = Vec::with_capacity(positions.len());
8475 for &pos in positions {
8476 values.push(Scalar::Bool(data[pos]));
8477 }
8478 return Some(values);
8479 }
8480 }
8481 DType::Int64 => {
8482 if let Some(data) = self.as_i64_slice() {
8483 let mut values = Vec::with_capacity(positions.len());
8484 for &pos in positions {
8485 values.push(Scalar::Int64(data[pos]));
8486 }
8487 return Some(values);
8488 }
8489 }
8490 DType::Float64 => {
8491 if let Some(data) = self.as_f64_slice() {
8492 let mut values = Vec::with_capacity(positions.len());
8493 for &pos in positions {
8494 values.push(Scalar::Float64(data[pos]));
8495 }
8496 return Some(values);
8497 }
8498 }
8499 _ => {}
8500 }
8501
8502 let data = self.data.as_ref()?;
8503 let mut values = Vec::with_capacity(positions.len());
8504 match (self.dtype, data) {
8505 (DType::Bool | DType::BoolNullable, ColumnData::Bool(data)) => {
8506 for &pos in positions {
8507 values.push(Scalar::Bool(data[pos]));
8508 }
8509 }
8510 (DType::Int64 | DType::Int64Nullable, ColumnData::Int64(data)) => {
8511 for &pos in positions {
8512 values.push(Scalar::Int64(data[pos]));
8513 }
8514 }
8515 (DType::Float64, ColumnData::Float64(data)) => {
8516 for &pos in positions {
8517 values.push(Scalar::Float64(data[pos]));
8518 }
8519 }
8520 (DType::Timedelta64, ColumnData::Timedelta64(data)) => {
8521 for &pos in positions {
8522 values.push(Scalar::Timedelta64(data[pos]));
8523 }
8524 }
8525 (DType::Datetime64, ColumnData::Datetime64(data)) => {
8526 for &pos in positions {
8527 values.push(Scalar::Datetime64(data[pos]));
8528 }
8529 }
8530 (DType::Period, ColumnData::Period(data, freq)) => {
8531 for &pos in positions {
8532 values.push(Scalar::Period(Period::new(data[pos], *freq)));
8533 }
8534 }
8535 _ => return None,
8536 }
8537 Some(values)
8538 }
8539
8540 pub fn zeros(n: usize, dtype: DType) -> Result<Self, ColumnError> {
8544 let zero = match dtype {
8545 DType::Int64 => Scalar::Int64(0),
8546 DType::Float64 => Scalar::Float64(0.0),
8547 DType::Bool => Scalar::Bool(false),
8548 _ => Scalar::Int64(0),
8549 };
8550 Self::new(dtype, vec![zero; n])
8551 }
8552
8553 pub fn ones(n: usize, dtype: DType) -> Result<Self, ColumnError> {
8557 let one = match dtype {
8558 DType::Int64 => Scalar::Int64(1),
8559 DType::Float64 => Scalar::Float64(1.0),
8560 DType::Bool => Scalar::Bool(true),
8561 _ => Scalar::Int64(1),
8562 };
8563 Self::new(dtype, vec![one; n])
8564 }
8565
8566 pub fn full(n: usize, fill_value: Scalar) -> Result<Self, ColumnError> {
8570 let dtype = fill_value.dtype();
8571 Self::new(dtype, vec![fill_value; n])
8572 }
8573
8574 pub fn zeros_like(&self) -> Result<Self, ColumnError> {
8576 Self::zeros(self.len(), self.dtype)
8577 }
8578
8579 pub fn ones_like(&self) -> Result<Self, ColumnError> {
8581 Self::ones(self.len(), self.dtype)
8582 }
8583
8584 pub fn full_like(&self, fill_value: Scalar) -> Result<Self, ColumnError> {
8586 Self::new(self.dtype, vec![fill_value; self.len()])
8587 }
8588
8589 pub fn empty_like(&self) -> Result<Self, ColumnError> {
8591 Self::new(self.dtype, Vec::new())
8592 }
8593
8594 pub fn arange(start: f64, stop: f64, step: f64) -> Result<Self, ColumnError> {
8598 if step == 0.0 {
8599 return Err(ColumnError::Type(TypeError::NonNumericValue {
8600 value: "step cannot be zero".to_string(),
8601 dtype: DType::Float64,
8602 }));
8603 }
8604 let mut values = Vec::new();
8605 let mut x = start;
8606 if step > 0.0 {
8607 while x < stop {
8608 values.push(Scalar::Float64(x));
8609 x += step;
8610 }
8611 } else {
8612 while x > stop {
8613 values.push(Scalar::Float64(x));
8614 x += step;
8615 }
8616 }
8617 Self::new(DType::Float64, values)
8618 }
8619
8620 pub fn linspace(start: f64, stop: f64, num: usize) -> Result<Self, ColumnError> {
8624 if num == 0 {
8625 return Self::new(DType::Float64, Vec::new());
8626 }
8627 if num == 1 {
8628 return Self::new(DType::Float64, vec![Scalar::Float64(start)]);
8629 }
8630 let step = (stop - start) / (num - 1) as f64;
8631 let values: Vec<Scalar> = (0..num)
8632 .map(|i| Scalar::Float64(start + step * i as f64))
8633 .collect();
8634 Self::new(DType::Float64, values)
8635 }
8636
8637 pub fn logspace(start: f64, stop: f64, num: usize) -> Result<Self, ColumnError> {
8641 let lin = Self::linspace(start, stop, num)?;
8642 let values: Vec<Scalar> = lin
8643 .values()
8644 .iter()
8645 .map(|v| match v {
8646 Scalar::Float64(x) => Scalar::Float64(10.0_f64.powf(*x)),
8647 _ => v.clone(),
8648 })
8649 .collect();
8650 Self::new(DType::Float64, values)
8651 }
8652
8653 pub fn geomspace(start: f64, stop: f64, num: usize) -> Result<Self, ColumnError> {
8658 if num == 0 {
8659 return Self::new(DType::Float64, vec![]);
8660 }
8661 if start == 0.0 || stop == 0.0 {
8662 return Err(ColumnError::Type(TypeError::NonNumericValue {
8663 value: "geomspace endpoints cannot be zero".to_owned(),
8664 dtype: DType::Float64,
8665 }));
8666 }
8667 if num == 1 {
8668 return Self::new(DType::Float64, vec![Scalar::Float64(start)]);
8669 }
8670
8671 let log_start = start.ln();
8672 let log_stop = stop.ln();
8673 let step = (log_stop - log_start) / (num - 1) as f64;
8674 let values: Vec<Scalar> = (0..num)
8675 .map(|i| Scalar::Float64((log_start + step * i as f64).exp()))
8676 .collect();
8677 Self::new(DType::Float64, values)
8678 }
8679
8680 pub fn hanning(m: usize) -> Result<Self, ColumnError> {
8684 if m == 0 {
8685 return Self::new(DType::Float64, vec![]);
8686 }
8687 if m == 1 {
8688 return Self::new(DType::Float64, vec![Scalar::Float64(1.0)]);
8689 }
8690 let values: Vec<Scalar> = (0..m)
8691 .map(|n| {
8692 let val =
8693 0.5 - 0.5 * (2.0 * std::f64::consts::PI * n as f64 / (m - 1) as f64).cos();
8694 Scalar::Float64(val)
8695 })
8696 .collect();
8697 Self::new(DType::Float64, values)
8698 }
8699
8700 pub fn hamming(m: usize) -> Result<Self, ColumnError> {
8704 if m == 0 {
8705 return Self::new(DType::Float64, vec![]);
8706 }
8707 if m == 1 {
8708 return Self::new(DType::Float64, vec![Scalar::Float64(1.0)]);
8709 }
8710 let values: Vec<Scalar> = (0..m)
8711 .map(|n| {
8712 let val =
8713 0.54 - 0.46 * (2.0 * std::f64::consts::PI * n as f64 / (m - 1) as f64).cos();
8714 Scalar::Float64(val)
8715 })
8716 .collect();
8717 Self::new(DType::Float64, values)
8718 }
8719
8720 pub fn blackman(m: usize) -> Result<Self, ColumnError> {
8724 if m == 0 {
8725 return Self::new(DType::Float64, vec![]);
8726 }
8727 if m == 1 {
8728 return Self::new(DType::Float64, vec![Scalar::Float64(1.0)]);
8729 }
8730 let values: Vec<Scalar> = (0..m)
8731 .map(|n| {
8732 let x = n as f64 / (m - 1) as f64;
8733 let val = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * x).cos()
8734 + 0.08 * (4.0 * std::f64::consts::PI * x).cos();
8735 Scalar::Float64(val)
8736 })
8737 .collect();
8738 Self::new(DType::Float64, values)
8739 }
8740
8741 pub fn bartlett(m: usize) -> Result<Self, ColumnError> {
8745 if m == 0 {
8746 return Self::new(DType::Float64, vec![]);
8747 }
8748 if m == 1 {
8749 return Self::new(DType::Float64, vec![Scalar::Float64(1.0)]);
8750 }
8751 let half = (m - 1) as f64 / 2.0;
8752 let values: Vec<Scalar> = (0..m)
8753 .map(|n| {
8754 let val = 1.0 - ((n as f64 - half) / half).abs();
8755 Scalar::Float64(val)
8756 })
8757 .collect();
8758 Self::new(DType::Float64, values)
8759 }
8760
8761 #[must_use]
8762 pub fn dtype(&self) -> DType {
8763 self.dtype
8764 }
8765
8766 #[must_use]
8768 pub fn has_nulls(&self) -> bool {
8769 self.validity.count_invalid() > 0
8770 }
8771
8772 #[must_use]
8777 pub fn promote_to_nullable(&self) -> Self {
8778 if !self.has_nulls() {
8779 return self.clone();
8780 }
8781 let new_dtype = self.dtype.to_nullable();
8782 if new_dtype == self.dtype {
8783 return self.clone();
8784 }
8785 Self {
8786 dtype: new_dtype,
8787 values: self.values.clone(),
8788 validity: self.validity.clone(),
8789 data: self.data.clone(),
8790 }
8791 }
8792
8793 #[must_use]
8799 pub fn with_dtype(&self, dtype: DType) -> Self {
8800 Self {
8801 dtype,
8802 values: self.values.clone(),
8803 validity: self.validity.clone(),
8804 data: None,
8805 }
8806 }
8807
8808 #[must_use]
8809 pub fn len(&self) -> usize {
8810 self.values.len()
8811 }
8812
8813 #[must_use]
8815 pub fn size(&self) -> usize {
8816 self.len()
8817 }
8818
8819 #[must_use]
8821 pub fn shape(&self) -> (usize,) {
8822 (self.len(),)
8823 }
8824
8825 #[must_use]
8827 pub fn ndim(&self) -> usize {
8828 1
8829 }
8830
8831 #[must_use]
8832 pub fn is_empty(&self) -> bool {
8833 self.values.is_empty()
8834 }
8835
8836 #[must_use]
8838 pub fn empty(&self) -> bool {
8839 self.is_empty()
8840 }
8841
8842 #[must_use]
8846 pub fn copy(&self) -> Self {
8847 self.clone()
8848 }
8849
8850 #[must_use]
8854 pub fn view(&self) -> Self {
8855 self.clone()
8856 }
8857
8858 #[must_use]
8862 pub fn transpose(&self) -> Self {
8863 self.clone()
8864 }
8865
8866 #[must_use]
8868 pub fn t(&self) -> Self {
8869 self.transpose()
8870 }
8871
8872 #[allow(non_snake_case)]
8874 #[must_use]
8875 pub fn T(&self) -> Self {
8876 self.transpose()
8877 }
8878
8879 #[must_use]
8880 pub fn values(&self) -> &[Scalar] {
8881 &self.values
8882 }
8883
8884 #[must_use]
8885 pub fn value(&self, idx: usize) -> Option<&Scalar> {
8886 self.values.get(idx)
8887 }
8888
8889 pub fn item(&self) -> Result<Scalar, ColumnError> {
8894 match self.values.as_slice() {
8895 [value] => Ok(value.clone()),
8896 values => Err(ColumnError::InvalidLength {
8897 operation: "item()",
8898 expected: 1,
8899 actual: values.len(),
8900 }),
8901 }
8902 }
8903
8904 #[must_use]
8905 pub fn validity(&self) -> &ValidityMask {
8906 &self.validity
8907 }
8908
8909 pub fn iter_values(&self) -> std::slice::Iter<'_, Scalar> {
8915 self.values.iter()
8916 }
8917
8918 #[must_use]
8924 pub fn to_vec(&self) -> Vec<Scalar> {
8925 self.values.to_vec()
8926 }
8927
8928 #[must_use]
8930 pub fn to_list(&self) -> Vec<Scalar> {
8931 self.to_vec()
8932 }
8933
8934 #[must_use]
8936 pub fn tolist(&self) -> Vec<Scalar> {
8937 self.to_list()
8938 }
8939
8940 #[must_use]
8942 pub fn to_numpy(&self) -> Vec<Scalar> {
8943 self.to_vec()
8944 }
8945
8946 #[must_use]
8948 pub fn ravel(&self) -> Vec<Scalar> {
8949 self.to_numpy()
8950 }
8951
8952 #[must_use]
8957 pub fn flatten(&self) -> Vec<Scalar> {
8958 self.values.to_vec()
8959 }
8960
8961 #[must_use]
8965 pub fn asarray(&self) -> Self {
8966 self.clone()
8967 }
8968
8969 #[must_use]
8971 pub fn array(&self) -> Vec<Scalar> {
8972 self.to_vec()
8973 }
8974
8975 #[must_use]
8981 pub fn has_any_missing(&self) -> bool {
8982 if self.dtype == DType::Float64 {
8983 if let Some((data, validity)) = self.as_f64_slice_with_validity() {
8984 return data
8985 .iter()
8986 .enumerate()
8987 .any(|(idx, value)| !validity.get(idx) || value.is_nan());
8988 }
8989 if let Some(data) = self.as_f64_slice() {
8990 return data.iter().any(|value| value.is_nan());
8991 }
8992 }
8993
8994 if matches!(
8995 self.dtype,
8996 DType::Bool
8997 | DType::BoolNullable
8998 | DType::Int64
8999 | DType::Int64Nullable
9000 | DType::Utf8
9001 | DType::Interval
9002 ) {
9003 return self.validity.count_invalid() > 0;
9004 }
9005
9006 self.values.iter().any(Scalar::is_missing)
9007 }
9008
9009 #[must_use]
9011 pub fn hasnans(&self) -> bool {
9012 self.has_any_missing()
9013 }
9014
9015 #[must_use]
9021 pub fn all_missing(&self) -> bool {
9022 if self.dtype == DType::Float64 {
9023 if let Some((data, validity)) = self.as_f64_slice_with_validity() {
9024 return data
9025 .iter()
9026 .enumerate()
9027 .all(|(idx, value)| !validity.get(idx) || value.is_nan());
9028 }
9029 if let Some(data) = self.as_f64_slice() {
9030 return data.iter().all(|value| value.is_nan());
9031 }
9032 }
9033
9034 if matches!(
9035 self.dtype,
9036 DType::Bool
9037 | DType::BoolNullable
9038 | DType::Int64
9039 | DType::Int64Nullable
9040 | DType::Utf8
9041 | DType::Interval
9042 ) {
9043 return self.validity.count_valid() == 0;
9044 }
9045
9046 self.values.iter().all(Scalar::is_missing)
9047 }
9048
9049 #[must_use]
9055 pub fn first(&self) -> Option<&Scalar> {
9056 self.values.first()
9057 }
9058
9059 #[must_use]
9061 pub fn last(&self) -> Option<&Scalar> {
9062 self.values.last()
9063 }
9064
9065 pub fn count_matching<F>(&self, mut predicate: F) -> usize
9072 where
9073 F: FnMut(&Scalar) -> bool,
9074 {
9075 self.values
9076 .iter()
9077 .filter(|v| !v.is_missing() && predicate(v))
9078 .count()
9079 }
9080
9081 pub fn zip_with<F>(&self, other: &Self, mut func: F) -> Result<Self, ColumnError>
9089 where
9090 F: FnMut(&Scalar, &Scalar) -> Scalar,
9091 {
9092 if self.values.len() != other.values.len() {
9093 return Err(ColumnError::LengthMismatch {
9094 left: self.values.len(),
9095 right: other.values.len(),
9096 });
9097 }
9098 let out: Vec<Scalar> = self
9099 .values
9100 .iter()
9101 .zip(other.values.iter())
9102 .map(|(a, b)| func(a, b))
9103 .collect();
9104 let inferred = infer_dtype(&out).unwrap_or(self.dtype);
9105 Self::new(inferred, out)
9106 }
9107
9108 pub fn iter_enumerate(&self) -> std::iter::Enumerate<std::slice::Iter<'_, Scalar>> {
9114 self.values.iter().enumerate()
9115 }
9116
9117 pub fn apply_bool<F>(&self, mut predicate: F) -> Result<Self, ColumnError>
9125 where
9126 F: FnMut(&Scalar) -> bool,
9127 {
9128 let out: Vec<Scalar> = self
9129 .values
9130 .iter()
9131 .map(|v| {
9132 if v.is_missing() {
9133 Scalar::Bool(false)
9134 } else {
9135 Scalar::Bool(predicate(v))
9136 }
9137 })
9138 .collect();
9139 Self::new(DType::Bool, out)
9140 }
9141
9142 pub fn reindex_by_positions(&self, positions: &[Option<usize>]) -> Result<Self, ColumnError> {
9143 let mut present_positions = Vec::with_capacity(positions.len());
9144 let mut all_present = true;
9145 for position in positions {
9146 match position {
9147 Some(idx) if *idx < self.len() => present_positions.push(*idx),
9148 Some(_) | None => {
9149 all_present = false;
9150 break;
9151 }
9152 }
9153 }
9154 if all_present {
9155 return Ok(self.take_positions(&present_positions));
9156 }
9157
9158 let n = positions.len();
9168 if self.validity.all()
9169 && let Some(slice) = self.as_i64_slice()
9170 {
9171 let mut data = Vec::with_capacity(n);
9172 let mut words = vec![0_u64; n.div_ceil(64)];
9173 for (out_idx, slot) in positions.iter().enumerate() {
9174 match slot {
9175 Some(idx) if *idx < slice.len() => {
9176 data.push(slice[*idx]);
9177 words[out_idx / 64] |= 1_u64 << (out_idx % 64);
9178 }
9179 _ => data.push(0),
9180 }
9181 }
9182 return Ok(Self::from_i64_values_with_validity(
9183 data,
9184 ValidityMask::from_words(words, n),
9185 ));
9186 }
9187 if self.validity.all()
9188 && let Some(slice) = self.as_f64_slice()
9189 {
9190 let mut data = Vec::with_capacity(n);
9191 let mut words = vec![0_u64; n.div_ceil(64)];
9192 for (out_idx, slot) in positions.iter().enumerate() {
9193 match slot {
9194 Some(idx) if *idx < slice.len() => {
9195 data.push(slice[*idx]);
9196 words[out_idx / 64] |= 1_u64 << (out_idx % 64);
9197 }
9198 _ => data.push(0.0),
9199 }
9200 }
9201 return Ok(Self::from_f64_values_with_validity(
9202 data,
9203 ValidityMask::from_words(words, n),
9204 ));
9205 }
9206
9207 if self.dtype == DType::Utf8
9219 && self.validity.all()
9220 && let Some(source) = self.values.eager_arc()
9221 {
9222 let source_len = source.len();
9223 let mut plan = Vec::with_capacity(n);
9224 let mut words = vec![0_u64; n.div_ceil(64)];
9225 for (out_idx, slot) in positions.iter().enumerate() {
9226 match slot {
9227 Some(idx) if *idx < source_len => {
9228 plan.push(*idx);
9229 words[out_idx / 64] |= 1_u64 << (out_idx % 64);
9230 }
9231 _ => plan.push(usize::MAX),
9232 }
9233 }
9234 return Ok(Self::from_utf8_lazy_gather(
9235 Arc::clone(source),
9236 plan.into(),
9237 ValidityMask::from_words(words, n),
9238 ));
9239 }
9240
9241 if self.dtype == DType::Utf8
9250 && let Some(strs) = self.as_all_valid_str_vec()
9251 {
9252 let mut new_bytes = Vec::new();
9253 let mut new_offsets = Vec::with_capacity(n + 1);
9254 new_offsets.push(0);
9255 let mut words = vec![0_u64; n.div_ceil(64)];
9256 for (out_idx, slot) in positions.iter().enumerate() {
9257 if let Some(idx) = slot
9258 && *idx < strs.len()
9259 {
9260 new_bytes.extend_from_slice(strs[*idx].as_bytes());
9261 words[out_idx / 64] |= 1_u64 << (out_idx % 64);
9262 }
9263 new_offsets.push(new_bytes.len());
9264 }
9265 return Ok(Self::from_utf8_values_with_validity(
9266 new_bytes,
9267 new_offsets,
9268 ValidityMask::from_words(words, n),
9269 ));
9270 }
9271
9272 let values = positions
9273 .iter()
9274 .map(|slot| match slot {
9275 Some(idx) => self
9276 .values
9277 .get(*idx)
9278 .cloned()
9279 .unwrap_or_else(|| Scalar::missing_for_dtype(self.dtype)),
9280 None => Scalar::missing_for_dtype(self.dtype),
9281 })
9282 .collect::<Vec<_>>();
9283
9284 let validity = ValidityMask::from_values(&values);
9285 Ok(Self {
9286 dtype: self.dtype,
9287 values: ScalarValues::from_vec(values),
9288 validity,
9289 data: None,
9290 })
9291 }
9292
9293 #[doc(hidden)]
9296 pub fn reindex_by_positions_with_absent_scalar(
9297 &self,
9298 positions: &[Option<usize>],
9299 absent: Scalar,
9300 ) -> Result<Self, ColumnError> {
9301 let mut present_positions = Vec::with_capacity(positions.len());
9302 let mut all_present = true;
9303 for position in positions {
9304 match position {
9305 Some(idx) if *idx < self.len() => present_positions.push(*idx),
9306 Some(_) | None => {
9307 all_present = false;
9308 break;
9309 }
9310 }
9311 }
9312 if all_present {
9313 return Ok(self.take_positions(&present_positions));
9314 }
9315
9316 if absent == Scalar::missing_for_dtype(self.dtype) {
9317 return self.reindex_by_positions(positions);
9318 }
9319
9320 let values = positions
9321 .iter()
9322 .map(|slot| match slot {
9323 Some(idx) => self
9324 .values
9325 .get(*idx)
9326 .cloned()
9327 .unwrap_or_else(|| absent.clone()),
9328 None => absent.clone(),
9329 })
9330 .collect::<Vec<_>>();
9331 let validity = ValidityMask::from_values(&values);
9332 Ok(Self {
9333 dtype: self.dtype,
9334 values: ScalarValues::from_vec(values),
9335 validity,
9336 data: None,
9337 })
9338 }
9339
9340 fn try_vectorized_binary(
9346 &self,
9347 right: &Self,
9348 op: ArithmeticOp,
9349 out_dtype: DType,
9350 ) -> Option<Result<Self, ColumnError>> {
9351 match out_dtype {
9354 DType::Float64 => {
9355 if let (Some(l), Some(r)) = (self.as_f64_slice(), right.as_f64_slice()) {
9364 let apply = binary_f64_apply(op);
9365 let result: Vec<f64> = l.iter().zip(r).map(|(&a, &b)| apply(a, b)).collect();
9366 return Some(Ok(Self::from_f64_values(result)));
9367 }
9368 let left_data = ColumnData::from_scalars(&self.values, DType::Float64);
9369 let right_data = ColumnData::from_scalars(&right.values, DType::Float64);
9370 let (ColumnData::Float64(l), ColumnData::Float64(r)) = (&left_data, &right_data)
9371 else {
9372 return None;
9373 };
9374
9375 let left_nan_aware = self.nan_aware_validity();
9378 let right_nan_aware = right.nan_aware_validity();
9379
9380 let (result_data, result_validity) =
9381 vectorized_binary_f64(l, r, &left_nan_aware, &right_nan_aware, op);
9382
9383 if result_validity.all() {
9388 return Some(Ok(Self::from_f64_values(result_data)));
9389 }
9390
9391 let values: Vec<Scalar> = result_data
9394 .iter()
9395 .enumerate()
9396 .map(|(i, v)| {
9397 if !result_validity.get(i) {
9398 if self.is_nan_at(i) || right.is_nan_at(i) {
9400 Scalar::Null(NullKind::NaN)
9401 } else {
9402 Scalar::missing_for_dtype(out_dtype)
9403 }
9404 } else {
9405 Scalar::Float64(*v)
9406 }
9407 })
9408 .collect();
9409
9410 Some(Self::new(out_dtype, values))
9411 }
9412 DType::Int64 if !matches!(op, ArithmeticOp::Div) => {
9413 if self.dtype != DType::Int64 || right.dtype != DType::Int64 {
9415 return None;
9416 }
9417 if let (Some(l), Some(r)) = (self.as_i64_slice(), right.as_i64_slice()) {
9423 let (result_data, _validity) =
9424 vectorized_binary_i64(l, r, &self.validity, &right.validity, op)?;
9425 return Some(Ok(Self::from_i64_values(result_data)));
9426 }
9427 let left_data = ColumnData::from_scalars(&self.values, DType::Int64);
9428 let right_data = ColumnData::from_scalars(&right.values, DType::Int64);
9429 let (ColumnData::Int64(l), ColumnData::Int64(r)) = (&left_data, &right_data) else {
9430 return None;
9431 };
9432
9433 let (result_data, result_validity) =
9434 vectorized_binary_i64(l, r, &self.validity, &right.validity, op)?;
9435
9436 if result_validity.all() {
9439 return Some(Ok(Self::from_i64_values(result_data)));
9440 }
9441
9442 let values: Vec<Scalar> = result_data
9443 .iter()
9444 .enumerate()
9445 .map(|(i, v)| {
9446 if !result_validity.get(i) {
9447 Scalar::missing_for_dtype(out_dtype)
9448 } else {
9449 Scalar::Int64(*v)
9450 }
9451 })
9452 .collect();
9453
9454 Some(Self::new(out_dtype, values))
9455 }
9456 _ => None, }
9458 }
9459
9460 pub fn aligned_binary_f64(
9475 &self,
9476 right: &Self,
9477 left_positions: &[Option<usize>],
9478 right_positions: &[Option<usize>],
9479 op: ArithmeticOp,
9480 ) -> Result<Self, ColumnError> {
9481 debug_assert_eq!(left_positions.len(), right_positions.len());
9482 let out_len = left_positions.len();
9483
9484 let lsrc = self.float64_binary_data();
9485 let rsrc = right.float64_binary_data();
9486 let lvalid = &self.validity;
9496 let rvalid = &right.validity;
9497
9498 let apply = binary_f64_apply(op);
9499
9500 let mut data = Vec::with_capacity(out_len);
9501 let mut words = vec![0_u64; out_len.div_ceil(64)];
9502 let mut all_valid = true;
9503 for (k, left_slot) in left_positions.iter().enumerate() {
9504 if let Some(i) = *left_slot
9505 && let Some(j) = right_positions.get(k).copied().flatten()
9506 && lvalid.get(i)
9507 && !lsrc[i].is_nan()
9508 && rvalid.get(j)
9509 && !rsrc[j].is_nan()
9510 {
9511 let value = apply(lsrc[i], rsrc[j]);
9512 data.push(value);
9513 if value.is_nan() {
9514 all_valid = false;
9515 } else {
9516 words[k / 64] |= 1_u64 << (k % 64);
9517 }
9518 } else {
9519 data.push(0.0);
9520 all_valid = false;
9521 }
9522 }
9523 if all_valid {
9524 return Ok(Self::from_f64_values_all_valid_unchecked(data));
9525 }
9526 Ok(Self::from_f64_values_with_validity(
9527 data,
9528 ValidityMask::from_words(words, out_len),
9529 ))
9530 }
9531
9532 pub fn aligned_binary_f64_int64_unit_ranges(
9540 &self,
9541 right: &Self,
9542 left_range: (i64, i64),
9543 right_range: (i64, i64),
9544 union_range: (i64, i64),
9545 op: ArithmeticOp,
9546 ) -> Result<Self, ColumnError> {
9547 if !matches!(self.dtype, DType::Float64) || !matches!(right.dtype, DType::Float64) {
9548 return Err(ColumnError::DTypeMismatch {
9549 left: self.dtype,
9550 right: right.dtype,
9551 });
9552 }
9553
9554 let (left_start, left_end) = left_range;
9555 let (right_start, right_end) = right_range;
9556 let (union_start, union_end) = union_range;
9557
9558 let Some(left_len) = unit_range_len(left_start, left_end) else {
9559 return Err(ColumnError::LengthMismatch {
9560 left: self.len(),
9561 right: right.len(),
9562 });
9563 };
9564 let Some(right_len) = unit_range_len(right_start, right_end) else {
9565 return Err(ColumnError::LengthMismatch {
9566 left: self.len(),
9567 right: right.len(),
9568 });
9569 };
9570 let Some(out_len) = unit_range_len(union_start, union_end) else {
9571 return Err(ColumnError::LengthMismatch {
9572 left: self.len(),
9573 right: right.len(),
9574 });
9575 };
9576 if left_len != self.len() || right_len != right.len() {
9577 return Err(ColumnError::LengthMismatch {
9578 left: self.len(),
9579 right: right.len(),
9580 });
9581 }
9582
9583 let lsrc = self.float64_binary_data();
9584 let rsrc = right.float64_binary_data();
9585 let lvalid = self.nan_aware_validity();
9586 let rvalid = right.nan_aware_validity();
9587 let apply = binary_f64_apply(op);
9588
9589 let mut data = vec![0.0; out_len];
9590 let mut words = vec![0_u64; out_len.div_ceil(64)];
9591 let overlap_start = left_start.max(right_start);
9592 let overlap_end = left_end.min(right_end);
9593 let mut all_valid = overlap_start == union_start && overlap_end == union_end;
9594
9595 if overlap_start <= overlap_end {
9596 for value in overlap_start..=overlap_end {
9597 let out_idx = (value - union_start) as usize;
9598 let left_idx = (value - left_start) as usize;
9599 let right_idx = (value - right_start) as usize;
9600 if lvalid.get(left_idx) && rvalid.get(right_idx) {
9601 let result = apply(lsrc[left_idx], rsrc[right_idx]);
9602 data[out_idx] = result;
9603 if result.is_nan() {
9604 all_valid = false;
9605 } else {
9606 words[out_idx / 64] |= 1_u64 << (out_idx % 64);
9607 }
9608 } else {
9609 all_valid = false;
9610 }
9611 }
9612 }
9613
9614 if all_valid {
9615 return Ok(Self::from_f64_values(data));
9616 }
9617 Ok(Self::from_f64_values_with_validity(
9618 data,
9619 ValidityMask::from_words(words, out_len),
9620 ))
9621 }
9622
9623 pub fn aligned_binary_f64_same_positions(
9629 &self,
9630 right: &Self,
9631 op: ArithmeticOp,
9632 ) -> Result<Self, ColumnError> {
9633 debug_assert_eq!(self.len(), right.len());
9634 let out_len = self.len();
9635
9636 let lsrc = self.float64_binary_data();
9637 let rsrc = right.float64_binary_data();
9638
9639 if self.validity.all() && right.validity.all() {
9671 let (data, input_nan, output_nan) = apply_f64_slices_nan_tracked(op, &lsrc, &rsrc);
9672 if !input_nan {
9673 if output_nan {
9674 return Ok(Self::from_f64_values(data));
9675 }
9676 return Ok(Self::from_f64_values_all_valid_unchecked(data));
9677 }
9678 }
9679
9680 let lvalid = self.nan_aware_validity();
9681 let rvalid = right.nan_aware_validity();
9682 let apply = binary_f64_apply(op);
9683
9684 let mut data = Vec::with_capacity(out_len);
9685 let mut all_valid = true;
9686 for i in 0..out_len {
9687 if lvalid.get(i) && rvalid.get(i) {
9688 data.push(apply(lsrc[i], rsrc[i]));
9689 } else {
9690 all_valid = false;
9691 break;
9692 }
9693 }
9694 if all_valid {
9695 return Ok(Self::from_f64_values(data));
9696 }
9697
9698 let mut values = Vec::with_capacity(out_len);
9699 for i in 0..out_len {
9700 if lvalid.get(i) && rvalid.get(i) {
9701 values.push(Scalar::Float64(apply(lsrc[i], rsrc[i])));
9702 } else {
9703 values.push(Scalar::Null(NullKind::NaN));
9704 }
9705 }
9706 Self::new(DType::Float64, values)
9707 }
9708
9709 fn cached_float64_data(&self) -> Option<&[f64]> {
9710 match &self.data {
9711 Some(ColumnData::Float64(data)) if data.len() == self.values.len() => {
9712 return Some(data.as_ref());
9713 }
9714 _ => {}
9715 }
9716
9717 match &self.values {
9718 ScalarValues::LazyAllValidFloat64 { data, .. } if data.len() == self.validity.len() => {
9719 Some(data.as_ref())
9720 }
9721 ScalarValues::LazyStridedFloat64 { len, .. } if *len == self.validity.len() => {
9722 self.values.strided_float64_data()
9723 }
9724 ScalarValues::LazyNullableFloat64 { data, .. } if data.len() == self.validity.len() => {
9725 Some(data.as_slice())
9726 }
9727 ScalarValues::LazyCombineFirstFloat64 { len, .. } if *len == self.validity.len() => {
9728 self.values.combine_first_float64_data()
9729 }
9730 ScalarValues::LazyRepeatedSlicesFloat64 { total_len, .. }
9731 if *total_len == self.validity.len() =>
9732 {
9733 self.values.repeated_slices_f64_data()
9734 }
9735 _ => None,
9736 }
9737 }
9738
9739 fn float64_binary_data(&self) -> std::borrow::Cow<'_, [f64]> {
9740 if let Some(data) = self.cached_float64_data() {
9741 return std::borrow::Cow::Borrowed(data);
9742 }
9743
9744 match ColumnData::from_scalars(&self.values, DType::Float64) {
9745 ColumnData::Float64(data) => std::borrow::Cow::Owned(data.to_vec()),
9746 _ => unreachable!("Float64 materialization must produce Float64 data"),
9747 }
9748 }
9749
9750 #[must_use]
9752 fn nan_aware_validity(&self) -> ValidityMask {
9753 let mut mask = self.validity.clone();
9754
9755 if let Some(data) = self.cached_float64_data() {
9756 for (i, value) in data.iter().enumerate() {
9757 if value.is_nan() {
9758 mask.set(i, false);
9759 }
9760 }
9761 return mask;
9762 }
9763
9764 for (i, value) in self.values.iter().enumerate() {
9765 if matches!(value, Scalar::Float64(f) if f.is_nan()) {
9766 mask.set(i, false);
9767 }
9768 }
9769 mask
9770 }
9771
9772 fn is_nan_at(&self, i: usize) -> bool {
9774 self.values.get(i).is_some_and(|v| v.is_nan())
9775 }
9776
9777 pub fn binary_numeric(&self, right: &Self, op: ArithmeticOp) -> Result<Self, ColumnError> {
9778 if self.len() != right.len() {
9779 return Err(ColumnError::LengthMismatch {
9780 left: self.len(),
9781 right: right.len(),
9782 });
9783 }
9784
9785 let mut out_dtype = common_dtype(self.dtype, right.dtype)?;
9786 if matches!(out_dtype, DType::Bool) {
9787 out_dtype = DType::Int64;
9788 }
9789 let int_pow = matches!(op, ArithmeticOp::Pow)
9793 && self.dtype == DType::Int64
9794 && right.dtype == DType::Int64;
9795 if matches!(op, ArithmeticOp::Div | ArithmeticOp::Pow) && !int_pow {
9796 out_dtype = DType::Float64;
9797 }
9798
9799 if let Some(result) = self.try_vectorized_binary(right, op, out_dtype) {
9801 return result;
9802 }
9803
9804 if matches!(op, ArithmeticOp::Mod | ArithmeticOp::FloorDiv)
9806 && matches!(out_dtype, DType::Int64)
9807 {
9808 out_dtype = DType::Float64;
9809 }
9810
9811 let values = self
9813 .values
9814 .iter()
9815 .zip(&right.values)
9816 .map(|(left, right)| {
9817 if left.is_missing() || right.is_missing() {
9818 return Ok::<_, ColumnError>(if left.is_nan() || right.is_nan() {
9819 Scalar::Null(NullKind::NaN)
9820 } else {
9821 Scalar::missing_for_dtype(out_dtype)
9822 });
9823 }
9824
9825 if matches!(out_dtype, DType::Int64) {
9826 let lhs_i64 = match cast_scalar(left, DType::Int64)? {
9827 Scalar::Int64(v) => v,
9828 _ => unreachable!(),
9829 };
9830 let rhs_i64 = match cast_scalar(right, DType::Int64)? {
9831 Scalar::Int64(v) => v,
9832 _ => unreachable!(),
9833 };
9834 let result = match op {
9835 ArithmeticOp::Add => lhs_i64.wrapping_add(rhs_i64),
9836 ArithmeticOp::Sub => lhs_i64.wrapping_sub(rhs_i64),
9837 ArithmeticOp::Mul => lhs_i64.wrapping_mul(rhs_i64),
9838 ArithmeticOp::Pow => {
9842 if rhs_i64 < 0 {
9843 return Err(ColumnError::NegativeIntegerPower);
9844 }
9845 lhs_i64.wrapping_pow(u32::try_from(rhs_i64).unwrap_or(u32::MAX))
9846 }
9847 ArithmeticOp::Div | ArithmeticOp::Mod | ArithmeticOp::FloorDiv => {
9848 unreachable!()
9849 }
9850 };
9851 return Ok(Scalar::Int64(result));
9852 }
9853
9854 let lhs = left.to_f64()?;
9855 let rhs = right.to_f64()?;
9856 let result = match op {
9857 ArithmeticOp::Add => lhs + rhs,
9858 ArithmeticOp::Sub => lhs - rhs,
9859 ArithmeticOp::Mul => lhs * rhs,
9860 ArithmeticOp::Div => lhs / rhs,
9861 ArithmeticOp::Mod => python_mod_f64(lhs, rhs),
9862 ArithmeticOp::Pow => lhs.powf(rhs),
9863 ArithmeticOp::FloorDiv => python_floor_div_f64(lhs, rhs),
9864 };
9865
9866 Ok(Scalar::Float64(result))
9867 })
9868 .collect::<Result<Vec<_>, _>>()?;
9869
9870 Self::new(out_dtype, values)
9871 }
9872
9873 pub fn add(&self, right: &Self) -> Result<Self, ColumnError> {
9875 self.binary_numeric(right, ArithmeticOp::Add)
9876 }
9877
9878 pub fn radd(&self, left: &Self) -> Result<Self, ColumnError> {
9880 left.binary_numeric(self, ArithmeticOp::Add)
9881 }
9882
9883 pub fn sub(&self, right: &Self) -> Result<Self, ColumnError> {
9885 self.binary_numeric(right, ArithmeticOp::Sub)
9886 }
9887
9888 pub fn rsub(&self, left: &Self) -> Result<Self, ColumnError> {
9890 left.binary_numeric(self, ArithmeticOp::Sub)
9891 }
9892
9893 pub fn subtract(&self, right: &Self) -> Result<Self, ColumnError> {
9895 self.sub(right)
9896 }
9897
9898 pub fn mul(&self, right: &Self) -> Result<Self, ColumnError> {
9900 self.binary_numeric(right, ArithmeticOp::Mul)
9901 }
9902
9903 pub fn rmul(&self, left: &Self) -> Result<Self, ColumnError> {
9905 left.binary_numeric(self, ArithmeticOp::Mul)
9906 }
9907
9908 pub fn multiply(&self, right: &Self) -> Result<Self, ColumnError> {
9910 self.mul(right)
9911 }
9912
9913 pub fn div(&self, right: &Self) -> Result<Self, ColumnError> {
9915 self.binary_numeric(right, ArithmeticOp::Div)
9916 }
9917
9918 pub fn rdiv(&self, left: &Self) -> Result<Self, ColumnError> {
9920 left.binary_numeric(self, ArithmeticOp::Div)
9921 }
9922
9923 pub fn divide(&self, right: &Self) -> Result<Self, ColumnError> {
9925 self.div(right)
9926 }
9927
9928 pub fn truediv(&self, right: &Self) -> Result<Self, ColumnError> {
9930 self.div(right)
9931 }
9932
9933 pub fn rtruediv(&self, left: &Self) -> Result<Self, ColumnError> {
9935 self.rdiv(left)
9936 }
9937
9938 pub fn floordiv(&self, right: &Self) -> Result<Self, ColumnError> {
9940 self.binary_numeric(right, ArithmeticOp::FloorDiv)
9941 }
9942
9943 pub fn rfloordiv(&self, left: &Self) -> Result<Self, ColumnError> {
9945 left.binary_numeric(self, ArithmeticOp::FloorDiv)
9946 }
9947
9948 pub fn r#mod(&self, right: &Self) -> Result<Self, ColumnError> {
9950 self.binary_numeric(right, ArithmeticOp::Mod)
9951 }
9952
9953 pub fn rmod(&self, left: &Self) -> Result<Self, ColumnError> {
9955 left.binary_numeric(self, ArithmeticOp::Mod)
9956 }
9957
9958 pub fn pow(&self, right: &Self) -> Result<Self, ColumnError> {
9960 self.binary_numeric(right, ArithmeticOp::Pow)
9961 }
9962
9963 pub fn rpow(&self, left: &Self) -> Result<Self, ColumnError> {
9965 left.binary_numeric(self, ArithmeticOp::Pow)
9966 }
9967
9968 pub fn power(&self, right: &Self) -> Result<Self, ColumnError> {
9970 self.pow(right)
9971 }
9972
9973 pub fn float_power(&self, right: &Self) -> Result<Self, ColumnError> {
9979 if self.len() != right.len() {
9980 return Err(ColumnError::LengthMismatch {
9981 left: self.len(),
9982 right: right.len(),
9983 });
9984 }
9985 if let Some(out) = self.typed_float_binary(right, |b, e| b.powf(e)) {
9986 return Ok(out);
9987 }
9988 let mut out = Vec::with_capacity(self.values.len());
9989 for (base, exp) in self.values.iter().zip(&right.values) {
9990 if base.is_missing() || exp.is_missing() {
9991 out.push(Scalar::Float64(f64::NAN));
9992 continue;
9993 }
9994 let b = base.to_f64().map_err(ColumnError::Type)?;
9995 let e = exp.to_f64().map_err(ColumnError::Type)?;
9996 let result = b.powf(e);
9997 out.push(Scalar::Float64(result));
9998 }
9999 Self::new(DType::Float64, out)
10000 }
10001
10002 pub fn remainder(&self, right: &Self) -> Result<Self, ColumnError> {
10004 self.r#mod(right)
10005 }
10006
10007 pub fn floor_divide(&self, right: &Self) -> Result<Self, ColumnError> {
10009 self.floordiv(right)
10010 }
10011
10012 pub fn true_divide(&self, right: &Self) -> Result<Self, ColumnError> {
10014 self.div(right)
10015 }
10016
10017 pub fn atan2(&self, other: &Self) -> Result<Self, ColumnError> {
10019 if self.len() != other.len() {
10020 return Err(ColumnError::LengthMismatch {
10021 left: self.len(),
10022 right: other.len(),
10023 });
10024 }
10025 if let Some(out) = self.typed_float_binary(other, |y, x| y.atan2(x)) {
10026 return Ok(out);
10027 }
10028 let mut out = Vec::with_capacity(self.values.len());
10029 for (y, x) in self.values.iter().zip(&other.values) {
10030 if y.is_missing() || x.is_missing() {
10031 out.push(Scalar::Float64(f64::NAN));
10032 continue;
10033 }
10034 let yf = y.to_f64().map_err(ColumnError::Type)?;
10035 let xf = x.to_f64().map_err(ColumnError::Type)?;
10036 out.push(Scalar::Float64(yf.atan2(xf)));
10037 }
10038 Self::new(DType::Float64, out)
10039 }
10040
10041 pub fn hypot(&self, other: &Self) -> Result<Self, ColumnError> {
10043 if self.len() != other.len() {
10044 return Err(ColumnError::LengthMismatch {
10045 left: self.len(),
10046 right: other.len(),
10047 });
10048 }
10049 if let Some(out) = self.typed_float_binary(other, |a, b| a.hypot(b)) {
10050 return Ok(out);
10051 }
10052 let mut out = Vec::with_capacity(self.values.len());
10053 for (a, b) in self.values.iter().zip(&other.values) {
10054 if a.is_missing() || b.is_missing() {
10055 out.push(Scalar::Float64(f64::NAN));
10056 continue;
10057 }
10058 let af = a.to_f64().map_err(ColumnError::Type)?;
10059 let bf = b.to_f64().map_err(ColumnError::Type)?;
10060 out.push(Scalar::Float64(af.hypot(bf)));
10061 }
10062 Self::new(DType::Float64, out)
10063 }
10064
10065 pub fn fmod(&self, other: &Self) -> Result<Self, ColumnError> {
10067 if self.len() != other.len() {
10068 return Err(ColumnError::LengthMismatch {
10069 left: self.len(),
10070 right: other.len(),
10071 });
10072 }
10073 if let Some(out) = self.typed_float_binary(other, |a, b| a % b) {
10074 return Ok(out);
10075 }
10076 let mut out = Vec::with_capacity(self.values.len());
10077 for (a, b) in self.values.iter().zip(&other.values) {
10078 if a.is_missing() || b.is_missing() {
10079 out.push(Scalar::Float64(f64::NAN));
10080 continue;
10081 }
10082 let af = a.to_f64().map_err(ColumnError::Type)?;
10083 let bf = b.to_f64().map_err(ColumnError::Type)?;
10084 out.push(Scalar::Float64(af % bf));
10085 }
10086 Self::new(DType::Float64, out)
10087 }
10088
10089 pub fn copysign(&self, other: &Self) -> Result<Self, ColumnError> {
10091 if self.len() != other.len() {
10092 return Err(ColumnError::LengthMismatch {
10093 left: self.len(),
10094 right: other.len(),
10095 });
10096 }
10097 if let Some(out) = self.typed_float_binary(other, |m, s| m.copysign(s)) {
10098 return Ok(out);
10099 }
10100 let mut out = Vec::with_capacity(self.values.len());
10101 for (mag, sign) in self.values.iter().zip(&other.values) {
10102 if mag.is_missing() || sign.is_missing() {
10103 out.push(Scalar::Float64(f64::NAN));
10104 continue;
10105 }
10106 let mf = mag.to_f64().map_err(ColumnError::Type)?;
10107 let sf = sign.to_f64().map_err(ColumnError::Type)?;
10108 out.push(Scalar::Float64(mf.copysign(sf)));
10109 }
10110 Self::new(DType::Float64, out)
10111 }
10112
10113 pub fn sign(&self) -> Result<Self, ColumnError> {
10115 if let Some(data) = self.as_i64_slice() {
10120 return Ok(Self::from_i64_values(
10121 data.iter()
10122 .map(|&x| {
10123 if x > 0 {
10124 1
10125 } else if x < 0 {
10126 -1
10127 } else {
10128 0
10129 }
10130 })
10131 .collect(),
10132 ));
10133 }
10134 if let Some(data) = self.as_f64_slice() {
10135 let out: Vec<f64> = data
10140 .iter()
10141 .map(|&x| {
10142 if x > 0.0 {
10143 1.0
10144 } else if x < 0.0 {
10145 -1.0
10146 } else {
10147 0.0
10148 }
10149 })
10150 .collect();
10151 return Ok(Self::from_f64_all_valid_with_finite_opt(out, Some(true)));
10152 }
10153 let mut out = Vec::with_capacity(self.values.len());
10154 for v in &self.values {
10155 if v.is_missing() {
10156 out.push(Scalar::Float64(f64::NAN));
10157 continue;
10158 }
10159 match v {
10160 Scalar::Int64(x) => {
10161 let s = if *x > 0 {
10162 1
10163 } else if *x < 0 {
10164 -1
10165 } else {
10166 0
10167 };
10168 out.push(Scalar::Int64(s));
10169 }
10170 Scalar::Float64(x) => {
10171 let s = if x.is_nan() {
10172 f64::NAN
10173 } else if *x > 0.0 {
10174 1.0
10175 } else if *x < 0.0 {
10176 -1.0
10177 } else {
10178 0.0
10179 };
10180 out.push(Scalar::Float64(s));
10181 }
10182 _ => {
10183 return Err(ColumnError::Type(TypeError::NonNumericValue {
10184 value: format!("{v:?}"),
10185 dtype: self.dtype,
10186 }));
10187 }
10188 }
10189 }
10190 let dtype = match self.dtype {
10191 DType::Int64 => DType::Int64,
10192 _ => DType::Float64,
10193 };
10194 Self::new(dtype, out)
10195 }
10196
10197 pub fn signbit(&self) -> Result<Self, ColumnError> {
10201 if let Some(data) = self.as_i64_slice() {
10205 return Ok(Self::from_bool_values(
10206 data.iter().map(|&x| x < 0).collect(),
10207 ));
10208 }
10209 if let Some(data) = self.as_f64_slice() {
10210 return Ok(Self::from_bool_values(
10211 data.iter().map(|&x| x.is_sign_negative()).collect(),
10212 ));
10213 }
10214 let mut out = Vec::with_capacity(self.values.len());
10215 for v in &self.values {
10216 if v.is_missing() {
10217 out.push(Scalar::Bool(false));
10218 continue;
10219 }
10220 match v {
10221 Scalar::Int64(x) => out.push(Scalar::Bool(*x < 0)),
10222 Scalar::Float64(x) => out.push(Scalar::Bool(x.is_sign_negative())),
10223 _ => {
10224 return Err(ColumnError::Type(TypeError::NonNumericValue {
10225 value: format!("{v:?}"),
10226 dtype: self.dtype,
10227 }));
10228 }
10229 }
10230 }
10231 Self::new(DType::Bool, out)
10232 }
10233
10234 pub fn heaviside(&self, h0: f64) -> Result<Self, ColumnError> {
10241 let mut out = Vec::with_capacity(self.values.len());
10242 for v in &self.values {
10243 if v.is_missing() {
10244 out.push(Scalar::Float64(f64::NAN));
10245 continue;
10246 }
10247 match v {
10248 Scalar::Int64(x) => {
10249 let val = if *x < 0 {
10250 0.0
10251 } else if *x > 0 {
10252 1.0
10253 } else {
10254 h0
10255 };
10256 out.push(Scalar::Float64(val));
10257 }
10258 Scalar::Float64(x) => {
10259 let val = if x.is_nan() {
10260 f64::NAN
10261 } else if *x < 0.0 {
10262 0.0
10263 } else if *x > 0.0 {
10264 1.0
10265 } else {
10266 h0
10267 };
10268 out.push(Scalar::Float64(val));
10269 }
10270 _ => {
10271 return Err(ColumnError::Type(TypeError::NonNumericValue {
10272 value: format!("{v:?}"),
10273 dtype: self.dtype,
10274 }));
10275 }
10276 }
10277 }
10278 Self::new(DType::Float64, out)
10279 }
10280
10281 pub fn gcd(&self, other: &Self) -> Result<Self, ColumnError> {
10285 if self.len() != other.len() {
10286 return Err(ColumnError::LengthMismatch {
10287 left: self.len(),
10288 right: other.len(),
10289 });
10290 }
10291 fn compute_gcd(mut a: i64, mut b: i64) -> i64 {
10292 a = a.abs();
10293 b = b.abs();
10294 while b != 0 {
10295 let t = b;
10296 b = a % b;
10297 a = t;
10298 }
10299 a
10300 }
10301 let mut out = Vec::with_capacity(self.values.len());
10302 for (a, b) in self.values.iter().zip(&other.values) {
10303 if a.is_missing() || b.is_missing() {
10304 out.push(Scalar::Null(NullKind::Null));
10305 continue;
10306 }
10307 match (a, b) {
10308 (Scalar::Int64(x), Scalar::Int64(y)) => {
10309 out.push(Scalar::Int64(compute_gcd(*x, *y)));
10310 }
10311 _ => {
10312 return Err(ColumnError::Type(TypeError::NonNumericValue {
10313 value: format!("{a:?}"),
10314 dtype: self.dtype,
10315 }));
10316 }
10317 }
10318 }
10319 Self::new(DType::Int64, out)
10320 }
10321
10322 pub fn lcm(&self, other: &Self) -> Result<Self, ColumnError> {
10326 if self.len() != other.len() {
10327 return Err(ColumnError::LengthMismatch {
10328 left: self.len(),
10329 right: other.len(),
10330 });
10331 }
10332 fn compute_gcd(mut a: i64, mut b: i64) -> i64 {
10333 a = a.abs();
10334 b = b.abs();
10335 while b != 0 {
10336 let t = b;
10337 b = a % b;
10338 a = t;
10339 }
10340 a
10341 }
10342 let mut out = Vec::with_capacity(self.values.len());
10343 for (a, b) in self.values.iter().zip(&other.values) {
10344 if a.is_missing() || b.is_missing() {
10345 out.push(Scalar::Null(NullKind::Null));
10346 continue;
10347 }
10348 match (a, b) {
10349 (Scalar::Int64(x), Scalar::Int64(y)) => {
10350 let g = compute_gcd(*x, *y);
10351 let result = if g == 0 { 0 } else { (x.abs() / g) * y.abs() };
10352 out.push(Scalar::Int64(result));
10353 }
10354 _ => {
10355 return Err(ColumnError::Type(TypeError::NonNumericValue {
10356 value: format!("{a:?}"),
10357 dtype: self.dtype,
10358 }));
10359 }
10360 }
10361 }
10362 Self::new(DType::Int64, out)
10363 }
10364
10365 pub fn bitwise_and(&self, other: &Self) -> Result<Self, ColumnError> {
10367 if self.len() != other.len() {
10368 return Err(ColumnError::LengthMismatch {
10369 left: self.len(),
10370 right: other.len(),
10371 });
10372 }
10373 if let Some(out) = self.typed_bool_binary(other, |left, right| left && right) {
10374 return Ok(out);
10375 }
10376 let mut out = Vec::with_capacity(self.values.len());
10377 for (a, b) in self.values.iter().zip(&other.values) {
10378 if a.is_missing() || b.is_missing() {
10379 out.push(Scalar::Null(NullKind::Null));
10380 continue;
10381 }
10382 match (a, b) {
10383 (Scalar::Int64(x), Scalar::Int64(y)) => out.push(Scalar::Int64(x & y)),
10384 (Scalar::Bool(x), Scalar::Bool(y)) => out.push(Scalar::Bool(*x && *y)),
10385 _ => {
10386 return Err(ColumnError::Type(TypeError::NonNumericValue {
10387 value: format!("{a:?}"),
10388 dtype: self.dtype,
10389 }));
10390 }
10391 }
10392 }
10393 Self::new(self.dtype, out)
10394 }
10395
10396 pub fn bitwise_or(&self, other: &Self) -> Result<Self, ColumnError> {
10398 if self.len() != other.len() {
10399 return Err(ColumnError::LengthMismatch {
10400 left: self.len(),
10401 right: other.len(),
10402 });
10403 }
10404 if let Some(out) = self.typed_bool_binary(other, |left, right| left || right) {
10405 return Ok(out);
10406 }
10407 let mut out = Vec::with_capacity(self.values.len());
10408 for (a, b) in self.values.iter().zip(&other.values) {
10409 if a.is_missing() || b.is_missing() {
10410 out.push(Scalar::Null(NullKind::Null));
10411 continue;
10412 }
10413 match (a, b) {
10414 (Scalar::Int64(x), Scalar::Int64(y)) => out.push(Scalar::Int64(x | y)),
10415 (Scalar::Bool(x), Scalar::Bool(y)) => out.push(Scalar::Bool(*x || *y)),
10416 _ => {
10417 return Err(ColumnError::Type(TypeError::NonNumericValue {
10418 value: format!("{a:?}"),
10419 dtype: self.dtype,
10420 }));
10421 }
10422 }
10423 }
10424 Self::new(self.dtype, out)
10425 }
10426
10427 pub fn bitwise_xor(&self, other: &Self) -> Result<Self, ColumnError> {
10429 if self.len() != other.len() {
10430 return Err(ColumnError::LengthMismatch {
10431 left: self.len(),
10432 right: other.len(),
10433 });
10434 }
10435 if let Some(out) = self.typed_bool_binary(other, |left, right| left ^ right) {
10436 return Ok(out);
10437 }
10438 let mut out = Vec::with_capacity(self.values.len());
10439 for (a, b) in self.values.iter().zip(&other.values) {
10440 if a.is_missing() || b.is_missing() {
10441 out.push(Scalar::Null(NullKind::Null));
10442 continue;
10443 }
10444 match (a, b) {
10445 (Scalar::Int64(x), Scalar::Int64(y)) => out.push(Scalar::Int64(x ^ y)),
10446 (Scalar::Bool(x), Scalar::Bool(y)) => out.push(Scalar::Bool(*x ^ *y)),
10447 _ => {
10448 return Err(ColumnError::Type(TypeError::NonNumericValue {
10449 value: format!("{a:?}"),
10450 dtype: self.dtype,
10451 }));
10452 }
10453 }
10454 }
10455 Self::new(self.dtype, out)
10456 }
10457
10458 pub fn left_shift(&self, other: &Self) -> Result<Self, ColumnError> {
10462 if self.len() != other.len() {
10463 return Err(ColumnError::LengthMismatch {
10464 left: self.len(),
10465 right: other.len(),
10466 });
10467 }
10468 let mut out = Vec::with_capacity(self.values.len());
10469 for (a, b) in self.values.iter().zip(&other.values) {
10470 if a.is_missing() || b.is_missing() {
10471 out.push(Scalar::Null(NullKind::Null));
10472 continue;
10473 }
10474 match (a, b) {
10475 (Scalar::Int64(x), Scalar::Int64(y)) => {
10476 let shift = (*y).clamp(0, 63) as u32;
10477 out.push(Scalar::Int64(x.wrapping_shl(shift)));
10478 }
10479 _ => {
10480 return Err(ColumnError::Type(TypeError::NonNumericValue {
10481 value: format!("{a:?}"),
10482 dtype: self.dtype,
10483 }));
10484 }
10485 }
10486 }
10487 Self::new(DType::Int64, out)
10488 }
10489
10490 pub fn right_shift(&self, other: &Self) -> Result<Self, ColumnError> {
10494 if self.len() != other.len() {
10495 return Err(ColumnError::LengthMismatch {
10496 left: self.len(),
10497 right: other.len(),
10498 });
10499 }
10500 let mut out = Vec::with_capacity(self.values.len());
10501 for (a, b) in self.values.iter().zip(&other.values) {
10502 if a.is_missing() || b.is_missing() {
10503 out.push(Scalar::Null(NullKind::Null));
10504 continue;
10505 }
10506 match (a, b) {
10507 (Scalar::Int64(x), Scalar::Int64(y)) => {
10508 let shift = (*y).clamp(0, 63) as u32;
10509 out.push(Scalar::Int64(x.wrapping_shr(shift)));
10510 }
10511 _ => {
10512 return Err(ColumnError::Type(TypeError::NonNumericValue {
10513 value: format!("{a:?}"),
10514 dtype: self.dtype,
10515 }));
10516 }
10517 }
10518 }
10519 Self::new(DType::Int64, out)
10520 }
10521
10522 pub fn bitwise_not(&self) -> Result<Self, ColumnError> {
10524 if let Some(out) = self.typed_bool_unary(|value| !value) {
10525 return Ok(out);
10526 }
10527 let mut out = Vec::with_capacity(self.values.len());
10528 for v in &self.values {
10529 if v.is_missing() {
10530 out.push(Scalar::Null(NullKind::Null));
10531 continue;
10532 }
10533 match v {
10534 Scalar::Int64(x) => out.push(Scalar::Int64(!x)),
10535 Scalar::Bool(x) => out.push(Scalar::Bool(!x)),
10536 _ => {
10537 return Err(ColumnError::Type(TypeError::NonNumericValue {
10538 value: format!("{v:?}"),
10539 dtype: self.dtype,
10540 }));
10541 }
10542 }
10543 }
10544 Self::new(self.dtype, out)
10545 }
10546
10547 pub fn invert(&self) -> Result<Self, ColumnError> {
10549 self.bitwise_not()
10550 }
10551
10552 pub fn maximum(&self, other: &Self) -> Result<Self, ColumnError> {
10554 if self.len() != other.len() {
10555 return Err(ColumnError::LengthMismatch {
10556 left: self.len(),
10557 right: other.len(),
10558 });
10559 }
10560 if let Some(out) = self.typed_float_binary(other, f64::max) {
10563 return Ok(out);
10564 }
10565 let mut out = Vec::with_capacity(self.values.len());
10566 for (a, b) in self.values.iter().zip(&other.values) {
10567 if a.is_missing() || b.is_missing() {
10568 out.push(Scalar::Float64(f64::NAN));
10569 continue;
10570 }
10571 let af = a.to_f64().map_err(ColumnError::Type)?;
10572 let bf = b.to_f64().map_err(ColumnError::Type)?;
10573 if af.is_nan() || bf.is_nan() {
10574 out.push(Scalar::Float64(f64::NAN));
10575 } else {
10576 out.push(Scalar::Float64(af.max(bf)));
10577 }
10578 }
10579 Self::new(DType::Float64, out)
10580 }
10581
10582 pub fn minimum(&self, other: &Self) -> Result<Self, ColumnError> {
10584 if self.len() != other.len() {
10585 return Err(ColumnError::LengthMismatch {
10586 left: self.len(),
10587 right: other.len(),
10588 });
10589 }
10590 if let Some(out) = self.typed_float_binary(other, f64::min) {
10591 return Ok(out);
10592 }
10593 let mut out = Vec::with_capacity(self.values.len());
10594 for (a, b) in self.values.iter().zip(&other.values) {
10595 if a.is_missing() || b.is_missing() {
10596 out.push(Scalar::Float64(f64::NAN));
10597 continue;
10598 }
10599 let af = a.to_f64().map_err(ColumnError::Type)?;
10600 let bf = b.to_f64().map_err(ColumnError::Type)?;
10601 if af.is_nan() || bf.is_nan() {
10602 out.push(Scalar::Float64(f64::NAN));
10603 } else {
10604 out.push(Scalar::Float64(af.min(bf)));
10605 }
10606 }
10607 Self::new(DType::Float64, out)
10608 }
10609
10610 pub fn fmax(&self, other: &Self) -> Result<Self, ColumnError> {
10612 if self.len() != other.len() {
10613 return Err(ColumnError::LengthMismatch {
10614 left: self.len(),
10615 right: other.len(),
10616 });
10617 }
10618 if let Some(out) = self.typed_float_binary(other, f64::max) {
10621 return Ok(out);
10622 }
10623 let mut out = Vec::with_capacity(self.values.len());
10624 for (a, b) in self.values.iter().zip(&other.values) {
10625 let af = a.to_f64().ok();
10626 let bf = b.to_f64().ok();
10627 let result = match (af, bf) {
10628 (Some(x), Some(y)) if x.is_nan() => y,
10629 (Some(x), Some(y)) if y.is_nan() => x,
10630 (Some(x), Some(y)) => x.max(y),
10631 (Some(x), None) => x,
10632 (None, Some(y)) => y,
10633 (None, None) => f64::NAN,
10634 };
10635 out.push(Scalar::Float64(result));
10636 }
10637 Self::new(DType::Float64, out)
10638 }
10639
10640 pub fn fmin(&self, other: &Self) -> Result<Self, ColumnError> {
10642 if self.len() != other.len() {
10643 return Err(ColumnError::LengthMismatch {
10644 left: self.len(),
10645 right: other.len(),
10646 });
10647 }
10648 if let Some(out) = self.typed_float_binary(other, f64::min) {
10649 return Ok(out);
10650 }
10651 let mut out = Vec::with_capacity(self.values.len());
10652 for (a, b) in self.values.iter().zip(&other.values) {
10653 let af = a.to_f64().ok();
10654 let bf = b.to_f64().ok();
10655 let result = match (af, bf) {
10656 (Some(x), Some(y)) if x.is_nan() => y,
10657 (Some(x), Some(y)) if y.is_nan() => x,
10658 (Some(x), Some(y)) => x.min(y),
10659 (Some(x), None) => x,
10660 (None, Some(y)) => y,
10661 (None, None) => f64::NAN,
10662 };
10663 out.push(Scalar::Float64(result));
10664 }
10665 Self::new(DType::Float64, out)
10666 }
10667
10668 fn typed_bool_binary<F>(&self, other: &Self, op: F) -> Option<Self>
10669 where
10670 F: Fn(bool, bool) -> bool,
10671 {
10672 let left = self.as_bool_slice()?;
10673 let right = other.as_bool_slice()?;
10674 (left.len() == right.len()).then(|| {
10675 Self::from_bool_values(
10676 left.iter()
10677 .zip(right)
10678 .map(|(&left_value, &right_value)| op(left_value, right_value))
10679 .collect(),
10680 )
10681 })
10682 }
10683
10684 fn typed_bool_unary<F>(&self, op: F) -> Option<Self>
10685 where
10686 F: Fn(bool) -> bool,
10687 {
10688 let data = self.as_bool_slice()?;
10689 Some(Self::from_bool_values(
10690 data.iter().map(|&value| op(value)).collect(),
10691 ))
10692 }
10693
10694 pub fn logical_and(&self, other: &Self) -> Result<Self, ColumnError> {
10696 if self.len() != other.len() {
10697 return Err(ColumnError::LengthMismatch {
10698 left: self.len(),
10699 right: other.len(),
10700 });
10701 }
10702 if let Some(out) = self.typed_bool_binary(other, |left, right| left && right) {
10703 return Ok(out);
10704 }
10705 let mut out = Vec::with_capacity(self.values.len());
10706 for (a, b) in self.values.iter().zip(&other.values) {
10707 if a.is_missing() || b.is_missing() {
10708 out.push(Scalar::Null(NullKind::Null));
10709 continue;
10710 }
10711 let av = match a {
10712 Scalar::Bool(x) => *x,
10713 _ => a.to_f64().map(|v| v != 0.0).unwrap_or(false),
10714 };
10715 let bv = match b {
10716 Scalar::Bool(x) => *x,
10717 _ => b.to_f64().map(|v| v != 0.0).unwrap_or(false),
10718 };
10719 out.push(Scalar::Bool(av && bv));
10720 }
10721 Self::new(DType::Bool, out)
10722 }
10723
10724 pub fn logical_or(&self, other: &Self) -> Result<Self, ColumnError> {
10726 if self.len() != other.len() {
10727 return Err(ColumnError::LengthMismatch {
10728 left: self.len(),
10729 right: other.len(),
10730 });
10731 }
10732 if let Some(out) = self.typed_bool_binary(other, |left, right| left || right) {
10733 return Ok(out);
10734 }
10735 let mut out = Vec::with_capacity(self.values.len());
10736 for (a, b) in self.values.iter().zip(&other.values) {
10737 if a.is_missing() || b.is_missing() {
10738 out.push(Scalar::Null(NullKind::Null));
10739 continue;
10740 }
10741 let av = match a {
10742 Scalar::Bool(x) => *x,
10743 _ => a.to_f64().map(|v| v != 0.0).unwrap_or(false),
10744 };
10745 let bv = match b {
10746 Scalar::Bool(x) => *x,
10747 _ => b.to_f64().map(|v| v != 0.0).unwrap_or(false),
10748 };
10749 out.push(Scalar::Bool(av || bv));
10750 }
10751 Self::new(DType::Bool, out)
10752 }
10753
10754 pub fn logical_xor(&self, other: &Self) -> Result<Self, ColumnError> {
10756 if self.len() != other.len() {
10757 return Err(ColumnError::LengthMismatch {
10758 left: self.len(),
10759 right: other.len(),
10760 });
10761 }
10762 if let Some(out) = self.typed_bool_binary(other, |left, right| left ^ right) {
10763 return Ok(out);
10764 }
10765 let mut out = Vec::with_capacity(self.values.len());
10766 for (a, b) in self.values.iter().zip(&other.values) {
10767 if a.is_missing() || b.is_missing() {
10768 out.push(Scalar::Null(NullKind::Null));
10769 continue;
10770 }
10771 let av = match a {
10772 Scalar::Bool(x) => *x,
10773 _ => a.to_f64().map(|v| v != 0.0).unwrap_or(false),
10774 };
10775 let bv = match b {
10776 Scalar::Bool(x) => *x,
10777 _ => b.to_f64().map(|v| v != 0.0).unwrap_or(false),
10778 };
10779 out.push(Scalar::Bool(av ^ bv));
10780 }
10781 Self::new(DType::Bool, out)
10782 }
10783
10784 pub fn logical_not(&self) -> Result<Self, ColumnError> {
10786 if let Some(out) = self.typed_bool_unary(|value| !value) {
10787 return Ok(out);
10788 }
10789 let mut out = Vec::with_capacity(self.values.len());
10790 for v in &self.values {
10791 if v.is_missing() {
10792 out.push(Scalar::Null(NullKind::Null));
10793 continue;
10794 }
10795 let bv = match v {
10796 Scalar::Bool(x) => *x,
10797 _ => v.to_f64().map(|x| x != 0.0).unwrap_or(false),
10798 };
10799 out.push(Scalar::Bool(!bv));
10800 }
10801 Self::new(DType::Bool, out)
10802 }
10803
10804 pub fn binary_comparison(&self, right: &Self, op: ComparisonOp) -> Result<Self, ColumnError> {
10809 if self.len() != right.len() {
10810 return Err(ColumnError::LengthMismatch {
10811 left: self.len(),
10812 right: right.len(),
10813 });
10814 }
10815
10816 if let (Some(l), Some(r)) = (self.as_f64_slice(), right.as_f64_slice()) {
10828 let zip = || l.iter().zip(r);
10829 let bools: Vec<bool> = match op {
10830 ComparisonOp::Gt => zip().map(|(&a, &b)| a > b).collect(),
10831 ComparisonOp::Lt => zip().map(|(&a, &b)| a < b).collect(),
10832 ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
10833 ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
10834 ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
10835 ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
10836 };
10837 return Ok(Self::from_bool_values(bools));
10838 }
10839 if let (Some(l), Some(r)) = (self.as_i64_slice(), right.as_i64_slice()) {
10840 let zip = || l.iter().zip(r);
10841 let bools: Vec<bool> = match op {
10842 ComparisonOp::Gt => zip().map(|(&a, &b)| a > b).collect(),
10843 ComparisonOp::Lt => zip().map(|(&a, &b)| a < b).collect(),
10844 ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
10845 ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
10846 ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
10847 ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
10848 };
10849 return Ok(Self::from_bool_values(bools));
10850 }
10851 if let (Some(l), Some(r)) = (self.as_bool_slice(), right.as_bool_slice()) {
10852 let zip = || l.iter().zip(r);
10853 let bools: Vec<bool> = match op {
10854 ComparisonOp::Gt => zip().map(|(&a, &b)| a && !b).collect(),
10855 ComparisonOp::Lt => zip().map(|(&a, &b)| !a && b).collect(),
10856 ComparisonOp::Eq => zip().map(|(&a, &b)| a == b).collect(),
10857 ComparisonOp::Ne => zip().map(|(&a, &b)| a != b).collect(),
10858 ComparisonOp::Ge => zip().map(|(&a, &b)| a >= b).collect(),
10859 ComparisonOp::Le => zip().map(|(&a, &b)| a <= b).collect(),
10860 };
10861 return Ok(Self::from_bool_values(bools));
10862 }
10863
10864 let values = self
10865 .values
10866 .iter()
10867 .zip(&right.values)
10868 .map(|(l, r)| -> Result<Scalar, ColumnError> {
10869 if l.is_missing() || r.is_missing() {
10870 return Ok(Scalar::Null(NullKind::Null));
10871 }
10872 let result = scalar_compare(l, r, op)?;
10873 Ok(Scalar::Bool(result))
10874 })
10875 .collect::<Result<Vec<_>, _>>()?;
10876
10877 Self::new(DType::Bool, values)
10878 }
10879
10880 pub fn eq(&self, right: &Self) -> Result<Self, ColumnError> {
10882 self.binary_comparison(right, ComparisonOp::Eq)
10883 }
10884
10885 pub fn ne(&self, right: &Self) -> Result<Self, ColumnError> {
10887 self.binary_comparison(right, ComparisonOp::Ne)
10888 }
10889
10890 pub fn lt(&self, right: &Self) -> Result<Self, ColumnError> {
10892 self.binary_comparison(right, ComparisonOp::Lt)
10893 }
10894
10895 pub fn le(&self, right: &Self) -> Result<Self, ColumnError> {
10897 self.binary_comparison(right, ComparisonOp::Le)
10898 }
10899
10900 pub fn gt(&self, right: &Self) -> Result<Self, ColumnError> {
10902 self.binary_comparison(right, ComparisonOp::Gt)
10903 }
10904
10905 pub fn ge(&self, right: &Self) -> Result<Self, ColumnError> {
10907 self.binary_comparison(right, ComparisonOp::Ge)
10908 }
10909
10910 pub fn compare_scalar(&self, scalar: &Scalar, op: ComparisonOp) -> Result<Self, ColumnError> {
10914 if scalar.is_missing() {
10915 let values = vec![Scalar::Null(NullKind::Null); self.len()];
10917 return Self::new(DType::Bool, values);
10918 }
10919
10920 if let Some(data) = self.as_f64_slice()
10931 && let Ok(s) = scalar.to_f64()
10932 {
10933 let bools: Vec<bool> = data
10934 .iter()
10935 .map(|&v| match op {
10936 ComparisonOp::Gt => v > s,
10937 ComparisonOp::Lt => v < s,
10938 ComparisonOp::Eq => v == s,
10939 ComparisonOp::Ne => v != s,
10940 ComparisonOp::Ge => v >= s,
10941 ComparisonOp::Le => v <= s,
10942 })
10943 .collect();
10944 return Ok(Self::from_bool_values(bools));
10945 }
10946 if let Some(data) = self.as_i64_slice()
10947 && let Scalar::Int64(s) = scalar
10948 {
10949 let s = *s;
10950 let bools: Vec<bool> = data
10951 .iter()
10952 .map(|&v| match op {
10953 ComparisonOp::Gt => v > s,
10954 ComparisonOp::Lt => v < s,
10955 ComparisonOp::Eq => v == s,
10956 ComparisonOp::Ne => v != s,
10957 ComparisonOp::Ge => v >= s,
10958 ComparisonOp::Le => v <= s,
10959 })
10960 .collect();
10961 return Ok(Self::from_bool_values(bools));
10962 }
10963
10964 let values = self
10965 .values
10966 .iter()
10967 .map(|v| -> Result<Scalar, ColumnError> {
10968 if v.is_missing() {
10969 return Ok(Scalar::Null(NullKind::Null));
10970 }
10971 let result = scalar_compare(v, scalar, op)?;
10972 Ok(Scalar::Bool(result))
10973 })
10974 .collect::<Result<Vec<_>, _>>()?;
10975
10976 Self::new(DType::Bool, values)
10977 }
10978
10979 pub fn filter_by_mask(&self, mask: &Self) -> Result<Self, ColumnError> {
10984 if mask.dtype == DType::Null {
10985 if self.len() != mask.len() {
10986 return Err(ColumnError::LengthMismatch {
10987 left: self.len(),
10988 right: mask.len(),
10989 });
10990 }
10991 return Self::new(self.dtype, Vec::new());
10992 }
10993 if mask.dtype != DType::Bool {
10994 return Err(ColumnError::InvalidMaskType { dtype: mask.dtype });
10995 }
10996 if self.len() != mask.len() {
10997 return Err(ColumnError::LengthMismatch {
10998 left: self.len(),
10999 right: mask.len(),
11000 });
11001 }
11002
11003 if let Some(mask_bits) = mask.as_bool_slice() {
11016 if let Some(data) = self.as_f64_slice() {
11017 let gathered: Vec<f64> = data
11018 .iter()
11019 .zip(mask_bits)
11020 .filter_map(|(&v, &m)| m.then_some(v))
11021 .collect();
11022 return Ok(Self::from_f64_values(gathered));
11023 }
11024 if let Some(data) = self.as_i64_slice() {
11025 let gathered: Vec<i64> = data
11026 .iter()
11027 .zip(mask_bits)
11028 .filter_map(|(&v, &m)| m.then_some(v))
11029 .collect();
11030 return Ok(Self::from_i64_values(gathered));
11031 }
11032 let values = self
11033 .values
11034 .iter()
11035 .zip(mask_bits)
11036 .filter_map(|(val, &m)| m.then_some(val.clone()))
11037 .collect::<Vec<_>>();
11038 return Self::new(self.dtype, values);
11039 }
11040
11041 if let Some(data) = self.as_f64_slice() {
11042 let gathered: Vec<f64> = data
11043 .iter()
11044 .zip(mask.values.iter())
11045 .filter_map(|(&v, m)| matches!(m, Scalar::Bool(true)).then_some(v))
11046 .collect();
11047 return Ok(Self::from_f64_values(gathered));
11048 }
11049 if let Some(data) = self.as_i64_slice() {
11050 let gathered: Vec<i64> = data
11051 .iter()
11052 .zip(mask.values.iter())
11053 .filter_map(|(&v, m)| matches!(m, Scalar::Bool(true)).then_some(v))
11054 .collect();
11055 return Ok(Self::from_i64_values(gathered));
11056 }
11057
11058 let values = self
11059 .values
11060 .iter()
11061 .zip(mask.values.iter())
11062 .filter_map(|(val, mask_val)| match mask_val {
11063 Scalar::Bool(true) => Some(val.clone()),
11064 _ => None,
11065 })
11066 .collect::<Vec<_>>();
11067
11068 Self::new(self.dtype, values)
11069 }
11070
11071 pub fn fillna(&self, fill_value: &Scalar) -> Result<Self, ColumnError> {
11076 if self.dtype == DType::Null {
11077 let replacement_dtype = if fill_value.is_missing() {
11078 DType::Null
11079 } else {
11080 fill_value.dtype()
11081 };
11082 let values = self
11083 .values
11084 .iter()
11085 .map(|value| {
11086 if value.is_missing() {
11087 fill_value.clone()
11088 } else {
11089 value.clone()
11090 }
11091 })
11092 .collect();
11093 return Self::new(replacement_dtype, values);
11094 }
11095
11096 let cast_fill = cast_scalar(fill_value, self.dtype)?;
11097
11098 if self.dtype == DType::Float64
11106 && let Scalar::Float64(fv) = &cast_fill
11107 && fv.is_finite()
11108 && let Some((data, validity)) = self.as_f64_slice_with_validity()
11109 {
11110 let mut out = Vec::with_capacity(data.len());
11111 for (i, &d) in data.iter().enumerate() {
11112 if validity.get(i) && !d.is_nan() {
11113 out.push(d);
11114 } else {
11115 out.push(*fv);
11116 }
11117 }
11118 return Ok(Self::from_f64_values(out));
11119 }
11120
11121 if self.dtype == DType::Int64
11130 && let Some(data) = self.as_i64_slice()
11131 {
11132 return Ok(Self::from_i64_values(data.to_vec()));
11133 }
11134
11135 let values = self
11136 .values
11137 .iter()
11138 .map(|v| {
11139 if v.is_missing() {
11140 cast_fill.clone()
11141 } else {
11142 v.clone()
11143 }
11144 })
11145 .collect();
11146
11147 Self::new(self.dtype, values)
11148 }
11149
11150 pub fn dropna(&self) -> Result<Self, ColumnError> {
11152 let values = self
11153 .values
11154 .iter()
11155 .filter(|v| !v.is_missing())
11156 .cloned()
11157 .collect();
11158
11159 Self::new(self.dtype, values)
11160 }
11161
11162 pub fn take(&self, indices: &[usize]) -> Result<Self, ColumnError> {
11169 let mut out = Vec::with_capacity(indices.len());
11170 for &i in indices {
11171 match self.values.get(i) {
11172 Some(v) => out.push(v.clone()),
11173 None => {
11174 return Err(ColumnError::LengthMismatch {
11175 left: self.values.len(),
11176 right: i,
11177 });
11178 }
11179 }
11180 }
11181 Self::new(self.dtype, out)
11182 }
11183
11184 pub fn put(&self, indices: &[usize], values: &[Scalar]) -> Result<Self, ColumnError> {
11188 if indices.len() != values.len() {
11189 return Err(ColumnError::LengthMismatch {
11190 left: indices.len(),
11191 right: values.len(),
11192 });
11193 }
11194 let mut out = self.values.to_vec();
11195 for (&i, v) in indices.iter().zip(values) {
11196 if i >= out.len() {
11197 return Err(ColumnError::LengthMismatch {
11198 left: out.len(),
11199 right: i,
11200 });
11201 }
11202 out[i] = v.clone();
11203 }
11204 Self::new(self.dtype, out)
11205 }
11206
11207 pub fn slice(&self, start: usize, len: usize) -> Result<Self, ColumnError> {
11213 if start >= self.values.len() {
11214 return Self::new(self.dtype, Vec::new());
11215 }
11216 let end = start.saturating_add(len).min(self.values.len());
11217 Ok(self.take_contiguous_range(start, end - start))
11218 }
11219
11220 pub fn head(&self, n: i64) -> Result<Self, ColumnError> {
11225 let take = normalize_head_take(n, self.len());
11226 self.slice(0, take)
11227 }
11228
11229 pub fn tail(&self, n: i64) -> Result<Self, ColumnError> {
11234 let (start, len) = normalize_tail_window(n, self.len());
11235 self.slice(start, len)
11236 }
11237
11238 pub fn array_split(&self, n: usize) -> Result<Vec<Self>, ColumnError> {
11242 if n == 0 {
11243 return Ok(Vec::new());
11244 }
11245 let len = self.values.len();
11246 let base_size = len / n;
11247 let remainder = len % n;
11248 let mut result = Vec::with_capacity(n);
11249 let mut start = 0;
11250 for i in 0..n {
11251 let size = base_size + if i < remainder { 1 } else { 0 };
11252 let part = self.slice(start, size)?;
11253 result.push(part);
11254 start += size;
11255 }
11256 Ok(result)
11257 }
11258
11259 pub fn split(&self, n: usize) -> Result<Vec<Self>, ColumnError> {
11261 self.array_split(n)
11262 }
11263
11264 pub fn concat(&self, other: &Self) -> Result<Self, ColumnError> {
11269 if self.dtype != other.dtype {
11270 return Err(ColumnError::DTypeMismatch {
11271 left: self.dtype,
11272 right: other.dtype,
11273 });
11274 }
11275 if let (Some((a, a_start)), Some((b, b_start))) = (
11282 self.as_i64_arc_view_source(),
11283 other.as_i64_arc_view_source(),
11284 ) {
11285 return Ok(Self::from_i64_all_valid_chunks(
11286 vec![(a, a_start, self.len()), (b, b_start, other.len())],
11287 self.len() + other.len(),
11288 ));
11289 }
11290 if let (Some(a), Some(b)) = (self.as_f64_slice(), other.as_f64_slice()) {
11291 let mut out = Vec::with_capacity(a.len() + b.len());
11292 out.extend_from_slice(a);
11293 out.extend_from_slice(b);
11294 return Ok(Self::from_f64_values(out));
11295 }
11296 let mut values = Vec::with_capacity(self.values.len() + other.values.len());
11297 values.extend_from_slice(&self.values);
11298 values.extend_from_slice(&other.values);
11299 Self::new(self.dtype, values)
11300 }
11301
11302 pub fn append(&self, other: &Self) -> Result<Self, ColumnError> {
11304 self.concat(other)
11305 }
11306
11307 pub fn insert(&self, index: usize, values: &[Scalar]) -> Result<Self, ColumnError> {
11311 let idx = index.min(self.values.len());
11312 let mut out = Vec::with_capacity(self.values.len() + values.len());
11313 out.extend_from_slice(&self.values[..idx]);
11314 out.extend_from_slice(values);
11315 out.extend_from_slice(&self.values[idx..]);
11316 Self::new(self.dtype, out)
11317 }
11318
11319 pub fn delete(&self, indices: &[usize]) -> Result<Self, ColumnError> {
11323 let mut to_delete: FxHashSet<usize> = FxHashSet::default();
11324 for &i in indices {
11325 to_delete.insert(i);
11326 }
11327 let out: Vec<Scalar> = self
11328 .values
11329 .iter()
11330 .enumerate()
11331 .filter(|(i, _)| !to_delete.contains(i))
11332 .map(|(_, v)| v.clone())
11333 .collect();
11334 Self::new(self.dtype, out)
11335 }
11336
11337 pub fn resize(&self, new_size: usize) -> Result<Self, ColumnError> {
11341 if new_size == 0 || self.values.is_empty() {
11342 return Self::new(self.dtype, Vec::new());
11343 }
11344 let mut out = Vec::with_capacity(new_size);
11345 let mut i = 0;
11346 while out.len() < new_size {
11347 out.push(self.values[i % self.values.len()].clone());
11348 i += 1;
11349 }
11350 Self::new(self.dtype, out)
11351 }
11352
11353 pub fn repeat(&self, repeats: usize) -> Result<Self, ColumnError> {
11358 if repeats == 0 {
11359 return Self::new(self.dtype, Vec::new());
11360 }
11361 if repeats == 1 {
11362 return Ok(self.clone());
11363 }
11364 let mut out = Vec::with_capacity(self.values.len() * repeats);
11365 for v in &self.values {
11366 for _ in 0..repeats {
11367 out.push(v.clone());
11368 }
11369 }
11370 Self::new(self.dtype, out)
11371 }
11372
11373 pub fn tile(&self, reps: usize) -> Result<Self, ColumnError> {
11378 if reps == 0 {
11379 return Self::new(self.dtype, Vec::new());
11380 }
11381 if reps == 1 {
11382 return Ok(self.clone());
11383 }
11384 let mut out = Vec::with_capacity(self.values.len() * reps);
11385 for _ in 0..reps {
11386 out.extend_from_slice(&self.values);
11387 }
11388 Self::new(self.dtype, out)
11389 }
11390
11391 pub fn reverse(&self) -> Result<Self, ColumnError> {
11395 let mut values = self.values.to_vec();
11396 values.reverse();
11397 Self::new(self.dtype, values)
11398 }
11399
11400 pub fn flip(&self) -> Result<Self, ColumnError> {
11402 self.reverse()
11403 }
11404
11405 pub fn roll(&self, shift: i64) -> Result<Self, ColumnError> {
11411 let len = self.len();
11412 if len == 0 {
11413 return Ok(self.clone());
11414 }
11415 let shift = ((shift % len as i64) + len as i64) as usize % len;
11416 if shift == 0 {
11417 return Ok(self.clone());
11418 }
11419 let mut out = Vec::with_capacity(len);
11420 let split = len - shift;
11421 out.extend_from_slice(&self.values[split..]);
11422 out.extend_from_slice(&self.values[..split]);
11423 Self::new(self.dtype, out)
11424 }
11425
11426 pub fn compress(&self, condition: &Self) -> Result<Self, ColumnError> {
11430 if self.len() != condition.len() {
11431 return Err(ColumnError::LengthMismatch {
11432 left: self.len(),
11433 right: condition.len(),
11434 });
11435 }
11436 let mut out = Vec::new();
11437 for (v, c) in self.values.iter().zip(&condition.values) {
11438 match c {
11439 Scalar::Bool(true) => out.push(v.clone()),
11440 Scalar::Bool(false) => {}
11441 _ => {
11442 return Err(ColumnError::Type(TypeError::NonNumericValue {
11443 value: format!("{c:?}"),
11444 dtype: condition.dtype,
11445 }));
11446 }
11447 }
11448 }
11449 Self::new(self.dtype, out)
11450 }
11451
11452 pub fn cumsum(&self) -> Result<Self, ColumnError> {
11458 if let Some(data) = self.as_f64_slice() {
11464 let mut running = 0.0_f64;
11465 let out: Vec<f64> = data
11466 .iter()
11467 .map(|&x| {
11468 running += x;
11469 running
11470 })
11471 .collect();
11472 return Ok(Self::from_f64_values(out));
11473 }
11474 let out = nancumsum(&self.values);
11475 Self::new(DType::Float64, out)
11476 }
11477
11478 pub fn cumprod(&self) -> Result<Self, ColumnError> {
11480 if let Some(data) = self.as_f64_slice() {
11482 let mut running = 1.0_f64;
11483 let out: Vec<f64> = data
11484 .iter()
11485 .map(|&x| {
11486 running *= x;
11487 running
11488 })
11489 .collect();
11490 return Ok(Self::from_f64_values(out));
11491 }
11492 let out = nancumprod(&self.values);
11493 Self::new(DType::Float64, out)
11494 }
11495
11496 pub fn cummax(&self) -> Result<Self, ColumnError> {
11498 if let Some(data) = self.as_f64_slice() {
11502 if let Some((&first, rest)) = data.split_first() {
11503 let mut running = first;
11504 let mut out = Vec::with_capacity(data.len());
11505 out.push(running);
11506 for &x in rest {
11507 running = running.max(x);
11508 out.push(running);
11509 }
11510 return Ok(Self::from_f64_values(out));
11511 }
11512 return Ok(Self::from_f64_values(Vec::new()));
11513 }
11514 let out = nancummax(&self.values);
11515 Self::new(DType::Float64, out)
11516 }
11517
11518 pub fn cummin(&self) -> Result<Self, ColumnError> {
11520 if let Some(data) = self.as_f64_slice() {
11522 if let Some((&first, rest)) = data.split_first() {
11523 let mut running = first;
11524 let mut out = Vec::with_capacity(data.len());
11525 out.push(running);
11526 for &x in rest {
11527 running = running.min(x);
11528 out.push(running);
11529 }
11530 return Ok(Self::from_f64_values(out));
11531 }
11532 return Ok(Self::from_f64_values(Vec::new()));
11533 }
11534 let out = nancummin(&self.values);
11535 Self::new(DType::Float64, out)
11536 }
11537
11538 #[must_use]
11543 pub fn sum(&self) -> Scalar {
11544 if let Some(data) = self.as_f64_slice() {
11550 let mut s = 0.0_f64;
11551 for &x in data {
11552 s += x;
11553 }
11554 return Scalar::Float64(s);
11555 }
11556 nansum(&self.values)
11557 }
11558
11559 #[must_use]
11564 pub fn mean(&self) -> Scalar {
11565 if let Some(data) = self.as_f64_slice() {
11568 if data.is_empty() {
11569 return Scalar::Null(NullKind::NaN);
11570 }
11571 let mut s = 0.0_f64;
11572 for &x in data {
11573 s += x;
11574 }
11575 return Scalar::Float64(s / data.len() as f64);
11576 }
11577 nanmean(&self.values)
11578 }
11579
11580 #[must_use]
11584 pub fn weighted_mean(&self, weights: &Self) -> Scalar {
11585 if self.len() != weights.len() {
11586 return Scalar::Null(NullKind::NaN);
11587 }
11588 let mut sum = 0.0;
11589 let mut weight_sum = 0.0;
11590 for (v, w) in self.values.iter().zip(weights.values()) {
11591 if v.is_missing() || w.is_missing() {
11592 continue;
11593 }
11594 let vf = match v.to_f64() {
11595 Ok(x) => x,
11596 Err(_) => continue,
11597 };
11598 let wf = match w.to_f64() {
11599 Ok(x) => x,
11600 Err(_) => continue,
11601 };
11602 sum += vf * wf;
11603 weight_sum += wf;
11604 }
11605 if weight_sum == 0.0 {
11606 return Scalar::Null(NullKind::NaN);
11607 }
11608 Scalar::Float64(sum / weight_sum)
11609 }
11610
11611 #[must_use]
11613 pub fn average(&self, weights: &Self) -> Scalar {
11614 self.weighted_mean(weights)
11615 }
11616
11617 #[must_use]
11622 pub fn min(&self) -> Scalar {
11623 if let Some(data) = self.as_f64_slice()
11629 && let Some((&first, rest)) = data.split_first()
11630 {
11631 let mut m = first;
11632 for &x in rest {
11633 if x < m {
11634 m = x;
11635 }
11636 }
11637 return Scalar::Float64(m);
11638 }
11639 if let Some(data) = self.as_i64_slice()
11640 && let Some((&first, rest)) = data.split_first()
11641 {
11642 let mut m = first;
11643 for &x in rest {
11644 if x < m {
11645 m = x;
11646 }
11647 }
11648 return Scalar::Int64(m);
11649 }
11650 nanmin(&self.values)
11651 }
11652
11653 #[must_use]
11657 pub fn max(&self) -> Scalar {
11658 if let Some(data) = self.as_f64_slice()
11661 && let Some((&first, rest)) = data.split_first()
11662 {
11663 let mut m = first;
11664 for &x in rest {
11665 if x > m {
11666 m = x;
11667 }
11668 }
11669 return Scalar::Float64(m);
11670 }
11671 if let Some(data) = self.as_i64_slice()
11672 && let Some((&first, rest)) = data.split_first()
11673 {
11674 let mut m = first;
11675 for &x in rest {
11676 if x > m {
11677 m = x;
11678 }
11679 }
11680 return Scalar::Int64(m);
11681 }
11682 nanmax(&self.values)
11683 }
11684
11685 #[must_use]
11689 pub fn median(&self) -> Scalar {
11690 nanmedian(&self.values)
11691 }
11692
11693 #[must_use]
11698 pub fn prod(&self) -> Scalar {
11699 if let Some(data) = self.as_f64_slice() {
11706 let mut p = 1.0_f64;
11707 for &x in data {
11708 p *= x;
11709 }
11710 return Scalar::Float64(p);
11711 }
11712 nanprod(&self.values)
11713 }
11714
11715 #[must_use]
11717 pub fn product(&self) -> Scalar {
11718 self.prod()
11719 }
11720
11721 #[must_use]
11723 pub fn nansum(&self) -> Scalar {
11724 self.sum()
11725 }
11726
11727 #[must_use]
11729 pub fn nanmean(&self) -> Scalar {
11730 self.mean()
11731 }
11732
11733 #[must_use]
11735 pub fn nanmin(&self) -> Scalar {
11736 self.min()
11737 }
11738
11739 #[must_use]
11741 pub fn nanmax(&self) -> Scalar {
11742 self.max()
11743 }
11744
11745 #[must_use]
11747 pub fn nanprod(&self) -> Scalar {
11748 self.prod()
11749 }
11750
11751 #[must_use]
11753 pub fn nanstd(&self, ddof: usize) -> Scalar {
11754 self.std(ddof)
11755 }
11756
11757 #[must_use]
11759 pub fn nanvar(&self, ddof: usize) -> Scalar {
11760 self.var(ddof)
11761 }
11762
11763 #[must_use]
11765 pub fn nanmedian(&self) -> Scalar {
11766 self.median()
11767 }
11768
11769 fn skipna_false_missing_result(&self, skipna: bool) -> Option<Scalar> {
11770 if skipna || !self.values.iter().any(Scalar::is_missing) {
11771 return None;
11772 }
11773
11774 Some(if matches!(self.dtype, DType::Timedelta64) {
11775 Scalar::Timedelta64(Timedelta::NAT)
11776 } else {
11777 Scalar::Float64(f64::NAN)
11778 })
11779 }
11780
11781 #[must_use]
11785 pub fn sum_skipna(&self, skipna: bool) -> Scalar {
11786 self.skipna_false_missing_result(skipna)
11787 .unwrap_or_else(|| self.sum())
11788 }
11789
11790 #[must_use]
11792 pub fn mean_skipna(&self, skipna: bool) -> Scalar {
11793 self.skipna_false_missing_result(skipna)
11794 .unwrap_or_else(|| self.mean())
11795 }
11796
11797 #[must_use]
11799 pub fn min_skipna(&self, skipna: bool) -> Scalar {
11800 self.skipna_false_missing_result(skipna)
11801 .unwrap_or_else(|| self.min())
11802 }
11803
11804 #[must_use]
11806 pub fn max_skipna(&self, skipna: bool) -> Scalar {
11807 self.skipna_false_missing_result(skipna)
11808 .unwrap_or_else(|| self.max())
11809 }
11810
11811 #[must_use]
11813 pub fn median_skipna(&self, skipna: bool) -> Scalar {
11814 self.skipna_false_missing_result(skipna)
11815 .unwrap_or_else(|| self.median())
11816 }
11817
11818 #[must_use]
11820 pub fn prod_skipna(&self, skipna: bool) -> Scalar {
11821 self.skipna_false_missing_result(skipna)
11822 .unwrap_or_else(|| self.prod())
11823 }
11824
11825 #[must_use]
11827 pub fn var_skipna(&self, ddof: usize, skipna: bool) -> Scalar {
11828 self.skipna_false_missing_result(skipna)
11829 .unwrap_or_else(|| self.var(ddof))
11830 }
11831
11832 #[must_use]
11834 pub fn std_skipna(&self, ddof: usize, skipna: bool) -> Scalar {
11835 self.skipna_false_missing_result(skipna)
11836 .unwrap_or_else(|| self.std(ddof))
11837 }
11838
11839 #[must_use]
11841 pub fn sem_skipna(&self, ddof: usize, skipna: bool) -> Scalar {
11842 self.skipna_false_missing_result(skipna)
11843 .unwrap_or_else(|| self.sem(ddof))
11844 }
11845
11846 #[must_use]
11850 pub fn count(&self) -> usize {
11851 if self.dtype == DType::Float64 {
11852 if let Some((data, validity)) = self.as_f64_slice_with_validity() {
11853 if validity.all() {
11854 return data.iter().filter(|value| !value.is_nan()).count();
11855 }
11856 return data
11857 .iter()
11858 .enumerate()
11859 .filter(|(idx, value)| validity.get(*idx) && !value.is_nan())
11860 .count();
11861 }
11862 if let Some(data) = self.as_f64_slice() {
11863 return data.iter().filter(|value| !value.is_nan()).count();
11864 }
11865 }
11866
11867 if matches!(
11868 self.dtype,
11869 DType::Bool
11870 | DType::BoolNullable
11871 | DType::Int64
11872 | DType::Int64Nullable
11873 | DType::Utf8
11874 | DType::Interval
11875 ) {
11876 return self.validity.count_valid();
11877 }
11878
11879 self.values.iter().filter(|v| !v.is_missing()).count()
11880 }
11881
11882 pub fn ffill(&self, limit: Option<usize>) -> Result<Self, ColumnError> {
11889 let mut out = Vec::with_capacity(self.values.len());
11890 let mut last: Option<Scalar> = None;
11891 let mut run = 0usize;
11892 for v in &self.values {
11893 if !v.is_missing() {
11894 out.push(v.clone());
11895 last = Some(v.clone());
11896 run = 0;
11897 continue;
11898 }
11899 match (&last, limit) {
11900 (Some(prev), None) => out.push(prev.clone()),
11901 (Some(prev), Some(cap)) if run < cap => {
11902 out.push(prev.clone());
11903 run += 1;
11904 }
11905 _ => out.push(v.clone()),
11906 }
11907 }
11908 Self::new(self.dtype, out)
11909 }
11910
11911 pub fn pad(&self, limit: Option<usize>) -> Result<Self, ColumnError> {
11913 self.ffill(limit)
11914 }
11915
11916 pub fn bfill(&self, limit: Option<usize>) -> Result<Self, ColumnError> {
11922 let mut out = vec![Scalar::Null(NullKind::NaN); self.values.len()];
11923 let mut next: Option<Scalar> = None;
11924 let mut run = 0usize;
11925 for (i, v) in self.values.iter().enumerate().rev() {
11926 if !v.is_missing() {
11927 out[i] = v.clone();
11928 next = Some(v.clone());
11929 run = 0;
11930 continue;
11931 }
11932 match (&next, limit) {
11933 (Some(nxt), None) => out[i] = nxt.clone(),
11934 (Some(nxt), Some(cap)) if run < cap => {
11935 out[i] = nxt.clone();
11936 run += 1;
11937 }
11938 _ => out[i] = v.clone(),
11939 }
11940 }
11941 Self::new(self.dtype, out)
11942 }
11943
11944 pub fn backfill(&self, limit: Option<usize>) -> Result<Self, ColumnError> {
11946 self.bfill(limit)
11947 }
11948
11949 #[must_use]
11953 pub fn nunique(&self) -> Scalar {
11954 self.nunique_with_dropna(true)
11955 }
11956
11957 #[must_use]
11962 pub fn nunique_with_dropna(&self, dropna: bool) -> Scalar {
11963 if let Some(data) = self.as_i64_slice()
11969 && let Some((min, range)) = i64_direct_address_range(data)
11970 {
11971 let mut seen = vec![false; range];
11972 let mut distinct = 0i64;
11973 for &v in data {
11974 let slot = (v as i128 - min as i128) as usize;
11975 if !seen[slot] {
11976 seen[slot] = true;
11977 distinct += 1;
11978 }
11979 }
11980 return Scalar::Int64(distinct);
11981 }
11982
11983 let mut distinct = match nannunique(&self.values) {
11984 Scalar::Int64(count) => count,
11985 _ => 0,
11986 };
11987
11988 if !dropna && self.values.iter().any(Scalar::is_missing) {
11989 distinct += 1;
11990 }
11991
11992 Scalar::Int64(distinct)
11993 }
11994
11995 #[must_use]
12000 pub fn any(&self) -> Scalar {
12001 nanany(&self.values)
12002 }
12003
12004 #[must_use]
12009 pub fn all(&self) -> Scalar {
12010 nanall(&self.values)
12011 }
12012
12013 pub fn diff_valid(&self) -> Result<Self, ColumnError> {
12022 let mut prev: Option<f64> = None;
12023 let mut out = Vec::with_capacity(self.values.len());
12024 for v in &self.values {
12025 if v.is_missing() {
12026 out.push(Scalar::Null(NullKind::NaN));
12027 continue;
12028 }
12029 match v.to_f64() {
12030 Ok(x) if !x.is_nan() => match prev {
12031 Some(p) => {
12032 out.push(Scalar::Float64(x - p));
12033 prev = Some(x);
12034 }
12035 None => {
12036 out.push(Scalar::Null(NullKind::NaN));
12037 prev = Some(x);
12038 }
12039 },
12040 Ok(_) => out.push(Scalar::Null(NullKind::NaN)),
12041 Err(err) => return Err(ColumnError::Type(err)),
12042 }
12043 }
12044 Self::new(DType::Float64, out)
12045 }
12046
12047 pub fn sample(&self, n: usize, seed: u64) -> Result<Self, ColumnError> {
12056 let len = self.values.len();
12057 if n >= len {
12058 return Ok(self.clone());
12059 }
12060 let mut indices: Vec<usize> = (0..len).collect();
12061 let mut state = seed.wrapping_add(0x9E3779B97F4A7C15);
12062 for i in 0..n {
12063 state = state
12065 .wrapping_mul(6364136223846793005)
12066 .wrapping_add(1442695040888963407);
12067 let bound = (len - i) as u64;
12068 let pick = i + (state.wrapping_shr(33) % bound) as usize;
12069 indices.swap(i, pick);
12070 }
12071 let values: Vec<Scalar> = indices[..n]
12072 .iter()
12073 .map(|&idx| self.values[idx].clone())
12074 .collect();
12075 Self::new(self.dtype, values)
12076 }
12077
12078 #[must_use]
12085 pub fn first_valid(&self) -> Option<usize> {
12086 self.values.iter().position(|v| !v.is_missing())
12087 }
12088
12089 #[must_use]
12092 pub fn first_valid_index(&self) -> Option<usize> {
12093 self.first_valid()
12094 }
12095
12096 #[must_use]
12101 pub fn last_valid(&self) -> Option<usize> {
12102 self.values.iter().rposition(|v| !v.is_missing())
12103 }
12104
12105 #[must_use]
12108 pub fn last_valid_index(&self) -> Option<usize> {
12109 self.last_valid()
12110 }
12111
12112 pub fn rolling_window_sum(
12121 &self,
12122 window: usize,
12123 min_periods: usize,
12124 ) -> Result<Self, ColumnError> {
12125 let len = self.values.len();
12126 if window == 0 {
12127 return Self::new(DType::Float64, vec![Scalar::Null(NullKind::NaN); len]);
12128 }
12129 let mut out = Vec::with_capacity(len);
12130 for i in 0..len {
12131 let start = (i + 1).saturating_sub(window);
12132 let end = i + 1;
12133 let mut sum = 0.0_f64;
12134 let mut observed = 0usize;
12135 for v in &self.values[start..end] {
12136 if v.is_missing() {
12137 continue;
12138 }
12139 match v.to_f64() {
12140 Ok(x) if !x.is_nan() => {
12141 sum += x;
12142 observed += 1;
12143 }
12144 Ok(_) => {}
12145 Err(err) => return Err(ColumnError::Type(err)),
12146 }
12147 }
12148 if observed >= min_periods.max(1) || (min_periods == 0 && end - start > 0) {
12149 out.push(Scalar::Float64(sum));
12150 } else {
12151 out.push(Scalar::Null(NullKind::NaN));
12152 }
12153 }
12154 Self::new(DType::Float64, out)
12155 }
12156
12157 pub fn isnull(&self) -> Result<Self, ColumnError> {
12161 if self.dtype == DType::Float64 {
12162 if let Some((data, validity)) = self.as_f64_slice_with_validity() {
12163 let out: Vec<bool> = data
12164 .iter()
12165 .enumerate()
12166 .map(|(idx, value)| !validity.get(idx) || value.is_nan())
12167 .collect();
12168 return Ok(Self::from_bool_values(out));
12169 }
12170 if let Some(data) = self.as_f64_slice() {
12171 let out: Vec<bool> = data.iter().map(|value| value.is_nan()).collect();
12172 return Ok(Self::from_bool_values(out));
12173 }
12174 }
12175
12176 if self.missingness_is_validity_only() {
12177 let out = Self::bool_values_from_validity(&self.validity, false, true);
12178 return Ok(Self::from_bool_values(out));
12179 }
12180
12181 let out: Vec<Scalar> = self
12182 .values
12183 .iter()
12184 .map(|v| Scalar::Bool(v.is_missing()))
12185 .collect();
12186 Self::new(DType::Bool, out)
12187 }
12188
12189 pub fn isna(&self) -> Result<Self, ColumnError> {
12191 self.isnull()
12192 }
12193
12194 pub fn notnull(&self) -> Result<Self, ColumnError> {
12198 if self.dtype == DType::Float64 {
12199 if let Some((data, validity)) = self.as_f64_slice_with_validity() {
12200 let out: Vec<bool> = data
12201 .iter()
12202 .enumerate()
12203 .map(|(idx, value)| validity.get(idx) && !value.is_nan())
12204 .collect();
12205 return Ok(Self::from_bool_values(out));
12206 }
12207 if let Some(data) = self.as_f64_slice() {
12208 let out: Vec<bool> = data.iter().map(|value| !value.is_nan()).collect();
12209 return Ok(Self::from_bool_values(out));
12210 }
12211 }
12212
12213 if self.missingness_is_validity_only() {
12214 let out = Self::bool_values_from_validity(&self.validity, true, false);
12215 return Ok(Self::from_bool_values(out));
12216 }
12217
12218 let out: Vec<Scalar> = self
12219 .values
12220 .iter()
12221 .map(|v| Scalar::Bool(!v.is_missing()))
12222 .collect();
12223 Self::new(DType::Bool, out)
12224 }
12225
12226 pub fn notna(&self) -> Result<Self, ColumnError> {
12228 self.notnull()
12229 }
12230
12231 fn missingness_is_validity_only(&self) -> bool {
12232 matches!(
12233 self.dtype,
12234 DType::Bool
12235 | DType::BoolNullable
12236 | DType::Int64
12237 | DType::Int64Nullable
12238 | DType::Utf8
12239 | DType::Interval
12240 )
12241 }
12242
12243 fn bool_values_from_validity(
12244 validity: &ValidityMask,
12245 valid_value: bool,
12246 invalid_value: bool,
12247 ) -> Vec<bool> {
12248 let len = validity.len();
12249 if validity.all() {
12250 return vec![valid_value; len];
12251 }
12252
12253 if let Some(ranges) = &validity.invalid_ranges {
12254 let mut out = vec![valid_value; len];
12255 for &(start, run_len) in ranges.iter() {
12256 if let Some(end) = start.checked_add(run_len)
12257 && let Some(span) = out.get_mut(start..end)
12258 {
12259 span.fill(invalid_value);
12260 }
12261 }
12262 return out;
12263 }
12264
12265 validity
12266 .bits()
12267 .map(|valid| if valid { valid_value } else { invalid_value })
12268 .collect()
12269 }
12270
12271 pub fn isfinite(&self) -> Result<Self, ColumnError> {
12273 if let Some(out) = self.bool_values_from_f64(false, f64::is_finite) {
12274 return Ok(Self::from_bool_values(out));
12275 }
12276
12277 let out: Vec<Scalar> = self
12278 .values
12279 .iter()
12280 .map(|v| match v {
12281 Scalar::Float64(f) => Scalar::Bool(f.is_finite()),
12282 Scalar::Int64(_) => Scalar::Bool(true),
12283 _ if v.is_missing() => Scalar::Bool(false),
12284 _ => Scalar::Bool(true),
12285 })
12286 .collect();
12287 Self::new(DType::Bool, out)
12288 }
12289
12290 pub fn isinf(&self) -> Result<Self, ColumnError> {
12292 if let Some(out) = self.bool_values_from_f64(false, f64::is_infinite) {
12293 return Ok(Self::from_bool_values(out));
12294 }
12295
12296 let out: Vec<Scalar> = self
12297 .values
12298 .iter()
12299 .map(|v| match v {
12300 Scalar::Float64(f) => Scalar::Bool(f.is_infinite()),
12301 _ => Scalar::Bool(false),
12302 })
12303 .collect();
12304 Self::new(DType::Bool, out)
12305 }
12306
12307 pub fn isnan(&self) -> Result<Self, ColumnError> {
12309 if self.dtype == DType::Float64 && matches!(&self.values, ScalarValues::Eager(_)) {
12310 let out: Vec<Scalar> = self
12311 .values
12312 .iter()
12313 .map(|v| match v {
12314 Scalar::Float64(f) => Scalar::Bool(f.is_nan()),
12315 Scalar::Null(NullKind::NaN) => Scalar::Bool(true),
12316 _ => Scalar::Bool(false),
12317 })
12318 .collect();
12319 return Self::new(DType::Bool, out);
12320 }
12321 if let Some(out) = self.bool_values_from_f64(true, f64::is_nan) {
12322 return Ok(Self::from_bool_values(out));
12323 }
12324
12325 let out: Vec<Scalar> = self
12326 .values
12327 .iter()
12328 .map(|v| match v {
12329 Scalar::Float64(f) => Scalar::Bool(f.is_nan()),
12330 Scalar::Null(NullKind::NaN) => Scalar::Bool(true),
12331 _ => Scalar::Bool(false),
12332 })
12333 .collect();
12334 Self::new(DType::Bool, out)
12335 }
12336
12337 fn bool_values_from_f64<F>(&self, invalid_value: bool, predicate: F) -> Option<Vec<bool>>
12338 where
12339 F: Fn(f64) -> bool,
12340 {
12341 if self.dtype != DType::Float64 {
12342 return None;
12343 }
12344
12345 if let Some((data, validity)) = self.as_f64_slice_with_validity() {
12346 return Some(
12347 data.iter()
12348 .enumerate()
12349 .map(|(idx, value)| {
12350 if validity.get(idx) {
12351 predicate(*value)
12352 } else {
12353 invalid_value
12354 }
12355 })
12356 .collect(),
12357 );
12358 }
12359
12360 self.as_f64_slice()
12361 .map(|data| data.iter().map(|&value| predicate(value)).collect())
12362 }
12363
12364 #[must_use]
12368 pub fn var(&self, ddof: usize) -> Scalar {
12369 if let Some(data) = self.as_f64_slice() {
12376 let n = data.len();
12377 if n <= ddof {
12378 return Scalar::Null(NullKind::NaN);
12379 }
12380 let mean: f64 = data.iter().sum::<f64>() / n as f64;
12381 let sum_sq: f64 = data.iter().map(|&x| (x - mean).powi(2)).sum::<f64>();
12382 return Scalar::Float64(sum_sq / (n - ddof) as f64);
12383 }
12384 nanvar(&self.values, ddof)
12385 }
12386
12387 #[must_use]
12391 pub fn std(&self, ddof: usize) -> Scalar {
12392 if self.as_f64_slice().is_some() {
12396 return match self.var(ddof) {
12397 Scalar::Float64(v) => Scalar::Float64(v.sqrt()),
12398 other => other,
12399 };
12400 }
12401 nanstd(&self.values, ddof)
12402 }
12403
12404 #[must_use]
12408 pub fn sem(&self, ddof: usize) -> Scalar {
12409 nansem(&self.values, ddof)
12410 }
12411
12412 #[must_use]
12417 pub fn cov(&self, other: &Self) -> Scalar {
12418 self.cov_ddof(other, 1)
12419 }
12420
12421 #[must_use]
12423 pub fn cov_ddof(&self, other: &Self, ddof: usize) -> Scalar {
12424 let n = self.values.len().min(other.values.len());
12425 if n == 0 {
12426 return Scalar::Null(NullKind::NaN);
12427 }
12428 let mut sum_x = 0.0;
12429 let mut sum_y = 0.0;
12430 let mut count = 0usize;
12431 for i in 0..n {
12432 let x = match self.values[i].to_f64() {
12433 Ok(v) if v.is_finite() => v,
12434 _ => continue,
12435 };
12436 let y = match other.values[i].to_f64() {
12437 Ok(v) if v.is_finite() => v,
12438 _ => continue,
12439 };
12440 sum_x += x;
12441 sum_y += y;
12442 count += 1;
12443 }
12444 if count <= ddof {
12445 return Scalar::Null(NullKind::NaN);
12446 }
12447 let mean_x = sum_x / count as f64;
12448 let mean_y = sum_y / count as f64;
12449 let mut cov_sum = 0.0;
12450 for i in 0..n {
12451 let x = match self.values[i].to_f64() {
12452 Ok(v) if v.is_finite() => v,
12453 _ => continue,
12454 };
12455 let y = match other.values[i].to_f64() {
12456 Ok(v) if v.is_finite() => v,
12457 _ => continue,
12458 };
12459 cov_sum += (x - mean_x) * (y - mean_y);
12460 }
12461 Scalar::Float64(cov_sum / (count - ddof) as f64)
12462 }
12463
12464 #[must_use]
12468 pub fn corr(&self, other: &Self) -> Scalar {
12469 let n = self.values.len().min(other.values.len());
12470 if n == 0 {
12471 return Scalar::Null(NullKind::NaN);
12472 }
12473 let mut sum_x = 0.0;
12474 let mut sum_y = 0.0;
12475 let mut sum_xx = 0.0;
12476 let mut sum_yy = 0.0;
12477 let mut sum_xy = 0.0;
12478 let mut count = 0usize;
12479 for i in 0..n {
12480 let x = match self.values[i].to_f64() {
12481 Ok(v) if v.is_finite() => v,
12482 _ => continue,
12483 };
12484 let y = match other.values[i].to_f64() {
12485 Ok(v) if v.is_finite() => v,
12486 _ => continue,
12487 };
12488 sum_x += x;
12489 sum_y += y;
12490 sum_xx += x * x;
12491 sum_yy += y * y;
12492 sum_xy += x * y;
12493 count += 1;
12494 }
12495 if count < 2 {
12496 return Scalar::Null(NullKind::NaN);
12497 }
12498 let n_f = count as f64;
12499 let numerator = n_f * sum_xy - sum_x * sum_y;
12500 let denom_x = (n_f * sum_xx - sum_x * sum_x).sqrt();
12501 let denom_y = (n_f * sum_yy - sum_y * sum_y).sqrt();
12502 if denom_x == 0.0 || denom_y == 0.0 {
12503 return Scalar::Null(NullKind::NaN);
12504 }
12505 Scalar::Float64(numerator / (denom_x * denom_y))
12506 }
12507
12508 #[must_use]
12512 pub fn autocorr(&self, lag: usize) -> Scalar {
12513 if lag >= self.values.len() {
12514 return Scalar::Null(NullKind::NaN);
12515 }
12516 let shifted = match self.shift(lag as i64, Scalar::Null(NullKind::NaN)) {
12517 Ok(s) => s,
12518 Err(_) => return Scalar::Null(NullKind::NaN),
12519 };
12520 self.corr(&shifted)
12521 }
12522
12523 #[must_use]
12528 pub fn skew(&self) -> Scalar {
12529 nanskew(&self.values)
12530 }
12531
12532 #[must_use]
12537 pub fn kurt(&self) -> Scalar {
12538 nankurt(&self.values)
12539 }
12540
12541 #[must_use]
12543 pub fn kurtosis(&self) -> Scalar {
12544 self.kurt()
12545 }
12546
12547 #[must_use]
12552 pub fn ptp(&self) -> Scalar {
12553 nanptp(&self.values)
12554 }
12555
12556 #[must_use]
12560 pub fn is_unique(&self) -> bool {
12561 !self.has_duplicates()
12562 }
12563
12564 #[must_use]
12568 pub fn has_duplicates(&self) -> bool {
12569 #[derive(Hash, PartialEq, Eq)]
12570 enum Key<'a> {
12571 Bool(bool),
12572 Int64(i64),
12573 FloatBits(u64),
12574 Utf8(&'a str),
12575 Timedelta64(i64),
12576 Datetime64(i64),
12577 Period(i64),
12578 Interval(u64, u64, IntervalClosed),
12579 }
12580 let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
12581 for v in &self.values {
12582 if v.is_missing() {
12583 continue;
12584 }
12585 let key = match v {
12586 Scalar::Bool(b) => Key::Bool(*b),
12587 Scalar::Int64(i) => Key::Int64(*i),
12588 Scalar::Float64(f) => {
12589 let norm = if *f == 0.0 { 0.0 } else { *f };
12590 Key::FloatBits(norm.to_bits())
12591 }
12592 Scalar::Utf8(s) => Key::Utf8(s.as_str()),
12593 Scalar::Timedelta64(v) => Key::Timedelta64(*v),
12594 Scalar::Datetime64(v) => Key::Datetime64(*v),
12595 Scalar::Period(p) => Key::Period(p.ordinal),
12596 Scalar::Interval(v) => {
12597 let (left, right, closed) = interval_key(v);
12598 Key::Interval(left, right, closed)
12599 }
12600 Scalar::Null(_) => continue,
12601 };
12602 if !seen.insert(key) {
12603 return true;
12604 }
12605 }
12606 false
12607 }
12608
12609 pub fn pct_change(&self, periods: i64) -> Result<Self, ColumnError> {
12616 let len = self.values.len();
12617 if len == 0 || periods == 0 {
12618 return Self::new(DType::Float64, vec![Scalar::Null(NullKind::NaN); len]);
12619 }
12620 let abs = periods.unsigned_abs() as usize;
12621 let mut out: Vec<Scalar> = Vec::with_capacity(len);
12622 for i in 0..len {
12623 let prev_idx = if periods > 0 {
12624 i.checked_sub(abs)
12625 } else if i + abs < len {
12626 Some(i + abs)
12627 } else {
12628 None
12629 };
12630 let Some(pi) = prev_idx else {
12631 out.push(Scalar::Null(NullKind::NaN));
12632 continue;
12633 };
12634 let cur = &self.values[i];
12635 let prev = &self.values[pi];
12636 if cur.is_missing() || prev.is_missing() {
12637 out.push(Scalar::Null(NullKind::NaN));
12638 continue;
12639 }
12640 if let (Scalar::Timedelta64(cur_ns), Scalar::Timedelta64(prev_ns)) = (cur, prev) {
12644 if *cur_ns == Timedelta::NAT || *prev_ns == Timedelta::NAT {
12645 out.push(Scalar::Null(NullKind::NaN));
12646 continue;
12647 }
12648 let prev_f = *prev_ns as f64;
12649 if prev_f.abs() < f64::EPSILON {
12650 out.push(Scalar::Null(NullKind::NaN));
12651 } else {
12652 out.push(Scalar::Float64((*cur_ns as f64 - prev_f) / prev_f));
12653 }
12654 continue;
12655 }
12656 match (cur.to_f64(), prev.to_f64()) {
12657 (Ok(c), Ok(p)) => {
12658 if p == 0.0 || p.is_nan() || c.is_nan() {
12659 out.push(Scalar::Null(NullKind::NaN));
12660 } else {
12661 out.push(Scalar::Float64((c - p) / p));
12662 }
12663 }
12664 _ => out.push(Scalar::Null(NullKind::NaN)),
12665 }
12666 }
12667 Self::new(DType::Float64, out)
12668 }
12669
12670 pub fn pct_change_with_fill(
12678 &self,
12679 periods: i64,
12680 fill_method: Option<&str>,
12681 limit: Option<usize>,
12682 ) -> Result<Self, ColumnError> {
12683 let filled = match fill_method {
12684 None => self.clone(),
12685 Some(method) => match method {
12686 "ffill" | "pad" => self.ffill(limit)?,
12687 "bfill" | "backfill" => self.bfill(limit)?,
12688 other => {
12689 return Err(ColumnError::Type(TypeError::NonNumericValue {
12690 value: other.to_string(),
12691 dtype: self.dtype,
12692 }));
12693 }
12694 },
12695 };
12696 filled.pct_change(periods)
12697 }
12698
12699 pub fn describe(&self) -> Result<Vec<(&'static str, Scalar)>, ColumnError> {
12708 if !matches!(
12709 self.dtype,
12710 DType::Int64 | DType::Float64 | DType::Timedelta64
12711 ) {
12712 return Err(ColumnError::Type(TypeError::NonNumericValue {
12713 value: format!("{:?}", self.dtype),
12714 dtype: self.dtype,
12715 }));
12716 }
12717 let count = Scalar::Int64(self.count() as i64);
12718 let mean = self.mean();
12719 let std = {
12720 let nums: Vec<f64> = self
12721 .values
12722 .iter()
12723 .filter(|v| !v.is_missing())
12724 .filter_map(|v| v.to_f64().ok())
12725 .collect();
12726 if nums.len() < 2 {
12727 Scalar::Null(NullKind::NaN)
12728 } else {
12729 let mu = nums.iter().sum::<f64>() / nums.len() as f64;
12730 let ss: f64 = nums.iter().map(|x| (x - mu).powi(2)).sum();
12731 Scalar::Float64((ss / (nums.len() as f64 - 1.0)).sqrt())
12732 }
12733 };
12734 let q25 = self.quantile(0.25);
12735 let q50 = self.quantile(0.5);
12736 let q75 = self.quantile(0.75);
12737 let min = self.min();
12738 let max = self.max();
12739 Ok(vec![
12740 ("count", count),
12741 ("mean", mean),
12742 ("std", std),
12743 ("min", min),
12744 ("25%", q25),
12745 ("50%", q50),
12746 ("75%", q75),
12747 ("max", max),
12748 ])
12749 }
12750
12751 pub fn combine<F>(
12759 &self,
12760 other: &Self,
12761 mut func: F,
12762 fill: Option<Scalar>,
12763 ) -> Result<Self, ColumnError>
12764 where
12765 F: FnMut(&Scalar, &Scalar) -> Scalar,
12766 {
12767 if self.values.len() != other.values.len() {
12768 return Err(ColumnError::LengthMismatch {
12769 left: self.values.len(),
12770 right: other.values.len(),
12771 });
12772 }
12773 let out: Vec<Scalar> = self
12774 .values
12775 .iter()
12776 .zip(other.values.iter())
12777 .map(|(a, b)| {
12778 let a_miss = a.is_missing();
12779 let b_miss = b.is_missing();
12780 match (a_miss || b_miss, fill.as_ref()) {
12781 (true, None) => Scalar::Null(NullKind::NaN),
12783 (_, fill_opt) => {
12784 let default = fill_opt.unwrap_or(a);
12785 let left = if a_miss { default } else { a };
12786 let right = if b_miss { fill_opt.unwrap_or(b) } else { b };
12787 func(left, right)
12788 }
12789 }
12790 })
12791 .collect();
12792 let inferred = infer_dtype(&out).unwrap_or(self.dtype);
12793 Self::new(inferred, out)
12794 }
12795
12796 pub fn apply_float<F>(&self, mut func: F) -> Result<Self, ColumnError>
12805 where
12806 F: FnMut(f64) -> f64,
12807 {
12808 let mut out = Vec::with_capacity(self.values.len());
12809 for v in &self.values {
12810 if v.is_missing() {
12811 out.push(Scalar::Null(NullKind::NaN));
12812 continue;
12813 }
12814 match v.to_f64() {
12815 Ok(x) => {
12816 let y = func(x);
12817 if y.is_nan() {
12818 out.push(Scalar::Null(NullKind::NaN));
12819 } else {
12820 out.push(Scalar::Float64(y));
12821 }
12822 }
12823 Err(err) => return Err(ColumnError::Type(err)),
12824 }
12825 }
12826 Self::new(DType::Float64, out)
12827 }
12828
12829 #[must_use]
12837 pub fn hist_counts(&self, bins: usize) -> Vec<usize> {
12838 if bins == 0 {
12839 return Vec::new();
12840 }
12841 let nums: Vec<f64> = self
12842 .values
12843 .iter()
12844 .filter(|v| !v.is_missing())
12845 .filter_map(|v| v.to_f64().ok())
12846 .filter(|f| !f.is_nan())
12847 .collect();
12848 if nums.is_empty() {
12849 return vec![0; bins];
12850 }
12851 let (min, max) = nums
12852 .iter()
12853 .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| {
12854 (lo.min(x), hi.max(x))
12855 });
12856 if (max - min).abs() < f64::EPSILON {
12857 let mut counts = vec![0; bins];
12859 counts[0] = nums.len();
12860 return counts;
12861 }
12862 let width = (max - min) / bins as f64;
12863 let mut counts = vec![0usize; bins];
12864 for x in &nums {
12865 let mut idx = ((x - min) / width) as usize;
12866 if idx >= bins {
12867 idx = bins - 1;
12868 }
12869 counts[idx] += 1;
12870 }
12871 counts
12872 }
12873
12874 #[must_use]
12880 pub fn argmin(&self) -> Option<usize> {
12881 nanargmin(&self.values)
12882 }
12883
12884 #[must_use]
12887 pub fn idxmin(&self) -> Option<usize> {
12888 self.argmin()
12889 }
12890
12891 #[must_use]
12896 pub fn argmax(&self) -> Option<usize> {
12897 nanargmax(&self.values)
12898 }
12899
12900 #[must_use]
12903 pub fn idxmax(&self) -> Option<usize> {
12904 self.argmax()
12905 }
12906
12907 #[must_use]
12909 pub fn nanargmin(&self) -> Option<usize> {
12910 self.argmin()
12911 }
12912
12913 #[must_use]
12915 pub fn nanargmax(&self) -> Option<usize> {
12916 self.argmax()
12917 }
12918
12919 #[must_use]
12925 pub fn is_monotonic_increasing(&self) -> bool {
12926 is_monotonic_in_direction(&self.values, true)
12927 }
12928
12929 #[must_use]
12933 pub fn is_monotonic_decreasing(&self) -> bool {
12934 is_monotonic_in_direction(&self.values, false)
12935 }
12936
12937 pub fn combine_first(&self, other: &Self) -> Result<Self, ColumnError> {
12945 if self.values.len() != other.values.len() {
12946 return Err(ColumnError::LengthMismatch {
12947 left: self.values.len(),
12948 right: other.values.len(),
12949 });
12950 }
12951 let out: Vec<Scalar> = self
12952 .values
12953 .iter()
12954 .zip(other.values.iter())
12955 .map(|(a, b)| if a.is_missing() { b.clone() } else { a.clone() })
12956 .collect();
12957 Self::new(self.dtype, out)
12958 }
12959
12960 pub fn clip_lower(&self, lower: f64) -> Result<Self, ColumnError> {
12966 self.clip(Some(lower), None)
12967 }
12968
12969 pub fn clip_upper(&self, upper: f64) -> Result<Self, ColumnError> {
12973 self.clip(None, Some(upper))
12974 }
12975
12976 pub fn drop_duplicates(&self) -> Result<Self, ColumnError> {
12980 self.drop_duplicates_keep("first")
12981 }
12982
12983 pub fn drop_duplicates_keep(&self, keep: &str) -> Result<Self, ColumnError> {
12988 let dup = self.duplicated_keep(keep)?;
12989 let mut out = Vec::with_capacity(self.values.len());
12990 for (v, keep_flag) in self.values.iter().zip(dup.values.iter()) {
12991 if matches!(keep_flag, Scalar::Bool(false)) {
12992 out.push(v.clone());
12993 }
12994 }
12995 Self::new(self.dtype, out)
12996 }
12997
12998 pub fn compare(&self, other: &Self) -> Result<(Self, Self), ColumnError> {
13006 if self.values.len() != other.values.len() {
13007 return Err(ColumnError::LengthMismatch {
13008 left: self.values.len(),
13009 right: other.values.len(),
13010 });
13011 }
13012 let mut left = Vec::new();
13013 let mut right = Vec::new();
13014 for (a, b) in self.values.iter().zip(other.values.iter()) {
13015 let equal = match (a.is_missing(), b.is_missing()) {
13016 (true, true) => true,
13017 (true, false) | (false, true) => false,
13018 (false, false) => a.semantic_eq(b),
13019 };
13020 if !equal {
13021 left.push(a.clone());
13022 right.push(b.clone());
13023 }
13024 }
13025 Ok((Self::new(self.dtype, left)?, Self::new(other.dtype, right)?))
13026 }
13027
13028 pub fn map<F>(&self, mut func: F) -> Result<Self, ColumnError>
13036 where
13037 F: FnMut(&Scalar) -> Scalar,
13038 {
13039 let out: Vec<Scalar> = self.values.iter().map(&mut func).collect();
13040 let target = infer_dtype(&out).unwrap_or(self.dtype);
13041 Self::new(target, out)
13042 }
13043
13044 pub fn interpolate_linear(&self) -> Result<Self, ColumnError> {
13053 let len = self.values.len();
13054 let mut floats: Vec<Option<f64>> = Vec::with_capacity(len);
13056 for v in &self.values {
13057 if v.is_missing() {
13058 floats.push(None);
13059 continue;
13060 }
13061 match v.to_f64() {
13062 Ok(x) if !x.is_nan() => floats.push(Some(x)),
13063 Ok(_) => floats.push(None),
13064 Err(err) => return Err(ColumnError::Type(err)),
13065 }
13066 }
13067
13068 let first = floats.iter().position(Option::is_some);
13070 let last = floats.iter().rposition(Option::is_some);
13071 if let (Some(start), Some(end)) = (first, last) {
13072 let mut i = start;
13073 while i < end {
13074 if floats[i].is_some() {
13075 i += 1;
13076 continue;
13077 }
13078 let gap_start = i;
13079 while i < end && floats[i].is_none() {
13080 i += 1;
13081 }
13082 let before = floats[gap_start - 1].expect("anchor");
13083 let after = floats[i].expect("anchor");
13084 let span = (i - gap_start + 1) as f64;
13085 for (k, j) in (gap_start..i).enumerate() {
13086 let step = (k + 1) as f64;
13087 floats[j] = Some(before + (after - before) * (step / span));
13088 }
13089 }
13090 let last_valid = floats[end].expect("last valid anchor");
13095 for slot in floats.iter_mut().skip(end + 1) {
13096 *slot = Some(last_valid);
13097 }
13098 }
13099
13100 let out: Vec<Scalar> = floats
13101 .into_iter()
13102 .map(|opt| match opt {
13103 Some(x) => Scalar::Float64(x),
13104 None => Scalar::Null(NullKind::NaN),
13105 })
13106 .collect();
13107 Self::new(DType::Float64, out)
13108 }
13109
13110 pub fn interpolate(&self) -> Result<Self, ColumnError> {
13113 self.interpolate_linear()
13114 }
13115
13116 #[must_use]
13122 pub fn quantile(&self, q: f64) -> Scalar {
13123 nanquantile(&self.values, q)
13124 }
13125
13126 #[must_use]
13130 pub fn percentile(&self, p: f64) -> Scalar {
13131 self.quantile(p / 100.0)
13132 }
13133
13134 #[must_use]
13136 pub fn nanquantile(&self, q: f64) -> Scalar {
13137 self.quantile(q)
13138 }
13139
13140 #[must_use]
13142 pub fn nanpercentile(&self, p: f64) -> Scalar {
13143 self.percentile(p)
13144 }
13145
13146 pub fn mode(&self) -> Result<Self, ColumnError> {
13152 if let Some(data) = self.as_i64_slice()
13164 && let Some((min, range)) = i64_direct_address_range(data)
13165 {
13166 let mut count = vec![0i64; range];
13167 for &v in data {
13168 count[(v as i128 - min as i128) as usize] += 1;
13169 }
13170 let max_count = count.iter().copied().max().unwrap_or(0);
13171 let mut winners = Vec::new();
13172 for (s, &c) in count.iter().enumerate() {
13173 if c == max_count {
13174 winners.push(Scalar::Int64(min + s as i64));
13175 }
13176 }
13177 return Self::new(self.dtype, winners);
13178 }
13179
13180 #[derive(Hash, PartialEq, Eq)]
13181 enum Key<'a> {
13182 Bool(bool),
13183 Int64(i64),
13184 FloatBits(u64),
13185 Utf8(&'a str),
13186 Timedelta64(i64),
13187 Datetime64(i64),
13188 Period(i64),
13189 Interval(u64, u64, IntervalClosed),
13190 }
13191 fn key_of(v: &Scalar) -> Option<Key<'_>> {
13192 if v.is_missing() {
13193 return None;
13194 }
13195 Some(match v {
13196 Scalar::Bool(b) => Key::Bool(*b),
13197 Scalar::Int64(i) => Key::Int64(*i),
13198 Scalar::Float64(f) => {
13199 let norm = if *f == 0.0 { 0.0 } else { *f };
13200 Key::FloatBits(norm.to_bits())
13201 }
13202 Scalar::Utf8(s) => Key::Utf8(s.as_str()),
13203 Scalar::Timedelta64(v) => Key::Timedelta64(*v),
13204 Scalar::Datetime64(v) => Key::Datetime64(*v),
13205 Scalar::Period(p) => Key::Period(p.ordinal),
13206 Scalar::Interval(v) => {
13207 let (left, right, closed) = interval_key(v);
13208 Key::Interval(left, right, closed)
13209 }
13210 Scalar::Null(_) => return None,
13211 })
13212 }
13213
13214 let mut counts: FxHashMap<Key<'_>, (usize, &Scalar)> = FxHashMap::default();
13215 for v in &self.values {
13216 if let Some(k) = key_of(v) {
13217 counts
13218 .entry(k)
13219 .and_modify(|entry| entry.0 += 1)
13220 .or_insert((1, v));
13221 }
13222 }
13223 if counts.is_empty() {
13224 return Self::new(self.dtype, Vec::new());
13225 }
13226 let max_count = counts.values().map(|(c, _)| *c).max().unwrap_or(0);
13227 let mut winners: Vec<Scalar> = counts
13228 .values()
13229 .filter_map(|(c, v)| {
13230 if *c == max_count {
13231 Some((*v).clone())
13232 } else {
13233 None
13234 }
13235 })
13236 .collect();
13237 winners.sort_by(|a, b| compare_scalars_na_last(a, b, true));
13238 Self::new(self.dtype, winners)
13239 }
13240
13241 #[must_use]
13249 pub fn memory_usage(&self, deep: bool) -> usize {
13250 let element_bytes = match self.dtype {
13251 DType::Bool => 1,
13252 DType::Int64 | DType::Float64 | DType::Timedelta64 => 8,
13253 DType::Utf8 => std::mem::size_of::<usize>(),
13254 _ => 0,
13255 };
13256 let base = element_bytes * self.values.len();
13257 let deep_extra = if deep && self.dtype == DType::Utf8 {
13258 self.values
13259 .iter()
13260 .map(|v| match v {
13261 Scalar::Utf8(s) => s.len(),
13262 _ => 0,
13263 })
13264 .sum::<usize>()
13265 } else {
13266 0
13267 };
13268 let validity_bytes = self.values.len().div_ceil(8);
13270 base + deep_extra + validity_bytes
13271 }
13272
13273 #[must_use]
13275 pub fn nbytes(&self) -> usize {
13276 self.memory_usage(false)
13277 }
13278
13279 #[must_use]
13284 pub fn itemsize(&self) -> usize {
13285 match self.dtype() {
13286 DType::Bool | DType::BoolNullable => 1,
13287 DType::Int64
13288 | DType::Int64Nullable
13289 | DType::Float64
13290 | DType::Datetime64
13291 | DType::Timedelta64
13292 | DType::Period => 8,
13293 DType::Utf8 => {
13294 if self.values.is_empty() {
13295 0
13296 } else {
13297 self.memory_usage(true) / self.values.len()
13298 }
13299 }
13300 DType::Null | DType::Categorical | DType::Interval | DType::Sparse => 8,
13301 }
13302 }
13303
13304 pub fn equals(&self, other: &Self) -> Result<Self, ColumnError> {
13310 if self.values.len() != other.values.len() {
13311 return Err(ColumnError::LengthMismatch {
13312 left: self.values.len(),
13313 right: other.values.len(),
13314 });
13315 }
13316 let out: Vec<Scalar> = self
13317 .values
13318 .iter()
13319 .zip(other.values.iter())
13320 .map(|(a, b)| {
13321 if a.is_missing() || b.is_missing() {
13322 Scalar::Bool(false)
13323 } else {
13324 Scalar::Bool(a.semantic_eq(b))
13325 }
13326 })
13327 .collect();
13328 Self::new(DType::Bool, out)
13329 }
13330
13331 pub fn dot(&self, other: &Self) -> Result<f64, ColumnError> {
13339 if self.values.len() != other.values.len() {
13340 return Err(ColumnError::LengthMismatch {
13341 left: self.values.len(),
13342 right: other.values.len(),
13343 });
13344 }
13345 let mut sum = 0.0_f64;
13346 for (a, b) in self.values.iter().zip(other.values.iter()) {
13347 if a.is_missing() || b.is_missing() {
13348 continue;
13349 }
13350 let av = a.to_f64().map_err(ColumnError::Type)?;
13351 let bv = b.to_f64().map_err(ColumnError::Type)?;
13352 if av.is_nan() || bv.is_nan() {
13353 continue;
13354 }
13355 sum += av * bv;
13356 }
13357 Ok(sum)
13358 }
13359
13360 pub fn convolve(&self, kernel: &Self, mode: &str) -> Result<Self, ColumnError> {
13367 let a: Vec<f64> = self
13368 .values
13369 .iter()
13370 .map(|v| v.to_f64().unwrap_or(0.0))
13371 .collect();
13372 let v: Vec<f64> = kernel
13373 .values
13374 .iter()
13375 .map(|v| v.to_f64().unwrap_or(0.0))
13376 .collect();
13377
13378 if a.is_empty() || v.is_empty() {
13379 return Self::new(DType::Float64, vec![]);
13380 }
13381
13382 let full_len = a.len() + v.len() - 1;
13383 let mut full: Vec<f64> = vec![0.0; full_len];
13384
13385 for (i, &ai) in a.iter().enumerate() {
13386 for (j, &vj) in v.iter().enumerate() {
13387 full[i + j] += ai * vj;
13388 }
13389 }
13390
13391 let out: Vec<f64> = match mode {
13392 "full" => full,
13393 "same" => {
13394 let target_len = a.len().max(v.len());
13395 let start = (full_len - target_len) / 2;
13396 full[start..start + target_len].to_vec()
13397 }
13398 "valid" => {
13399 let min_len = a.len().min(v.len());
13400 let valid_len = a.len().max(v.len()) - min_len + 1;
13401 let start = min_len - 1;
13402 full[start..start + valid_len].to_vec()
13403 }
13404 _ => {
13405 return Err(ColumnError::Type(TypeError::NonNumericValue {
13406 value: format!("invalid mode '{mode}', expected 'full', 'same', or 'valid'"),
13407 dtype: self.dtype,
13408 }));
13409 }
13410 };
13411
13412 let scalars: Vec<Scalar> = out.into_iter().map(Scalar::Float64).collect();
13413 Self::new(DType::Float64, scalars)
13414 }
13415
13416 pub fn correlate(&self, other: &Self, mode: &str) -> Result<Self, ColumnError> {
13420 let reversed = other.reverse()?;
13421 self.convolve(&reversed, mode)
13422 }
13423
13424 pub fn fillna_with_column(&self, other: &Self) -> Result<Self, ColumnError> {
13431 if self.values.len() != other.values.len() {
13432 return Err(ColumnError::LengthMismatch {
13433 left: self.values.len(),
13434 right: other.values.len(),
13435 });
13436 }
13437 let out: Vec<Scalar> = self
13438 .values
13439 .iter()
13440 .zip(other.values.iter())
13441 .map(|(v, o)| {
13442 if v.is_missing() {
13443 cast_scalar(o, self.dtype)
13444 } else {
13445 Ok(v.clone())
13446 }
13447 })
13448 .collect::<Result<Vec<_>, _>>()
13449 .map_err(ColumnError::Type)?;
13450 Self::new(self.dtype, out)
13451 }
13452
13453 pub fn divmod(&self, divisor: &Self) -> Result<(Self, Self), ColumnError> {
13461 if self.values.len() != divisor.values.len() {
13462 return Err(ColumnError::LengthMismatch {
13463 left: self.values.len(),
13464 right: divisor.values.len(),
13465 });
13466 }
13467 let mut quotient = Vec::with_capacity(self.values.len());
13468 let mut remainder = Vec::with_capacity(self.values.len());
13469 for (a, b) in self.values.iter().zip(divisor.values.iter()) {
13470 if a.is_missing() || b.is_missing() {
13471 quotient.push(Scalar::Null(NullKind::NaN));
13472 remainder.push(Scalar::Null(NullKind::NaN));
13473 continue;
13474 }
13475 let num = match a.to_f64() {
13476 Ok(x) if !x.is_nan() => x,
13477 _ => {
13478 quotient.push(Scalar::Null(NullKind::NaN));
13479 remainder.push(Scalar::Null(NullKind::NaN));
13480 continue;
13481 }
13482 };
13483 let den = match b.to_f64() {
13484 Ok(x) if !x.is_nan() => x,
13485 _ => {
13486 quotient.push(Scalar::Null(NullKind::NaN));
13487 remainder.push(Scalar::Null(NullKind::NaN));
13488 continue;
13489 }
13490 };
13491 if den == 0.0 {
13492 quotient.push(Scalar::Null(NullKind::NaN));
13493 remainder.push(Scalar::Null(NullKind::NaN));
13494 continue;
13495 }
13496 let q = python_floor_div_f64(num, den);
13499 let r = python_mod_f64(num, den);
13500 quotient.push(Scalar::Float64(q));
13501 remainder.push(Scalar::Float64(r));
13502 }
13503 Ok((
13504 Self::new(DType::Float64, quotient)?,
13505 Self::new(DType::Float64, remainder)?,
13506 ))
13507 }
13508
13509 pub fn where_cond_series(&self, cond: &Self, other: &Self) -> Result<Self, ColumnError> {
13518 if cond.dtype != DType::Bool {
13519 return Err(ColumnError::InvalidMaskType { dtype: cond.dtype });
13520 }
13521 if self.values.len() != cond.values.len() || self.values.len() != other.values.len() {
13522 return Err(ColumnError::LengthMismatch {
13523 left: self.values.len(),
13524 right: cond.values.len().max(other.values.len()),
13525 });
13526 }
13527 if let Some(cb) = cond.as_bool_slice() {
13534 if let (Some(s), Some(o)) = (self.as_f64_slice(), other.as_f64_slice()) {
13535 let out: Vec<f64> = (0..s.len())
13536 .map(|i| if cb[i] { s[i] } else { o[i] })
13537 .collect();
13538 return Ok(Self::from_f64_values(out));
13539 }
13540 if let (Some(s), Some(o)) = (self.as_i64_slice(), other.as_i64_slice()) {
13541 let out: Vec<i64> = (0..s.len())
13542 .map(|i| if cb[i] { s[i] } else { o[i] })
13543 .collect();
13544 return Ok(Self::from_i64_values(out));
13545 }
13546 }
13547 let out: Vec<Scalar> = self
13548 .values
13549 .iter()
13550 .zip(cond.values.iter().zip(other.values.iter()))
13551 .map(|(v, (c, o))| match c {
13552 Scalar::Bool(true) => Ok(v.clone()),
13553 Scalar::Bool(false) => cast_scalar(o, self.dtype),
13554 _ => Ok(Scalar::Null(NullKind::NaN)),
13555 })
13556 .collect::<Result<Vec<_>, _>>()
13557 .map_err(ColumnError::Type)?;
13558 Self::new(self.dtype, out)
13559 }
13560
13561 pub fn mask_series(&self, cond: &Self, other: &Self) -> Result<Self, ColumnError> {
13566 if cond.dtype != DType::Bool {
13567 return Err(ColumnError::InvalidMaskType { dtype: cond.dtype });
13568 }
13569 if self.values.len() != cond.values.len() || self.values.len() != other.values.len() {
13570 return Err(ColumnError::LengthMismatch {
13571 left: self.values.len(),
13572 right: cond.values.len().max(other.values.len()),
13573 });
13574 }
13575 if let Some(cb) = cond.as_bool_slice() {
13578 if let (Some(s), Some(o)) = (self.as_f64_slice(), other.as_f64_slice()) {
13579 let out: Vec<f64> = (0..s.len())
13580 .map(|i| if cb[i] { o[i] } else { s[i] })
13581 .collect();
13582 return Ok(Self::from_f64_values(out));
13583 }
13584 if let (Some(s), Some(o)) = (self.as_i64_slice(), other.as_i64_slice()) {
13585 let out: Vec<i64> = (0..s.len())
13586 .map(|i| if cb[i] { o[i] } else { s[i] })
13587 .collect();
13588 return Ok(Self::from_i64_values(out));
13589 }
13590 }
13591 let out: Vec<Scalar> = self
13592 .values
13593 .iter()
13594 .zip(cond.values.iter().zip(other.values.iter()))
13595 .map(|(v, (c, o))| match c {
13596 Scalar::Bool(true) => cast_scalar(o, self.dtype),
13597 Scalar::Bool(false) => Ok(v.clone()),
13598 _ => Ok(Scalar::Null(NullKind::NaN)),
13599 })
13600 .collect::<Result<Vec<_>, _>>()
13601 .map_err(ColumnError::Type)?;
13602 Self::new(self.dtype, out)
13603 }
13604
13605 pub fn replace_values(
13615 &self,
13616 to_replace: &[Scalar],
13617 replacement: &[Scalar],
13618 ) -> Result<Self, ColumnError> {
13619 if to_replace.len() != replacement.len() {
13620 return Err(ColumnError::LengthMismatch {
13621 left: to_replace.len(),
13622 right: replacement.len(),
13623 });
13624 }
13625 let out: Vec<Scalar> = self
13626 .values
13627 .iter()
13628 .map(|v| {
13629 for (target, replacement_val) in to_replace.iter().zip(replacement.iter()) {
13630 let matches = if target.is_missing() && v.is_missing() {
13632 true
13633 } else if target.is_missing() || v.is_missing() {
13634 false
13635 } else {
13636 v.semantic_eq(target)
13637 };
13638 if matches {
13639 return replacement_val.clone();
13640 }
13641 }
13642 v.clone()
13643 })
13644 .collect();
13645 let inferred = infer_dtype(&out).unwrap_or(self.dtype);
13646 Self::new(inferred, out)
13647 }
13648
13649 pub fn replace(
13653 &self,
13654 to_replace: &[Scalar],
13655 replacement: &[Scalar],
13656 ) -> Result<Self, ColumnError> {
13657 self.replace_values(to_replace, replacement)
13658 }
13659
13660 #[must_use]
13667 pub fn nonzero(&self) -> Vec<usize> {
13668 let mut out = Vec::new();
13669 for (i, v) in self.values.iter().enumerate() {
13670 if v.is_missing() {
13671 continue;
13672 }
13673 let truthy = match v {
13674 Scalar::Bool(b) => *b,
13675 Scalar::Int64(x) => *x != 0,
13676 Scalar::Float64(x) => *x != 0.0 && !x.is_nan(),
13677 Scalar::Utf8(s) => !s.is_empty(),
13678 Scalar::Timedelta64(x) => *x != 0,
13679 Scalar::Datetime64(x) => *x != Timestamp::NAT,
13680 Scalar::Period(p) => p.ordinal != i64::MIN,
13681 Scalar::Interval(_) => true,
13682 Scalar::Null(_) => false,
13683 };
13684 if truthy {
13685 out.push(i);
13686 }
13687 }
13688 out
13689 }
13690
13691 #[must_use]
13695 pub fn count_nonzero(&self) -> usize {
13696 self.nonzero().len()
13697 }
13698
13699 pub fn flatnonzero(&self) -> Result<Self, ColumnError> {
13703 let indices: Vec<Scalar> = self
13704 .nonzero()
13705 .into_iter()
13706 .map(|i| Scalar::Int64(i as i64))
13707 .collect();
13708 Self::new(DType::Int64, indices)
13709 }
13710
13711 pub fn where_cond(&self, cond: &Self, other: &Scalar) -> Result<Self, ColumnError> {
13718 if cond.dtype != DType::Bool {
13719 return Err(ColumnError::InvalidMaskType { dtype: cond.dtype });
13720 }
13721 if self.values.len() != cond.values.len() {
13722 return Err(ColumnError::LengthMismatch {
13723 left: self.values.len(),
13724 right: cond.values.len(),
13725 });
13726 }
13727 if !other.is_missing()
13733 && let Some(cb) = cond.as_bool_slice()
13734 {
13735 if let Some(s) = self.as_f64_slice()
13736 && let Ok(o) = other.to_f64()
13737 {
13738 let out: Vec<f64> = (0..s.len()).map(|i| if cb[i] { s[i] } else { o }).collect();
13739 return Ok(Self::from_f64_values(out));
13740 }
13741 if let Some(s) = self.as_i64_slice()
13742 && let Scalar::Int64(o) = other
13743 {
13744 let o = *o;
13745 let out: Vec<i64> = (0..s.len()).map(|i| if cb[i] { s[i] } else { o }).collect();
13746 return Ok(Self::from_i64_values(out));
13747 }
13748 }
13749 let out: Vec<Scalar> = self
13750 .values
13751 .iter()
13752 .zip(cond.values.iter())
13753 .map(|(v, c)| match c {
13754 Scalar::Bool(true) => v.clone(),
13755 Scalar::Bool(false) => other.clone(),
13756 _ => Scalar::Null(NullKind::NaN),
13757 })
13758 .collect();
13759 Self::new(self.dtype, out)
13760 }
13761
13762 pub fn r#where(&self, cond: &Self, other: &Scalar) -> Result<Self, ColumnError> {
13765 self.where_cond(cond, other)
13766 }
13767
13768 pub fn rank(&self, method: &str, ascending: bool) -> Result<Self, ColumnError> {
13781 let valid_method = matches!(method, "average" | "min" | "max" | "first" | "dense");
13782 if !valid_method {
13783 return Err(ColumnError::Type(TypeError::NonNumericValue {
13784 value: method.to_string(),
13785 dtype: self.dtype,
13786 }));
13787 }
13788
13789 let len = self.values.len();
13790
13791 if let Some(data) = self.as_i64_slice()
13800 && let Some((min, range)) = i64_direct_address_range(data)
13801 {
13802 let total = data.len() as i64;
13803 let mut count = vec![0i64; range];
13804 for &v in data {
13805 count[(v as i128 - min as i128) as usize] += 1;
13806 }
13807 let mut c_less = vec![0i64; range];
13810 let mut dense_asc = vec![0i64; range];
13811 let mut acc = 0i64;
13812 let mut ord = 0i64;
13813 for s in 0..range {
13814 c_less[s] = acc;
13815 if count[s] > 0 {
13816 ord += 1;
13817 dense_asc[s] = ord;
13818 }
13819 acc += count[s];
13820 }
13821 let n_distinct = ord;
13822 let mut occ = vec![0i64; range];
13823 let mut ranks = vec![0.0_f64; len];
13830 for (i, &v) in data.iter().enumerate() {
13831 let s = (v as i128 - min as i128) as usize;
13832 let c = count[s];
13833 let before = if ascending {
13837 c_less[s]
13838 } else {
13839 total - c_less[s] - c
13840 };
13841 let start_rank = before as f64 + 1.0;
13842 let end_rank = (before + c) as f64;
13843 let value = match method {
13844 "average" => (start_rank + end_rank) / 2.0,
13845 "min" => start_rank,
13846 "max" => end_rank,
13847 "first" => {
13848 let k = occ[s];
13849 occ[s] += 1;
13850 (before + k) as f64 + 1.0
13851 }
13852 "dense" => {
13853 let d = if ascending {
13854 dense_asc[s]
13855 } else {
13856 n_distinct - dense_asc[s] + 1
13857 };
13858 d as f64
13859 }
13860 _ => unreachable!(),
13861 };
13862 ranks[i] = value;
13863 }
13864 return Ok(Self::from_f64_values(ranks));
13865 }
13866
13867 if let Some(data) = self.as_f64_slice()
13882 && !data.iter().any(|x| x.is_nan())
13883 {
13884 let perm = self
13885 .typed_radix_perm(ascending)
13886 .expect("f64 slice yields radix perm");
13887 let n = perm.len();
13888 let mut ranks = vec![0.0_f64; len];
13889 let mut cursor = 0usize;
13890 let mut dense_rank = 0f64;
13891 while cursor < n {
13892 let mut end = cursor + 1;
13893 while end < n && data[perm[end]] == data[perm[cursor]] {
13894 end += 1;
13895 }
13896 let start_rank = cursor as f64 + 1.0;
13897 let end_rank = end as f64;
13898 dense_rank += 1.0;
13899 #[allow(clippy::needless_range_loop)] for group_idx in cursor..end {
13901 let original = perm[group_idx];
13902 ranks[original] = match method {
13903 "average" => (start_rank + end_rank) / 2.0,
13904 "min" => start_rank,
13905 "max" => end_rank,
13906 "first" => group_idx as f64 + 1.0,
13907 "dense" => dense_rank,
13908 _ => unreachable!(),
13909 };
13910 }
13911 cursor = end;
13912 }
13913 return Ok(Self::from_f64_values(ranks));
13914 }
13915
13916 let mut non_missing: Vec<(usize, &Scalar)> = Vec::with_capacity(len);
13917 for (i, v) in self.values.iter().enumerate() {
13918 if !v.is_missing() {
13919 non_missing.push((i, v));
13920 }
13921 }
13922 non_missing.sort_by(|a, b| compare_scalars_na_last(a.1, b.1, ascending));
13923
13924 let mut ranks = vec![Scalar::Null(NullKind::NaN); len];
13925 let n = non_missing.len();
13926 let mut cursor = 0usize;
13927 let mut dense_rank = 0f64;
13928 while cursor < n {
13929 let mut end = cursor + 1;
13930 while end < n {
13931 let same =
13932 compare_scalars_na_last(non_missing[cursor].1, non_missing[end].1, ascending)
13933 .is_eq();
13934 if !same {
13935 break;
13936 }
13937 end += 1;
13938 }
13939 let start_rank = cursor as f64 + 1.0;
13940 let end_rank = end as f64;
13941 dense_rank += 1.0;
13942 for (group_idx, entry) in non_missing.iter().enumerate().take(end).skip(cursor) {
13943 let original = entry.0;
13944 let value = match method {
13945 "average" => (start_rank + end_rank) / 2.0,
13946 "min" => start_rank,
13947 "max" => end_rank,
13948 "first" => group_idx as f64 + 1.0,
13949 "dense" => dense_rank,
13950 _ => unreachable!(),
13951 };
13952 ranks[original] = Scalar::Float64(value);
13953 }
13954 cursor = end;
13955 }
13956 Self::new(DType::Float64, ranks)
13957 }
13958
13959 pub fn searchsorted(&self, needle: &Scalar, side: &str) -> Result<usize, ColumnError> {
13967 self.searchsorted_position(needle, side, None)
13968 }
13969
13970 pub fn searchsorted_with_sorter(
13975 &self,
13976 needle: &Scalar,
13977 side: &str,
13978 sorter: &[usize],
13979 ) -> Result<usize, ColumnError> {
13980 self.searchsorted_position(needle, side, Some(sorter))
13981 }
13982
13983 pub fn searchsorted_values(&self, needles: &[Scalar], side: &str) -> Result<Self, ColumnError> {
13989 let positions: Vec<Scalar> = needles
13990 .iter()
13991 .map(|needle| self.searchsorted_position(needle, side, None))
13992 .map(|result| result.map(|position| Scalar::Int64(position as i64)))
13993 .collect::<Result<Vec<_>, _>>()?;
13994 Self::new(DType::Int64, positions)
13995 }
13996
13997 pub fn searchsorted_values_with_sorter(
14002 &self,
14003 needles: &[Scalar],
14004 side: &str,
14005 sorter: &[usize],
14006 ) -> Result<Self, ColumnError> {
14007 let positions: Vec<Scalar> = needles
14008 .iter()
14009 .map(|needle| self.searchsorted_position(needle, side, Some(sorter)))
14010 .map(|result| result.map(|position| Scalar::Int64(position as i64)))
14011 .collect::<Result<Vec<_>, _>>()?;
14012 Self::new(DType::Int64, positions)
14013 }
14014
14015 fn searchsorted_position(
14016 &self,
14017 needle: &Scalar,
14018 side: &str,
14019 sorter: Option<&[usize]>,
14020 ) -> Result<usize, ColumnError> {
14021 if side != "left" && side != "right" {
14022 return Err(ColumnError::Type(TypeError::NonNumericValue {
14023 value: side.to_string(),
14024 dtype: self.dtype,
14025 }));
14026 }
14027 if needle.is_missing() {
14028 return Err(ColumnError::Type(TypeError::ValueIsMissing {
14029 kind: NullKind::NaN,
14030 }));
14031 }
14032
14033 let sorter = self.validate_searchsorted_sorter(sorter)?;
14034 let len = sorter.map_or(self.values.len(), <[usize]>::len);
14035 let mut lo = 0usize;
14036 let mut hi = len;
14037 while lo < hi {
14038 let mid = lo + (hi - lo) / 2;
14039 let mid_idx = sorter.map_or(mid, |indices| indices[mid]);
14040 let mid_val = &self.values[mid_idx];
14041 let ord = if mid_val.is_missing() {
14044 std::cmp::Ordering::Greater
14045 } else {
14046 compare_scalars_na_last(mid_val, needle, true)
14047 };
14048 use std::cmp::Ordering;
14049 let go_right = match (ord, side) {
14050 (Ordering::Less, _) => true,
14051 (Ordering::Equal, "left") => false,
14052 (Ordering::Equal, "right") => true,
14053 (Ordering::Greater, _) => false,
14054 _ => unreachable!(),
14055 };
14056 if go_right {
14057 lo = mid + 1;
14058 } else {
14059 hi = mid;
14060 }
14061 }
14062 Ok(lo)
14063 }
14064
14065 fn validate_searchsorted_sorter<'a>(
14066 &self,
14067 sorter: Option<&'a [usize]>,
14068 ) -> Result<Option<&'a [usize]>, ColumnError> {
14069 let Some(sorter) = sorter else {
14070 return Ok(None);
14071 };
14072 let len = self.values.len();
14073 if sorter.len() != len {
14074 return Err(ColumnError::LengthMismatch {
14075 left: len,
14076 right: sorter.len(),
14077 });
14078 }
14079 let mut seen = vec![false; len];
14080 for &idx in sorter {
14081 if idx >= len {
14082 return Err(ColumnError::InvalidSorter {
14083 len,
14084 reason: format!("index {idx} out of bounds"),
14085 });
14086 }
14087 if std::mem::replace(&mut seen[idx], true) {
14088 return Err(ColumnError::InvalidSorter {
14089 len,
14090 reason: format!("index {idx} appears more than once"),
14091 });
14092 }
14093 }
14094 Ok(Some(sorter))
14095 }
14096
14097 pub fn digitize(&self, bins: &Self, right: bool) -> Result<Self, ColumnError> {
14101 let mut out = Vec::with_capacity(self.values.len());
14102 for v in &self.values {
14103 if v.is_missing() {
14104 out.push(Scalar::Int64(0));
14105 continue;
14106 }
14107 let vf = v.to_f64().map_err(ColumnError::Type)?;
14108 let side = if right { "right" } else { "left" };
14109 let pos = bins.searchsorted(&Scalar::Float64(vf), side)?;
14110 out.push(Scalar::Int64(pos as i64));
14111 }
14112 Self::new(DType::Int64, out)
14113 }
14114
14115 pub fn bincount(&self, minlength: usize) -> Result<Self, ColumnError> {
14120 let mut max_val = 0i64;
14121 for v in &self.values {
14122 if v.is_missing() {
14123 continue;
14124 }
14125 match v {
14126 Scalar::Int64(x) if *x >= 0 => {
14127 if *x > max_val {
14128 max_val = *x;
14129 }
14130 }
14131 Scalar::Int64(x) => {
14132 return Err(ColumnError::Type(TypeError::NonNumericValue {
14133 value: format!("negative value {x}"),
14134 dtype: self.dtype,
14135 }));
14136 }
14137 _ => {
14138 return Err(ColumnError::Type(TypeError::NonNumericValue {
14139 value: format!("{v:?}"),
14140 dtype: self.dtype,
14141 }));
14142 }
14143 }
14144 }
14145 let len = (max_val as usize + 1).max(minlength);
14146 let mut counts = vec![0i64; len];
14147 for v in &self.values {
14148 if v.is_missing() {
14149 continue;
14150 }
14151 if let Scalar::Int64(x) = v {
14152 counts[*x as usize] += 1;
14153 }
14154 }
14155 let out: Vec<Scalar> = counts.into_iter().map(Scalar::Int64).collect();
14156 Self::new(DType::Int64, out)
14157 }
14158
14159 pub fn histogram(&self, bin_edges: &[f64]) -> Result<Self, ColumnError> {
14164 if bin_edges.len() < 2 {
14165 return Err(ColumnError::Type(TypeError::NonNumericValue {
14166 value: "histogram requires at least 2 bin edges".to_owned(),
14167 dtype: self.dtype,
14168 }));
14169 }
14170 let n_bins = bin_edges.len() - 1;
14171 let mut counts = vec![0i64; n_bins];
14172
14173 let strict = bin_edges.windows(2).all(|w| w[0] < w[1]);
14183
14184 for v in &self.values {
14185 if v.is_missing() {
14186 continue;
14187 }
14188 let x = match v.to_f64() {
14189 Ok(f) if f.is_finite() => f,
14190 _ => continue,
14191 };
14192 if strict {
14193 if x < bin_edges[0] || x > bin_edges[n_bins] {
14194 continue;
14195 }
14196 let bin = (bin_edges.partition_point(|&e| e <= x) - 1).min(n_bins - 1);
14197 counts[bin] += 1;
14198 continue;
14199 }
14200 for i in 0..n_bins {
14202 let in_bin = if i == n_bins - 1 {
14203 x >= bin_edges[i] && x <= bin_edges[i + 1]
14205 } else {
14206 x >= bin_edges[i] && x < bin_edges[i + 1]
14207 };
14208 if in_bin {
14209 counts[i] += 1;
14210 break;
14211 }
14212 }
14213 }
14215
14216 let out: Vec<Scalar> = counts.into_iter().map(Scalar::Int64).collect();
14217 Self::new(DType::Int64, out)
14218 }
14219
14220 pub fn histogram_auto(&self, n_bins: usize) -> Result<(Self, Vec<f64>), ColumnError> {
14225 if n_bins == 0 {
14226 return Err(ColumnError::Type(TypeError::NonNumericValue {
14227 value: "histogram requires at least 1 bin".to_owned(),
14228 dtype: self.dtype,
14229 }));
14230 }
14231
14232 let mut min_val = f64::INFINITY;
14234 let mut max_val = f64::NEG_INFINITY;
14235 for v in &self.values {
14236 if v.is_missing() {
14237 continue;
14238 }
14239 if let Ok(x) = v.to_f64()
14240 && x.is_finite()
14241 {
14242 min_val = min_val.min(x);
14243 max_val = max_val.max(x);
14244 }
14245 }
14246
14247 if !min_val.is_finite() || !max_val.is_finite() || min_val > max_val {
14248 let counts: Vec<Scalar> = vec![Scalar::Int64(0); n_bins];
14250 let edges = vec![0.0; n_bins + 1];
14251 return Ok((Self::new(DType::Int64, counts)?, edges));
14252 }
14253
14254 let range = max_val - min_val;
14256 let (adj_min, adj_max) = if range == 0.0 {
14257 (min_val - 0.5, max_val + 0.5)
14259 } else {
14260 (min_val, max_val)
14261 };
14262 let adj_range = adj_max - adj_min;
14263 let step = adj_range / n_bins as f64;
14264 let bin_edges: Vec<f64> = (0..=n_bins).map(|i| adj_min + step * i as f64).collect();
14265
14266 let counts = self.histogram(&bin_edges)?;
14267 Ok((counts, bin_edges))
14268 }
14269
14270 pub fn astype(&self, target: DType) -> Result<Self, ColumnError> {
14280 if self.dtype == target {
14281 return Ok(self.clone());
14282 }
14283 if target == DType::Float64
14291 && let Some(data) = self.as_i64_slice()
14292 {
14293 let out: Vec<f64> = data.iter().map(|&x| x as f64).collect();
14294 return Ok(Self::from_f64_values(out));
14295 }
14296 if target == DType::Int64
14297 && let Some(data) = self.as_f64_slice()
14298 && data
14299 .iter()
14300 .all(|&v| v >= i64::MIN as f64 && v < 9_223_372_036_854_775_808.0)
14301 {
14302 let out: Vec<i64> = data.iter().map(|&v| v as i64).collect();
14303 return Ok(Self::from_i64_values(out));
14304 }
14305 if target == DType::Utf8
14313 && let Some(data) = self.as_i64_slice()
14314 {
14315 use std::io::Write as _;
14316 let mut bytes: Vec<u8> = Vec::with_capacity(data.len() * 4);
14317 let mut offsets: Vec<usize> = Vec::with_capacity(data.len() + 1);
14318 offsets.push(0);
14319 for &v in data {
14320 let _ = write!(bytes, "{v}");
14321 offsets.push(bytes.len());
14322 }
14323 return Ok(Self::from_utf8_contiguous(bytes, offsets));
14324 }
14325 if target == DType::Utf8
14330 && let Some(data) = self.as_bool_slice()
14331 {
14332 let mut bytes: Vec<u8> = Vec::with_capacity(data.len() * 5);
14333 let mut offsets: Vec<usize> = Vec::with_capacity(data.len() + 1);
14334 offsets.push(0);
14335 for &b in data {
14336 bytes.extend_from_slice(if b { b"True" } else { b"False" });
14337 offsets.push(bytes.len());
14338 }
14339 return Ok(Self::from_utf8_contiguous(bytes, offsets));
14340 }
14341 if target == DType::Utf8
14351 && let Some(data) = self.as_f64_slice()
14352 {
14353 let mut bytes: Vec<u8> = Vec::with_capacity(data.len() * 6);
14354 let mut offsets: Vec<usize> = Vec::with_capacity(data.len() + 1);
14355 offsets.push(0);
14356 for &v in data {
14357 bytes.extend_from_slice(fp_types::float_to_string_for_astype(v).as_bytes());
14358 offsets.push(bytes.len());
14359 }
14360 return Ok(Self::from_utf8_contiguous(bytes, offsets));
14361 }
14362 let out: Vec<Scalar> = self
14363 .values
14364 .iter()
14365 .map(|v| cast_scalar(v, target))
14366 .collect::<Result<Vec<_>, _>>()
14367 .map_err(ColumnError::Type)?;
14368 Self::new(target, out)
14369 }
14370
14371 pub fn nsmallest_keep(&self, n: usize, keep: &str) -> Result<Self, ColumnError> {
14381 nkeep_impl(self, n, keep, true)
14382 }
14383
14384 pub fn nlargest_keep(&self, n: usize, keep: &str) -> Result<Self, ColumnError> {
14390 nkeep_impl(self, n, keep, false)
14391 }
14392
14393 pub fn nlargest(&self, n: usize) -> Result<Self, ColumnError> {
14401 let sorted = self.sort_values(false)?;
14402 let take = n.min(sorted.values.len());
14403 let values: Vec<Scalar> = sorted.values[..take].to_vec();
14404 Self::new(self.dtype, values)
14405 }
14406
14407 pub fn nsmallest(&self, n: usize) -> Result<Self, ColumnError> {
14411 let sorted = self.sort_values(true)?;
14412 let take = n.min(sorted.values.len());
14413 let values: Vec<Scalar> = sorted.values[..take].to_vec();
14414 Self::new(self.dtype, values)
14415 }
14416
14417 pub fn mask(&self, cond: &Self, other: &Scalar) -> Result<Self, ColumnError> {
14422 if cond.dtype != DType::Bool {
14423 return Err(ColumnError::InvalidMaskType { dtype: cond.dtype });
14424 }
14425 if self.values.len() != cond.values.len() {
14426 return Err(ColumnError::LengthMismatch {
14427 left: self.values.len(),
14428 right: cond.values.len(),
14429 });
14430 }
14431 if !other.is_missing()
14434 && let Some(cb) = cond.as_bool_slice()
14435 {
14436 if let Some(s) = self.as_f64_slice()
14437 && let Ok(o) = other.to_f64()
14438 {
14439 let out: Vec<f64> = (0..s.len()).map(|i| if cb[i] { o } else { s[i] }).collect();
14440 return Ok(Self::from_f64_values(out));
14441 }
14442 if let Some(s) = self.as_i64_slice()
14443 && let Scalar::Int64(o) = other
14444 {
14445 let o = *o;
14446 let out: Vec<i64> = (0..s.len()).map(|i| if cb[i] { o } else { s[i] }).collect();
14447 return Ok(Self::from_i64_values(out));
14448 }
14449 }
14450 let out: Vec<Scalar> = self
14451 .values
14452 .iter()
14453 .zip(cond.values.iter())
14454 .map(|(v, c)| match c {
14455 Scalar::Bool(true) => other.clone(),
14456 Scalar::Bool(false) => v.clone(),
14457 _ => Scalar::Null(NullKind::NaN),
14458 })
14459 .collect();
14460 Self::new(self.dtype, out)
14461 }
14462
14463 fn as_all_valid_str_vec(&self) -> Option<Vec<&str>> {
14478 if self.dtype != DType::Utf8 || !self.validity.all() {
14479 return None;
14480 }
14481 if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
14488 let mut strs = Vec::with_capacity(offsets.len() - 1);
14489 for w in offsets.windows(2) {
14490 strs.push(
14491 std::str::from_utf8(&bytes[w[0]..w[1]])
14492 .expect("contiguous utf8 buffer is valid by construction"),
14493 );
14494 }
14495 return Some(strs);
14496 }
14497 let mut strs = Vec::with_capacity(self.len());
14498 for v in self.values.iter() {
14499 match v {
14500 Scalar::Utf8(s) => strs.push(s.as_str()),
14501 _ => return None,
14502 }
14503 }
14504 Some(strs)
14505 }
14506
14507 fn typed_radix_perm(&self, ascending: bool) -> Option<Vec<usize>> {
14508 if let Some(data) = self.as_i64_slice() {
14509 let keys: Vec<u64> = if ascending {
14510 data.iter().map(|&v| i64_radix_key(v)).collect()
14511 } else {
14512 data.iter().map(|&v| !i64_radix_key(v)).collect()
14513 };
14514 return Some(radix_argsort_u64(&keys));
14515 }
14516 if let Some(data) = self.as_f64_slice() {
14517 let keys: Vec<u64> = if ascending {
14518 data.iter().map(|&v| f64_radix_key(v)).collect()
14519 } else {
14520 data.iter().map(|&v| !f64_radix_key(v)).collect()
14521 };
14522 return Some(radix_argsort_u64(&keys));
14523 }
14524 None
14525 }
14526
14527 #[must_use]
14537 pub fn typed_radix_keys(&self, ascending: bool) -> Option<Vec<u64>> {
14538 if let Some(data) = self.as_i64_slice() {
14539 return Some(if ascending {
14540 data.iter().map(|&v| i64_radix_key(v)).collect()
14541 } else {
14542 data.iter().map(|&v| !i64_radix_key(v)).collect()
14543 });
14544 }
14545 if let Some(data) = self.as_f64_slice() {
14546 if data.iter().any(|x| x.is_nan()) {
14547 return None;
14548 }
14549 return Some(if ascending {
14550 data.iter().map(|&v| f64_radix_key(v)).collect()
14551 } else {
14552 data.iter().map(|&v| !f64_radix_key(v)).collect()
14553 });
14554 }
14555 None
14556 }
14557
14558 pub fn sort_values(&self, ascending: bool) -> Result<Self, ColumnError> {
14559 if let Some(data) = self.as_i64_slice() {
14563 let perm = self
14564 .typed_radix_perm(ascending)
14565 .expect("i64 slice yields perm");
14566 let sorted: Vec<i64> = perm.iter().map(|&i| data[i]).collect();
14567 return Ok(Self::from_i64_values(sorted));
14568 }
14569 if let Some(data) = self.as_f64_slice() {
14570 let perm = self
14571 .typed_radix_perm(ascending)
14572 .expect("f64 slice yields perm");
14573 let sorted: Vec<f64> = perm.iter().map(|&i| data[i]).collect();
14574 return Ok(Self::from_f64_values(sorted));
14575 }
14576 if let Some(strs) = self.as_all_valid_str_vec() {
14581 let perm = utf8_msd_argsort(&strs, ascending);
14582 let sorted: Vec<Scalar> = perm.iter().map(|&i| self.values[i].clone()).collect();
14583 return Self::new(self.dtype, sorted);
14584 }
14585 let mut indexed: Vec<(usize, &Scalar)> = self.values.iter().enumerate().collect();
14586 indexed.sort_by(|a, b| compare_scalars_na_last(a.1, b.1, ascending));
14587 let sorted: Vec<Scalar> = indexed.into_iter().map(|(_, v)| v.clone()).collect();
14588 Self::new(self.dtype, sorted)
14589 }
14590
14591 #[must_use]
14597 pub fn argsort(&self) -> Vec<usize> {
14598 self.argsort_with(true)
14599 }
14600
14601 #[must_use]
14606 pub fn argsort_with(&self, ascending: bool) -> Vec<usize> {
14607 if let Some(perm) = self.typed_radix_perm(ascending) {
14608 return perm;
14609 }
14610 if self.validity.all()
14616 && let Some((bytes, offsets)) = self.as_utf8_contiguous()
14617 {
14618 let spans: Vec<&[u8]> = offsets.windows(2).map(|w| &bytes[w[0]..w[1]]).collect();
14619 return utf8_msd_argsort_bytes(&spans, ascending);
14620 }
14621 if let Some(strs) = self.as_all_valid_str_vec() {
14626 return utf8_msd_argsort(&strs, ascending);
14627 }
14628 let mut indexed: Vec<(usize, &Scalar)> = self.values.iter().enumerate().collect();
14629 indexed.sort_by(|a, b| compare_scalars_na_last(a.1, b.1, ascending));
14630 indexed.into_iter().map(|(i, _)| i).collect()
14631 }
14632
14633 pub fn argpartition(&self, kth: usize) -> Result<Vec<usize>, ColumnError> {
14639 if kth >= self.len() {
14640 return Err(ColumnError::InvalidLength {
14641 operation: "argpartition",
14642 expected: kth + 1,
14643 actual: self.len(),
14644 });
14645 }
14646 let mut indexed: Vec<(usize, &Scalar)> = self.values.iter().enumerate().collect();
14647 indexed.select_nth_unstable_by(kth, |a, b| compare_scalars_na_last(a.1, b.1, true));
14648 Ok(indexed.into_iter().map(|(i, _)| i).collect())
14649 }
14650
14651 pub fn partition(&self, kth: usize) -> Result<Self, ColumnError> {
14656 let indices = self.argpartition(kth)?;
14657 let out: Vec<Scalar> = indices.iter().map(|&i| self.values[i].clone()).collect();
14658 Self::new(self.dtype, out)
14659 }
14660
14661 pub fn diff(&self, periods: i64) -> Result<Self, ColumnError> {
14668 let len = self.values.len();
14669 let out_dtype = match self.dtype {
14677 DType::Timedelta64 => DType::Timedelta64,
14678 DType::Bool => DType::Bool,
14679 _ => DType::Float64,
14680 };
14681 if len == 0 || periods == 0 {
14682 let null = if out_dtype == DType::Timedelta64 {
14683 Scalar::Null(NullKind::NaT)
14684 } else {
14685 Scalar::Null(NullKind::NaN)
14686 };
14687 return Self::new(out_dtype, vec![null; len]);
14688 }
14689 let abs = periods.unsigned_abs() as usize;
14690 let mut out: Vec<Scalar> = Vec::with_capacity(len);
14691 let null_scalar = if out_dtype == DType::Timedelta64 {
14692 Scalar::Null(NullKind::NaT)
14693 } else {
14694 Scalar::Null(NullKind::NaN)
14695 };
14696 for i in 0..len {
14697 if (periods > 0 && i < abs) || (periods < 0 && i + abs >= len) {
14698 out.push(null_scalar.clone());
14699 continue;
14700 }
14701 let (cur, prev) = if periods > 0 {
14702 (&self.values[i], &self.values[i - abs])
14703 } else {
14704 (&self.values[i], &self.values[i + abs])
14705 };
14706 if cur.is_missing() || prev.is_missing() {
14707 out.push(null_scalar.clone());
14708 continue;
14709 }
14710 if let (Scalar::Timedelta64(cur_ns), Scalar::Timedelta64(prev_ns)) = (cur, prev) {
14711 if *cur_ns == Timedelta::NAT || *prev_ns == Timedelta::NAT {
14712 out.push(Scalar::Null(NullKind::NaT));
14713 } else {
14714 out.push(Scalar::Timedelta64(cur_ns.saturating_sub(*prev_ns)));
14715 }
14716 continue;
14717 }
14718 if let (Scalar::Bool(cur_b), Scalar::Bool(prev_b)) = (cur, prev) {
14719 out.push(Scalar::Bool(cur_b != prev_b));
14721 continue;
14722 }
14723 match (cur.to_f64(), prev.to_f64()) {
14724 (Ok(a), Ok(b)) => out.push(Scalar::Float64(a - b)),
14725 _ => out.push(Scalar::Null(NullKind::NaN)),
14726 }
14727 }
14728 Self::new(out_dtype, out)
14729 }
14730
14731 pub fn ediff1d(
14735 &self,
14736 to_begin: Option<Scalar>,
14737 to_end: Option<Scalar>,
14738 ) -> Result<Self, ColumnError> {
14739 let mut out = Vec::new();
14740 if let Some(v) = to_begin {
14741 out.push(v);
14742 }
14743 for i in 1..self.values.len() {
14744 let cur = &self.values[i];
14745 let prev = &self.values[i - 1];
14746 if cur.is_missing() || prev.is_missing() {
14747 out.push(Scalar::Float64(f64::NAN));
14748 continue;
14749 }
14750 let cf = cur.to_f64().map_err(ColumnError::Type)?;
14751 let pf = prev.to_f64().map_err(ColumnError::Type)?;
14752 out.push(Scalar::Float64(cf - pf));
14753 }
14754 if let Some(v) = to_end {
14755 out.push(v);
14756 }
14757 Self::new(DType::Float64, out)
14758 }
14759
14760 pub fn gradient(&self) -> Result<Self, ColumnError> {
14764 let n = self.values.len();
14765 if n == 0 {
14766 return Self::new(DType::Float64, Vec::new());
14767 }
14768 if n == 1 {
14769 return Self::new(DType::Float64, vec![Scalar::Float64(0.0)]);
14770 }
14771 let vals: Vec<f64> = self
14772 .values
14773 .iter()
14774 .map(|v| v.to_f64().unwrap_or(f64::NAN))
14775 .collect();
14776 let mut out = Vec::with_capacity(n);
14777 out.push(Scalar::Float64(vals[1] - vals[0]));
14778 for i in 1..n - 1 {
14779 out.push(Scalar::Float64((vals[i + 1] - vals[i - 1]) / 2.0));
14780 }
14781 out.push(Scalar::Float64(vals[n - 1] - vals[n - 2]));
14782 Self::new(DType::Float64, out)
14783 }
14784
14785 pub fn trapz(&self, dx: f64) -> Result<Scalar, ColumnError> {
14789 let n = self.values.len();
14790 if n < 2 {
14791 return Ok(Scalar::Float64(0.0));
14792 }
14793 let vals: Vec<f64> = self
14794 .values
14795 .iter()
14796 .map(|v| v.to_f64().unwrap_or(0.0))
14797 .collect();
14798 let mut sum = 0.0;
14799 for i in 1..n {
14800 sum += (vals[i - 1] + vals[i]) / 2.0 * dx;
14801 }
14802 Ok(Scalar::Float64(sum))
14803 }
14804
14805 pub fn duplicated(&self) -> Result<Self, ColumnError> {
14811 self.duplicated_keep("first")
14812 }
14813
14814 pub fn duplicated_keep(&self, keep: &str) -> Result<Self, ColumnError> {
14820 #[derive(Hash, PartialEq, Eq)]
14821 enum Key<'a> {
14822 Null,
14823 Bool(bool),
14824 Int64(i64),
14825 FloatBits(u64),
14826 Utf8(&'a str),
14827 Timedelta64(i64),
14828 Datetime64(i64),
14829 Period(i64),
14830 Interval(u64, u64, IntervalClosed),
14831 }
14832 fn key_of(v: &Scalar) -> Key<'_> {
14833 if v.is_missing() {
14834 return Key::Null;
14835 }
14836 match v {
14837 Scalar::Bool(b) => Key::Bool(*b),
14838 Scalar::Int64(i) => Key::Int64(*i),
14839 Scalar::Float64(f) => {
14840 let norm = if *f == 0.0 { 0.0 } else { *f };
14841 Key::FloatBits(norm.to_bits())
14842 }
14843 Scalar::Utf8(s) => Key::Utf8(s.as_str()),
14844 Scalar::Timedelta64(v) => Key::Timedelta64(*v),
14845 Scalar::Datetime64(v) => Key::Datetime64(*v),
14846 Scalar::Period(p) => Key::Period(p.ordinal),
14847 Scalar::Interval(v) => {
14848 let (left, right, closed) = interval_key(v);
14849 Key::Interval(left, right, closed)
14850 }
14851 Scalar::Null(_) => Key::Null,
14852 }
14853 }
14854
14855 let policy = match keep {
14856 "first" => DupPolicy::First,
14857 "last" => DupPolicy::Last,
14858 "false" | "False" | "none" => DupPolicy::None,
14859 other => {
14860 return Err(ColumnError::Type(TypeError::NonNumericValue {
14861 value: other.to_string(),
14862 dtype: self.dtype,
14863 }));
14864 }
14865 };
14866
14867 if let Some(data) = self.as_i64_slice() {
14873 if let Some((min, range)) = i64_direct_address_range(data) {
14876 return Ok(Self::from_bool_values(duplicated_flags_i64_direct(
14877 data, min, range, policy,
14878 )));
14879 }
14880 return Ok(Self::from_bool_values(duplicated_flags_typed(data, policy)));
14881 }
14882 if let Some(data) = self.as_f64_slice() {
14883 let keys: Vec<u64> = data
14884 .iter()
14885 .map(|&f| (if f == 0.0 { 0.0 } else { f }).to_bits())
14886 .collect();
14887 return Ok(Self::from_bool_values(duplicated_flags_typed(
14888 &keys, policy,
14889 )));
14890 }
14891
14892 let mut flags = vec![false; self.values.len()];
14893 match policy {
14894 DupPolicy::First => {
14895 let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
14896 for (idx, value) in self.values.iter().enumerate() {
14897 flags[idx] = !seen.insert(key_of(value));
14898 }
14899 }
14900 DupPolicy::Last => {
14901 let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
14902 for (idx, value) in self.values.iter().enumerate().rev() {
14903 flags[idx] = !seen.insert(key_of(value));
14904 }
14905 }
14906 DupPolicy::None => {
14907 let mut seen_once: FxHashSet<Key<'_>> = FxHashSet::default();
14908 let mut seen_multiple: FxHashSet<Key<'_>> = FxHashSet::default();
14909 for value in &self.values {
14910 let key = key_of(value);
14911 if !seen_once.insert(key_of(value)) {
14912 seen_multiple.insert(key);
14913 }
14914 }
14915 for (idx, value) in self.values.iter().enumerate() {
14916 flags[idx] = seen_multiple.contains(&key_of(value));
14917 }
14918 }
14919 }
14920
14921 let out: Vec<Scalar> = flags.into_iter().map(Scalar::Bool).collect();
14922 Self::new(DType::Bool, out)
14923 }
14924
14925 pub fn between(&self, lower: f64, upper: f64, inclusive: bool) -> Result<Self, ColumnError> {
14932 let policy = if inclusive { "both" } else { "neither" };
14933 self.between_inclusive(lower, upper, policy)
14934 }
14935
14936 pub fn between_inclusive(
14942 &self,
14943 lower: f64,
14944 upper: f64,
14945 inclusive: &str,
14946 ) -> Result<Self, ColumnError> {
14947 let (include_left, include_right) = match inclusive {
14948 "both" => (true, true),
14949 "left" => (true, false),
14950 "right" => (false, true),
14951 "neither" => (false, false),
14952 other => {
14953 return Err(ColumnError::Type(TypeError::NonNumericValue {
14954 value: other.to_string(),
14955 dtype: self.dtype,
14956 }));
14957 }
14958 };
14959
14960 let mut out = Vec::with_capacity(self.values.len());
14961 for v in &self.values {
14962 if v.is_missing() {
14963 out.push(Scalar::Bool(false));
14964 continue;
14965 }
14966 match v.to_f64() {
14967 Ok(x) => {
14968 let lower_ok = if include_left { x >= lower } else { x > lower };
14969 let upper_ok = if include_right { x <= upper } else { x < upper };
14970 out.push(Scalar::Bool(lower_ok && upper_ok));
14971 }
14972 Err(err) => return Err(ColumnError::Type(err)),
14973 }
14974 }
14975 Self::new(DType::Bool, out)
14976 }
14977
14978 pub fn factorize(&self) -> Result<(Self, Self), ColumnError> {
14983 self.factorize_with_options(false, true)
14984 }
14985
14986 pub fn factorize_with_options(
14993 &self,
14994 sort: bool,
14995 use_na_sentinel: bool,
14996 ) -> Result<(Self, Self), ColumnError> {
14997 if !sort
14998 && use_na_sentinel
14999 && let Some(cached) = self.utf8_default_factorize_columns()
15000 {
15001 return Ok(cached);
15002 }
15003
15004 #[derive(Hash, PartialEq, Eq, Clone, Copy)]
15012 enum LocalKey<'a> {
15013 Bool(bool),
15014 Int64(i64),
15015 FloatBits(u64),
15016 Utf8(&'a str),
15017 Timedelta64(i64),
15018 Datetime64(i64),
15019 Period(i64),
15020 Interval(u64, u64, IntervalClosed),
15021 }
15022 fn key_of(s: &Scalar) -> Option<LocalKey<'_>> {
15023 match s {
15024 Scalar::Null(_) => None,
15025 Scalar::Bool(b) => Some(LocalKey::Bool(*b)),
15026 Scalar::Int64(i) => Some(LocalKey::Int64(*i)),
15027 Scalar::Float64(f) => {
15028 if f.is_nan() {
15029 None
15030 } else {
15031 let normalized = if *f == 0.0 { 0.0 } else { *f };
15032 Some(LocalKey::FloatBits(normalized.to_bits()))
15033 }
15034 }
15035 Scalar::Utf8(s) => Some(LocalKey::Utf8(s.as_str())),
15036 Scalar::Timedelta64(t) => {
15037 if *t == Timedelta::NAT {
15038 None
15039 } else {
15040 Some(LocalKey::Timedelta64(*t))
15041 }
15042 }
15043 Scalar::Datetime64(t) => {
15044 if *t == Timestamp::NAT {
15045 None
15046 } else {
15047 Some(LocalKey::Datetime64(*t))
15048 }
15049 }
15050 Scalar::Period(p) => {
15051 if p.ordinal == i64::MIN {
15052 None
15053 } else {
15054 Some(LocalKey::Period(p.ordinal))
15055 }
15056 }
15057 Scalar::Interval(interval) => {
15058 let (left, right, closed) = interval_key(interval);
15059 Some(LocalKey::Interval(left, right, closed))
15060 }
15061 }
15062 }
15063
15064 let (mut codes, mut uniques): (Vec<Scalar>, Vec<Scalar>) = if let Some((data, min, range)) =
15065 self.as_i64_slice()
15066 .and_then(|d| i64_direct_address_range(d).map(|(m, r)| (d, m, r)))
15067 {
15068 let mut code_table = vec![-1i64; range];
15074 let mut uniques: Vec<Scalar> = Vec::new();
15075 let mut codes: Vec<Scalar> = Vec::with_capacity(data.len());
15076 for &v in data {
15077 let slot = (v as i128 - min as i128) as usize;
15078 let existing = code_table[slot];
15079 if existing < 0 {
15080 let code = uniques.len() as i64;
15081 code_table[slot] = code;
15082 uniques.push(Scalar::Int64(v));
15083 codes.push(Scalar::Int64(code));
15084 } else {
15085 codes.push(Scalar::Int64(existing));
15086 }
15087 }
15088 (codes, uniques)
15089 } else {
15090 let mut uniques: Vec<Scalar> = Vec::new();
15091 let mut idx_map: FxHashMap<LocalKey<'_>, i64> = FxHashMap::default();
15092 let mut missing_position: Option<i64> = None;
15093 let mut codes: Vec<Scalar> = Vec::with_capacity(self.values.len());
15094
15095 for value in &self.values {
15096 if value.is_missing() {
15097 if use_na_sentinel {
15098 codes.push(Scalar::Int64(-1));
15099 } else if let Some(p) = missing_position {
15100 codes.push(Scalar::Int64(p));
15101 } else {
15102 let code = uniques.len() as i64;
15103 missing_position = Some(code);
15104 uniques.push(value.clone());
15105 codes.push(Scalar::Int64(code));
15106 }
15107 continue;
15108 }
15109 let Some(key) = key_of(value) else {
15110 codes.push(Scalar::Int64(-1));
15113 continue;
15114 };
15115 match idx_map.get(&key) {
15116 Some(&p) => codes.push(Scalar::Int64(p)),
15117 None => {
15118 let code = uniques.len() as i64;
15119 idx_map.insert(key, code);
15120 uniques.push(value.clone());
15121 codes.push(Scalar::Int64(code));
15122 }
15123 }
15124 }
15125 drop(idx_map);
15126 (codes, uniques)
15127 };
15128
15129 if sort && !uniques.is_empty() {
15130 let mut ordering: Vec<usize> = (0..uniques.len()).collect();
15131 ordering.sort_by(|left, right| {
15132 compare_scalars_na_last(&uniques[*left], &uniques[*right], true)
15133 });
15134
15135 let mut remap = vec![0usize; uniques.len()];
15136 let sorted_uniques: Vec<Scalar> = ordering
15137 .into_iter()
15138 .enumerate()
15139 .map(|(sorted_position, original_position)| {
15140 remap[original_position] = sorted_position;
15141 uniques[original_position].clone()
15142 })
15143 .collect();
15144
15145 for code in &mut codes {
15146 if let Scalar::Int64(value) = code
15147 && *value >= 0
15148 {
15149 *value = remap[*value as usize] as i64;
15150 }
15151 }
15152
15153 uniques = sorted_uniques;
15154 }
15155
15156 let codes_col = Self::new(DType::Int64, codes)?;
15157 let uniques_col = Self::new(self.dtype, uniques)?;
15158 Ok((codes_col, uniques_col))
15159 }
15160
15161 pub fn abs(&self) -> Result<Self, ColumnError> {
15167 if let Some(data) = self.as_i64_slice() {
15173 return Ok(Self::from_i64_values(
15174 data.iter().map(|&x| x.wrapping_abs()).collect(),
15175 ));
15176 }
15177 if let Some(data) = self.as_f64_slice() {
15178 let witness = self.f64_finite_witness();
15189 let out: Vec<f64> = data.iter().map(|&x| x.abs()).collect();
15190 return Ok(Self::from_f64_all_valid_with_finite_opt(out, witness));
15191 }
15192
15193 let mut out = Vec::with_capacity(self.values.len());
15194 for v in &self.values {
15195 if v.is_missing() {
15196 out.push(v.clone());
15197 continue;
15198 }
15199 match v {
15200 Scalar::Bool(x) => out.push(Scalar::Bool(*x)),
15201 Scalar::Int64(x) => out.push(Scalar::Int64(x.wrapping_abs())),
15202 Scalar::Float64(x) => out.push(Scalar::Float64(x.abs())),
15203 Scalar::Timedelta64(x) if *x != Timedelta::NAT => {
15204 out.push(Scalar::Timedelta64(x.wrapping_abs()))
15205 }
15206 _ => {
15207 return Err(ColumnError::Type(TypeError::NonNumericValue {
15208 value: format!("{v:?}"),
15209 dtype: self.dtype,
15210 }));
15211 }
15212 }
15213 }
15214 Self::new(self.dtype, out)
15215 }
15216
15217 pub fn fabs(&self) -> Result<Self, ColumnError> {
15219 self.abs()
15220 }
15221
15222 pub fn absolute(&self) -> Result<Self, ColumnError> {
15224 self.abs()
15225 }
15226
15227 pub fn neg(&self) -> Result<Self, ColumnError> {
15229 if let Some(data) = self.as_i64_slice() {
15233 return Ok(Self::from_i64_values(
15234 data.iter().map(|&x| x.wrapping_neg()).collect(),
15235 ));
15236 }
15237 if let Some(data) = self.as_f64_slice() {
15238 let witness = self.f64_finite_witness();
15243 let out: Vec<f64> = data.iter().map(|&x| -x).collect();
15244 return Ok(Self::from_f64_all_valid_with_finite_opt(out, witness));
15245 }
15246 let mut out = Vec::with_capacity(self.values.len());
15247 for v in &self.values {
15248 if v.is_missing() {
15249 out.push(v.clone());
15250 continue;
15251 }
15252 match v {
15253 Scalar::Int64(x) => out.push(Scalar::Int64(x.wrapping_neg())),
15254 Scalar::Float64(x) => out.push(Scalar::Float64(-x)),
15255 Scalar::Timedelta64(x) if *x != Timedelta::NAT => {
15256 out.push(Scalar::Timedelta64(x.wrapping_neg()))
15257 }
15258 _ => {
15259 return Err(ColumnError::Type(TypeError::NonNumericValue {
15260 value: format!("{v:?}"),
15261 dtype: self.dtype,
15262 }));
15263 }
15264 }
15265 }
15266 Self::new(self.dtype, out)
15267 }
15268
15269 pub fn positive(&self) -> Result<Self, ColumnError> {
15271 for v in &self.values {
15272 if v.is_missing() {
15273 continue;
15274 }
15275 match v {
15276 Scalar::Int64(_) | Scalar::Float64(_) | Scalar::Timedelta64(_) => {}
15277 _ => {
15278 return Err(ColumnError::Type(TypeError::NonNumericValue {
15279 value: format!("{v:?}"),
15280 dtype: self.dtype,
15281 }));
15282 }
15283 }
15284 }
15285 Ok(self.clone())
15286 }
15287
15288 pub fn negative(&self) -> Result<Self, ColumnError> {
15290 self.neg()
15291 }
15292
15293 pub fn sqrt(&self) -> Result<Self, ColumnError> {
15295 if let Some(out) = self.typed_float_unary(f64::sqrt) {
15296 return Ok(out);
15297 }
15298 let mut out = Vec::with_capacity(self.values.len());
15299 for v in &self.values {
15300 if v.is_missing() {
15301 out.push(Scalar::Float64(f64::NAN));
15302 continue;
15303 }
15304 match v {
15305 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).sqrt())),
15306 Scalar::Float64(x) => out.push(Scalar::Float64(x.sqrt())),
15307 _ => {
15308 return Err(ColumnError::Type(TypeError::NonNumericValue {
15309 value: format!("{v:?}"),
15310 dtype: self.dtype,
15311 }));
15312 }
15313 }
15314 }
15315 Self::new(DType::Float64, out)
15316 }
15317
15318 pub fn exp(&self) -> Result<Self, ColumnError> {
15320 if let Some(out) = self.typed_float_unary(f64::exp) {
15321 return Ok(out);
15322 }
15323 let mut out = Vec::with_capacity(self.values.len());
15324 for v in &self.values {
15325 if v.is_missing() {
15326 out.push(Scalar::Float64(f64::NAN));
15327 continue;
15328 }
15329 match v {
15330 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).exp())),
15331 Scalar::Float64(x) => out.push(Scalar::Float64(x.exp())),
15332 _ => {
15333 return Err(ColumnError::Type(TypeError::NonNumericValue {
15334 value: format!("{v:?}"),
15335 dtype: self.dtype,
15336 }));
15337 }
15338 }
15339 }
15340 Self::new(DType::Float64, out)
15341 }
15342
15343 pub fn log(&self) -> Result<Self, ColumnError> {
15345 if let Some(out) = self.typed_float_unary(f64::ln) {
15346 return Ok(out);
15347 }
15348 let mut out = Vec::with_capacity(self.values.len());
15349 for v in &self.values {
15350 if v.is_missing() {
15351 out.push(Scalar::Float64(f64::NAN));
15352 continue;
15353 }
15354 match v {
15355 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).ln())),
15356 Scalar::Float64(x) => out.push(Scalar::Float64(x.ln())),
15357 _ => {
15358 return Err(ColumnError::Type(TypeError::NonNumericValue {
15359 value: format!("{v:?}"),
15360 dtype: self.dtype,
15361 }));
15362 }
15363 }
15364 }
15365 Self::new(DType::Float64, out)
15366 }
15367
15368 pub fn log10(&self) -> Result<Self, ColumnError> {
15370 if let Some(out) = self.typed_float_unary(f64::log10) {
15371 return Ok(out);
15372 }
15373 let mut out = Vec::with_capacity(self.values.len());
15374 for v in &self.values {
15375 if v.is_missing() {
15376 out.push(Scalar::Float64(f64::NAN));
15377 continue;
15378 }
15379 match v {
15380 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).log10())),
15381 Scalar::Float64(x) => out.push(Scalar::Float64(x.log10())),
15382 _ => {
15383 return Err(ColumnError::Type(TypeError::NonNumericValue {
15384 value: format!("{v:?}"),
15385 dtype: self.dtype,
15386 }));
15387 }
15388 }
15389 }
15390 Self::new(DType::Float64, out)
15391 }
15392
15393 pub fn log2(&self) -> Result<Self, ColumnError> {
15395 if let Some(out) = self.typed_float_unary(f64::log2) {
15396 return Ok(out);
15397 }
15398 let mut out = Vec::with_capacity(self.values.len());
15399 for v in &self.values {
15400 if v.is_missing() {
15401 out.push(Scalar::Float64(f64::NAN));
15402 continue;
15403 }
15404 match v {
15405 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).log2())),
15406 Scalar::Float64(x) => out.push(Scalar::Float64(x.log2())),
15407 _ => {
15408 return Err(ColumnError::Type(TypeError::NonNumericValue {
15409 value: format!("{v:?}"),
15410 dtype: self.dtype,
15411 }));
15412 }
15413 }
15414 }
15415 Self::new(DType::Float64, out)
15416 }
15417
15418 pub fn sin(&self) -> Result<Self, ColumnError> {
15420 if let Some(out) = self.typed_float_unary(f64::sin) {
15421 return Ok(out);
15422 }
15423 let mut out = Vec::with_capacity(self.values.len());
15424 for v in &self.values {
15425 if v.is_missing() {
15426 out.push(Scalar::Float64(f64::NAN));
15427 continue;
15428 }
15429 match v {
15430 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).sin())),
15431 Scalar::Float64(x) => out.push(Scalar::Float64(x.sin())),
15432 _ => {
15433 return Err(ColumnError::Type(TypeError::NonNumericValue {
15434 value: format!("{v:?}"),
15435 dtype: self.dtype,
15436 }));
15437 }
15438 }
15439 }
15440 Self::new(DType::Float64, out)
15441 }
15442
15443 pub fn cos(&self) -> Result<Self, ColumnError> {
15445 if let Some(out) = self.typed_float_unary(f64::cos) {
15446 return Ok(out);
15447 }
15448 let mut out = Vec::with_capacity(self.values.len());
15449 for v in &self.values {
15450 if v.is_missing() {
15451 out.push(Scalar::Float64(f64::NAN));
15452 continue;
15453 }
15454 match v {
15455 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).cos())),
15456 Scalar::Float64(x) => out.push(Scalar::Float64(x.cos())),
15457 _ => {
15458 return Err(ColumnError::Type(TypeError::NonNumericValue {
15459 value: format!("{v:?}"),
15460 dtype: self.dtype,
15461 }));
15462 }
15463 }
15464 }
15465 Self::new(DType::Float64, out)
15466 }
15467
15468 pub fn tan(&self) -> Result<Self, ColumnError> {
15470 if let Some(out) = self.typed_float_unary(f64::tan) {
15471 return Ok(out);
15472 }
15473 let mut out = Vec::with_capacity(self.values.len());
15474 for v in &self.values {
15475 if v.is_missing() {
15476 out.push(Scalar::Float64(f64::NAN));
15477 continue;
15478 }
15479 match v {
15480 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).tan())),
15481 Scalar::Float64(x) => out.push(Scalar::Float64(x.tan())),
15482 _ => {
15483 return Err(ColumnError::Type(TypeError::NonNumericValue {
15484 value: format!("{v:?}"),
15485 dtype: self.dtype,
15486 }));
15487 }
15488 }
15489 }
15490 Self::new(DType::Float64, out)
15491 }
15492
15493 pub fn asin(&self) -> Result<Self, ColumnError> {
15495 if let Some(out) = self.typed_float_unary(f64::asin) {
15496 return Ok(out);
15497 }
15498 let mut out = Vec::with_capacity(self.values.len());
15499 for v in &self.values {
15500 if v.is_missing() {
15501 out.push(Scalar::Float64(f64::NAN));
15502 continue;
15503 }
15504 match v {
15505 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).asin())),
15506 Scalar::Float64(x) => out.push(Scalar::Float64(x.asin())),
15507 _ => {
15508 return Err(ColumnError::Type(TypeError::NonNumericValue {
15509 value: format!("{v:?}"),
15510 dtype: self.dtype,
15511 }));
15512 }
15513 }
15514 }
15515 Self::new(DType::Float64, out)
15516 }
15517
15518 pub fn acos(&self) -> Result<Self, ColumnError> {
15520 if let Some(out) = self.typed_float_unary(f64::acos) {
15521 return Ok(out);
15522 }
15523 let mut out = Vec::with_capacity(self.values.len());
15524 for v in &self.values {
15525 if v.is_missing() {
15526 out.push(Scalar::Float64(f64::NAN));
15527 continue;
15528 }
15529 match v {
15530 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).acos())),
15531 Scalar::Float64(x) => out.push(Scalar::Float64(x.acos())),
15532 _ => {
15533 return Err(ColumnError::Type(TypeError::NonNumericValue {
15534 value: format!("{v:?}"),
15535 dtype: self.dtype,
15536 }));
15537 }
15538 }
15539 }
15540 Self::new(DType::Float64, out)
15541 }
15542
15543 pub fn atan(&self) -> Result<Self, ColumnError> {
15545 if let Some(out) = self.typed_float_unary(f64::atan) {
15546 return Ok(out);
15547 }
15548 let mut out = Vec::with_capacity(self.values.len());
15549 for v in &self.values {
15550 if v.is_missing() {
15551 out.push(Scalar::Float64(f64::NAN));
15552 continue;
15553 }
15554 match v {
15555 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).atan())),
15556 Scalar::Float64(x) => out.push(Scalar::Float64(x.atan())),
15557 _ => {
15558 return Err(ColumnError::Type(TypeError::NonNumericValue {
15559 value: format!("{v:?}"),
15560 dtype: self.dtype,
15561 }));
15562 }
15563 }
15564 }
15565 Self::new(DType::Float64, out)
15566 }
15567
15568 pub fn sinh(&self) -> Result<Self, ColumnError> {
15570 if let Some(out) = self.typed_float_unary(f64::sinh) {
15571 return Ok(out);
15572 }
15573 let mut out = Vec::with_capacity(self.values.len());
15574 for v in &self.values {
15575 if v.is_missing() {
15576 out.push(Scalar::Float64(f64::NAN));
15577 continue;
15578 }
15579 match v {
15580 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).sinh())),
15581 Scalar::Float64(x) => out.push(Scalar::Float64(x.sinh())),
15582 _ => {
15583 return Err(ColumnError::Type(TypeError::NonNumericValue {
15584 value: format!("{v:?}"),
15585 dtype: self.dtype,
15586 }));
15587 }
15588 }
15589 }
15590 Self::new(DType::Float64, out)
15591 }
15592
15593 pub fn cosh(&self) -> Result<Self, ColumnError> {
15595 if let Some(out) = self.typed_float_unary(f64::cosh) {
15596 return Ok(out);
15597 }
15598 let mut out = Vec::with_capacity(self.values.len());
15599 for v in &self.values {
15600 if v.is_missing() {
15601 out.push(Scalar::Float64(f64::NAN));
15602 continue;
15603 }
15604 match v {
15605 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).cosh())),
15606 Scalar::Float64(x) => out.push(Scalar::Float64(x.cosh())),
15607 _ => {
15608 return Err(ColumnError::Type(TypeError::NonNumericValue {
15609 value: format!("{v:?}"),
15610 dtype: self.dtype,
15611 }));
15612 }
15613 }
15614 }
15615 Self::new(DType::Float64, out)
15616 }
15617
15618 pub fn tanh(&self) -> Result<Self, ColumnError> {
15620 if let Some(out) = self.typed_float_unary(f64::tanh) {
15621 return Ok(out);
15622 }
15623 let mut out = Vec::with_capacity(self.values.len());
15624 for v in &self.values {
15625 if v.is_missing() {
15626 out.push(Scalar::Float64(f64::NAN));
15627 continue;
15628 }
15629 match v {
15630 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).tanh())),
15631 Scalar::Float64(x) => out.push(Scalar::Float64(x.tanh())),
15632 _ => {
15633 return Err(ColumnError::Type(TypeError::NonNumericValue {
15634 value: format!("{v:?}"),
15635 dtype: self.dtype,
15636 }));
15637 }
15638 }
15639 }
15640 Self::new(DType::Float64, out)
15641 }
15642
15643 pub fn asinh(&self) -> Result<Self, ColumnError> {
15645 if let Some(out) = self.typed_float_unary(f64::asinh) {
15646 return Ok(out);
15647 }
15648 let mut out = Vec::with_capacity(self.values.len());
15649 for v in &self.values {
15650 if v.is_missing() {
15651 out.push(Scalar::Float64(f64::NAN));
15652 continue;
15653 }
15654 match v {
15655 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).asinh())),
15656 Scalar::Float64(x) => out.push(Scalar::Float64(x.asinh())),
15657 _ => {
15658 return Err(ColumnError::Type(TypeError::NonNumericValue {
15659 value: format!("{v:?}"),
15660 dtype: self.dtype,
15661 }));
15662 }
15663 }
15664 }
15665 Self::new(DType::Float64, out)
15666 }
15667
15668 pub fn acosh(&self) -> Result<Self, ColumnError> {
15670 if let Some(out) = self.typed_float_unary(f64::acosh) {
15671 return Ok(out);
15672 }
15673 let mut out = Vec::with_capacity(self.values.len());
15674 for v in &self.values {
15675 if v.is_missing() {
15676 out.push(Scalar::Float64(f64::NAN));
15677 continue;
15678 }
15679 match v {
15680 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).acosh())),
15681 Scalar::Float64(x) => out.push(Scalar::Float64(x.acosh())),
15682 _ => {
15683 return Err(ColumnError::Type(TypeError::NonNumericValue {
15684 value: format!("{v:?}"),
15685 dtype: self.dtype,
15686 }));
15687 }
15688 }
15689 }
15690 Self::new(DType::Float64, out)
15691 }
15692
15693 pub fn atanh(&self) -> Result<Self, ColumnError> {
15695 if let Some(out) = self.typed_float_unary(f64::atanh) {
15696 return Ok(out);
15697 }
15698 let mut out = Vec::with_capacity(self.values.len());
15699 for v in &self.values {
15700 if v.is_missing() {
15701 out.push(Scalar::Float64(f64::NAN));
15702 continue;
15703 }
15704 match v {
15705 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).atanh())),
15706 Scalar::Float64(x) => out.push(Scalar::Float64(x.atanh())),
15707 _ => {
15708 return Err(ColumnError::Type(TypeError::NonNumericValue {
15709 value: format!("{v:?}"),
15710 dtype: self.dtype,
15711 }));
15712 }
15713 }
15714 }
15715 Self::new(DType::Float64, out)
15716 }
15717
15718 pub fn arcsin(&self) -> Result<Self, ColumnError> {
15722 self.asin()
15723 }
15724
15725 pub fn arccos(&self) -> Result<Self, ColumnError> {
15729 self.acos()
15730 }
15731
15732 pub fn arctan(&self) -> Result<Self, ColumnError> {
15736 self.atan()
15737 }
15738
15739 pub fn arctan2(&self, other: &Self) -> Result<Self, ColumnError> {
15743 self.atan2(other)
15744 }
15745
15746 pub fn arcsinh(&self) -> Result<Self, ColumnError> {
15750 self.asinh()
15751 }
15752
15753 pub fn arccosh(&self) -> Result<Self, ColumnError> {
15757 self.acosh()
15758 }
15759
15760 pub fn arctanh(&self) -> Result<Self, ColumnError> {
15764 self.atanh()
15765 }
15766
15767 fn typed_float_unary(&self, f: fn(f64) -> f64) -> Option<Self> {
15778 if let Some(data) = self.as_f64_slice() {
15779 return Some(Self::from_f64_values(data.iter().map(|&x| f(x)).collect()));
15780 }
15781 if let Some(data) = self.as_i64_slice() {
15782 return Some(Self::from_f64_values(
15783 data.iter().map(|&x| f(x as f64)).collect(),
15784 ));
15785 }
15786 None
15787 }
15788
15789 fn typed_float_unary_finite_preserving<F: Fn(f64) -> f64>(&self, f: F) -> Option<Self> {
15801 if let Some(data) = self.as_f64_slice() {
15802 let witness = self.f64_finite_witness();
15803 let out: Vec<f64> = data.iter().map(|&x| f(x)).collect();
15804 return Some(Self::from_f64_all_valid_with_finite_opt(out, witness));
15805 }
15806 if let Some(data) = self.as_i64_slice() {
15807 let out: Vec<f64> = data.iter().map(|&x| f(x as f64)).collect();
15808 return Some(Self::from_f64_all_valid_with_finite_opt(out, Some(true)));
15810 }
15811 None
15812 }
15813
15814 fn all_valid_as_f64(&self) -> Option<Vec<f64>> {
15818 if let Some(s) = self.as_f64_slice() {
15819 return Some(s.to_vec());
15820 }
15821 if let Some(s) = self.as_i64_slice() {
15822 return Some(s.iter().map(|&x| x as f64).collect());
15823 }
15824 None
15825 }
15826
15827 fn typed_float_binary(&self, other: &Self, f: fn(f64, f64) -> f64) -> Option<Self> {
15835 let a = self.all_valid_as_f64()?;
15836 let b = other.all_valid_as_f64()?;
15837 Some(Self::from_f64_values(
15838 a.iter().zip(b.iter()).map(|(&x, &y)| f(x, y)).collect(),
15839 ))
15840 }
15841
15842 pub fn floor(&self) -> Result<Self, ColumnError> {
15843 if let Some(out) = self.typed_float_unary_finite_preserving(f64::floor) {
15844 return Ok(out);
15845 }
15846 let mut out = Vec::with_capacity(self.values.len());
15847 for v in &self.values {
15848 if v.is_missing() {
15849 out.push(Scalar::Float64(f64::NAN));
15850 continue;
15851 }
15852 match v {
15853 Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
15854 Scalar::Float64(x) => out.push(Scalar::Float64(x.floor())),
15855 _ => {
15856 return Err(ColumnError::Type(TypeError::NonNumericValue {
15857 value: format!("{v:?}"),
15858 dtype: self.dtype,
15859 }));
15860 }
15861 }
15862 }
15863 Self::new(DType::Float64, out)
15864 }
15865
15866 pub fn ceil(&self) -> Result<Self, ColumnError> {
15868 if let Some(out) = self.typed_float_unary_finite_preserving(f64::ceil) {
15869 return Ok(out);
15870 }
15871 let mut out = Vec::with_capacity(self.values.len());
15872 for v in &self.values {
15873 if v.is_missing() {
15874 out.push(Scalar::Float64(f64::NAN));
15875 continue;
15876 }
15877 match v {
15878 Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
15879 Scalar::Float64(x) => out.push(Scalar::Float64(x.ceil())),
15880 _ => {
15881 return Err(ColumnError::Type(TypeError::NonNumericValue {
15882 value: format!("{v:?}"),
15883 dtype: self.dtype,
15884 }));
15885 }
15886 }
15887 }
15888 Self::new(DType::Float64, out)
15889 }
15890
15891 pub fn trunc(&self) -> Result<Self, ColumnError> {
15893 if let Some(out) = self.typed_float_unary_finite_preserving(f64::trunc) {
15894 return Ok(out);
15895 }
15896 let mut out = Vec::with_capacity(self.values.len());
15897 for v in &self.values {
15898 if v.is_missing() {
15899 out.push(Scalar::Float64(f64::NAN));
15900 continue;
15901 }
15902 match v {
15903 Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
15904 Scalar::Float64(x) => out.push(Scalar::Float64(x.trunc())),
15905 _ => {
15906 return Err(ColumnError::Type(TypeError::NonNumericValue {
15907 value: format!("{v:?}"),
15908 dtype: self.dtype,
15909 }));
15910 }
15911 }
15912 }
15913 Self::new(DType::Float64, out)
15914 }
15915
15916 pub fn nan_to_num(&self) -> Result<Self, ColumnError> {
15921 self.nan_to_num_with_values(0.0, f64::MAX, f64::MIN)
15922 }
15923
15924 pub fn nan_to_num_with_values(
15928 &self,
15929 nan: f64,
15930 posinf: f64,
15931 neginf: f64,
15932 ) -> Result<Self, ColumnError> {
15933 if let Some(data) = self.as_f64_slice() {
15939 return Ok(Self::from_f64_values(
15940 data.iter()
15941 .map(|&x| {
15942 if x == f64::INFINITY {
15943 posinf
15944 } else if x == f64::NEG_INFINITY {
15945 neginf
15946 } else {
15947 x
15948 }
15949 })
15950 .collect(),
15951 ));
15952 }
15953 if let Some(data) = self.as_i64_slice() {
15954 return Ok(Self::from_f64_values(
15955 data.iter().map(|&x| x as f64).collect(),
15956 ));
15957 }
15958 let mut out = Vec::with_capacity(self.values.len());
15959 for v in &self.values {
15960 let result = match v {
15961 Scalar::Float64(x) => {
15962 if x.is_nan() {
15963 nan
15964 } else if *x == f64::INFINITY {
15965 posinf
15966 } else if *x == f64::NEG_INFINITY {
15967 neginf
15968 } else {
15969 *x
15970 }
15971 }
15972 Scalar::Int64(x) => *x as f64,
15973 Scalar::Null(_) => nan,
15974 _ => {
15975 return Err(ColumnError::Type(TypeError::NonNumericValue {
15976 value: format!("{v:?}"),
15977 dtype: self.dtype,
15978 }));
15979 }
15980 };
15981 out.push(Scalar::Float64(result));
15982 }
15983 Self::new(DType::Float64, out)
15984 }
15985
15986 pub fn rint(&self) -> Result<Self, ColumnError> {
15991 if let Some(out) = self.typed_float_unary(f64::round_ties_even) {
15994 return Ok(out);
15995 }
15996 let mut out = Vec::with_capacity(self.values.len());
15997 for v in &self.values {
15998 if v.is_missing() {
15999 out.push(Scalar::Float64(f64::NAN));
16000 continue;
16001 }
16002 match v {
16003 Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
16004 Scalar::Float64(x) => out.push(Scalar::Float64(x.round_ties_even())),
16005 _ => {
16006 return Err(ColumnError::Type(TypeError::NonNumericValue {
16007 value: format!("{v:?}"),
16008 dtype: self.dtype,
16009 }));
16010 }
16011 }
16012 }
16013 Self::new(DType::Float64, out)
16014 }
16015
16016 pub fn fix(&self) -> Result<Self, ColumnError> {
16020 self.trunc()
16021 }
16022
16023 pub fn trim_zeros(&self, trim: &str) -> Result<Self, ColumnError> {
16030 let values = &self.values;
16031 if values.is_empty() {
16032 return Self::new(self.dtype, vec![]);
16033 }
16034
16035 let is_zero = |s: &Scalar| -> bool {
16036 match s {
16037 Scalar::Int64(x) => *x == 0,
16038 Scalar::Float64(x) => *x == 0.0,
16039 Scalar::Bool(b) => !*b,
16040 _ => false,
16041 }
16042 };
16043
16044 let mut start = 0;
16045 let mut end = values.len();
16046
16047 if trim.contains('f') {
16048 while start < end && is_zero(&values[start]) {
16049 start += 1;
16050 }
16051 }
16052
16053 if trim.contains('b') {
16054 while end > start && is_zero(&values[end - 1]) {
16055 end -= 1;
16056 }
16057 }
16058
16059 Self::new(self.dtype, values[start..end].to_vec())
16060 }
16061
16062 pub fn around(&self, decimals: i32) -> Result<Self, ColumnError> {
16067 let factor = 10.0_f64.powi(decimals);
16068 let mut out = Vec::with_capacity(self.values.len());
16069 for v in &self.values {
16070 if v.is_missing() {
16071 out.push(Scalar::Float64(f64::NAN));
16072 continue;
16073 }
16074 match v {
16075 Scalar::Int64(x) => {
16076 if decimals >= 0 {
16077 out.push(Scalar::Int64(*x));
16078 } else {
16079 let rounded = ((*x as f64) * factor).round_ties_even() / factor;
16082 out.push(Scalar::Int64(rounded as i64));
16083 }
16084 }
16085 Scalar::Float64(x) => {
16086 let rounded = (*x * factor).round_ties_even() / factor;
16087 out.push(Scalar::Float64(rounded));
16088 }
16089 _ => {
16090 return Err(ColumnError::Type(TypeError::NonNumericValue {
16091 value: format!("{v:?}"),
16092 dtype: self.dtype,
16093 }));
16094 }
16095 }
16096 }
16097 if decimals >= 0 && self.dtype == DType::Int64 {
16098 Self::new(DType::Int64, out)
16099 } else {
16100 Self::new(DType::Float64, out)
16101 }
16102 }
16103
16104 pub fn unwrap(&self, discont: Option<f64>) -> Result<Self, ColumnError> {
16110 let threshold = discont.unwrap_or(std::f64::consts::PI);
16111 let two_pi = 2.0 * std::f64::consts::PI;
16112
16113 let mut out = Vec::with_capacity(self.values.len());
16114 let mut offset = 0.0;
16115
16116 for (i, v) in self.values.iter().enumerate() {
16117 if v.is_missing() {
16118 out.push(Scalar::Float64(f64::NAN));
16119 continue;
16120 }
16121 let x = match v {
16122 Scalar::Int64(x) => *x as f64,
16123 Scalar::Float64(x) => *x,
16124 _ => {
16125 return Err(ColumnError::Type(TypeError::NonNumericValue {
16126 value: format!("{v:?}"),
16127 dtype: self.dtype,
16128 }));
16129 }
16130 };
16131
16132 if i == 0 {
16133 out.push(Scalar::Float64(x));
16134 } else {
16135 let prev = match &out[out.len() - 1] {
16136 Scalar::Float64(p) if !p.is_nan() => *p,
16137 _ => {
16138 out.push(Scalar::Float64(x + offset));
16139 continue;
16140 }
16141 };
16142
16143 let diff = x + offset - prev;
16144 if diff > threshold {
16145 offset -= two_pi * ((diff + std::f64::consts::PI) / two_pi).floor();
16146 } else if diff < -threshold {
16147 offset += two_pi * ((-diff + std::f64::consts::PI) / two_pi).floor();
16148 }
16149 out.push(Scalar::Float64(x + offset));
16150 }
16151 }
16152
16153 Self::new(DType::Float64, out)
16154 }
16155
16156 pub fn expm1(&self) -> Result<Self, ColumnError> {
16158 if let Some(out) = self.typed_float_unary(f64::exp_m1) {
16159 return Ok(out);
16160 }
16161 let mut out = Vec::with_capacity(self.values.len());
16162 for v in &self.values {
16163 if v.is_missing() {
16164 out.push(Scalar::Float64(f64::NAN));
16165 continue;
16166 }
16167 match v {
16168 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).exp_m1())),
16169 Scalar::Float64(x) => out.push(Scalar::Float64(x.exp_m1())),
16170 _ => {
16171 return Err(ColumnError::Type(TypeError::NonNumericValue {
16172 value: format!("{v:?}"),
16173 dtype: self.dtype,
16174 }));
16175 }
16176 }
16177 }
16178 Self::new(DType::Float64, out)
16179 }
16180
16181 pub fn log1p(&self) -> Result<Self, ColumnError> {
16183 if let Some(out) = self.typed_float_unary(f64::ln_1p) {
16184 return Ok(out);
16185 }
16186 let mut out = Vec::with_capacity(self.values.len());
16187 for v in &self.values {
16188 if v.is_missing() {
16189 out.push(Scalar::Float64(f64::NAN));
16190 continue;
16191 }
16192 match v {
16193 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).ln_1p())),
16194 Scalar::Float64(x) => out.push(Scalar::Float64(x.ln_1p())),
16195 _ => {
16196 return Err(ColumnError::Type(TypeError::NonNumericValue {
16197 value: format!("{v:?}"),
16198 dtype: self.dtype,
16199 }));
16200 }
16201 }
16202 }
16203 Self::new(DType::Float64, out)
16204 }
16205
16206 pub fn cbrt(&self) -> Result<Self, ColumnError> {
16208 if let Some(out) = self.typed_float_unary(f64::cbrt) {
16209 return Ok(out);
16210 }
16211 let mut out = Vec::with_capacity(self.values.len());
16212 for v in &self.values {
16213 if v.is_missing() {
16214 out.push(Scalar::Float64(f64::NAN));
16215 continue;
16216 }
16217 match v {
16218 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).cbrt())),
16219 Scalar::Float64(x) => out.push(Scalar::Float64(x.cbrt())),
16220 _ => {
16221 return Err(ColumnError::Type(TypeError::NonNumericValue {
16222 value: format!("{v:?}"),
16223 dtype: self.dtype,
16224 }));
16225 }
16226 }
16227 }
16228 Self::new(DType::Float64, out)
16229 }
16230
16231 pub fn ldexp(&self, exp: i32) -> Result<Self, ColumnError> {
16235 let multiplier = 2.0_f64.powi(exp);
16236 let mut out = Vec::with_capacity(self.values.len());
16237 for v in &self.values {
16238 if v.is_missing() {
16239 out.push(Scalar::Float64(f64::NAN));
16240 continue;
16241 }
16242 match v {
16243 Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64 * multiplier)),
16244 Scalar::Float64(x) => out.push(Scalar::Float64(x * multiplier)),
16245 _ => {
16246 return Err(ColumnError::Type(TypeError::NonNumericValue {
16247 value: format!("{v:?}"),
16248 dtype: self.dtype,
16249 }));
16250 }
16251 }
16252 }
16253 Self::new(DType::Float64, out)
16254 }
16255
16256 pub fn modf(&self) -> Result<(Self, Self), ColumnError> {
16261 let mut frac = Vec::with_capacity(self.values.len());
16262 let mut int = Vec::with_capacity(self.values.len());
16263 for v in &self.values {
16264 if v.is_missing() {
16265 frac.push(Scalar::Float64(f64::NAN));
16266 int.push(Scalar::Float64(f64::NAN));
16267 continue;
16268 }
16269 match v {
16270 Scalar::Int64(x) => {
16271 frac.push(Scalar::Float64(0.0));
16272 int.push(Scalar::Float64(*x as f64));
16273 }
16274 Scalar::Float64(x) => {
16275 let i = x.trunc();
16276 let f = x - i;
16277 frac.push(Scalar::Float64(f));
16278 int.push(Scalar::Float64(i));
16279 }
16280 _ => {
16281 return Err(ColumnError::Type(TypeError::NonNumericValue {
16282 value: format!("{v:?}"),
16283 dtype: self.dtype,
16284 }));
16285 }
16286 }
16287 }
16288 Ok((
16289 Self::new(DType::Float64, frac)?,
16290 Self::new(DType::Float64, int)?,
16291 ))
16292 }
16293
16294 pub fn frexp(&self) -> Result<(Self, Self), ColumnError> {
16301 let mut mantissa = Vec::with_capacity(self.values.len());
16302 let mut exponent = Vec::with_capacity(self.values.len());
16303 for v in &self.values {
16304 if v.is_missing() {
16305 mantissa.push(Scalar::Float64(f64::NAN));
16306 exponent.push(Scalar::Int64(0));
16307 continue;
16308 }
16309 match v {
16310 Scalar::Int64(x) => {
16311 let f = *x as f64;
16312 if f == 0.0 {
16313 mantissa.push(Scalar::Float64(0.0));
16314 exponent.push(Scalar::Int64(0));
16315 } else {
16316 let bits = f.abs().to_bits();
16317 let exp_bits = ((bits >> 52) & 0x7ff) as i64;
16318 let exp = exp_bits - 1022; let mant_bits = (bits & 0x000f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000;
16320 let mant = f64::from_bits(mant_bits);
16321 let mant = if f < 0.0 { -mant } else { mant };
16322 mantissa.push(Scalar::Float64(mant));
16323 exponent.push(Scalar::Int64(exp));
16324 }
16325 }
16326 Scalar::Float64(x) => {
16327 if x.is_nan() {
16328 mantissa.push(Scalar::Float64(f64::NAN));
16329 exponent.push(Scalar::Int64(0));
16330 } else if x.is_infinite() {
16331 mantissa.push(Scalar::Float64(*x));
16332 exponent.push(Scalar::Int64(0));
16333 } else if *x == 0.0 {
16334 mantissa.push(Scalar::Float64(*x)); exponent.push(Scalar::Int64(0));
16336 } else {
16337 let bits = x.abs().to_bits();
16338 let exp_bits = ((bits >> 52) & 0x7ff) as i64;
16339 if exp_bits == 0 {
16340 let scaled = x.abs() * 2.0_f64.powi(64);
16342 let sbits = scaled.to_bits();
16343 let sexp_bits = ((sbits >> 52) & 0x7ff) as i64;
16344 let exp = sexp_bits - 1022 - 64;
16345 let mant_bits = (sbits & 0x000f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000;
16346 let mant = f64::from_bits(mant_bits);
16347 let mant = if *x < 0.0 { -mant } else { mant };
16348 mantissa.push(Scalar::Float64(mant));
16349 exponent.push(Scalar::Int64(exp));
16350 } else {
16351 let exp = exp_bits - 1022;
16352 let mant_bits = (bits & 0x000f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000;
16353 let mant = f64::from_bits(mant_bits);
16354 let mant = if *x < 0.0 { -mant } else { mant };
16355 mantissa.push(Scalar::Float64(mant));
16356 exponent.push(Scalar::Int64(exp));
16357 }
16358 }
16359 }
16360 _ => {
16361 return Err(ColumnError::Type(TypeError::NonNumericValue {
16362 value: format!("{v:?}"),
16363 dtype: self.dtype,
16364 }));
16365 }
16366 }
16367 }
16368 Ok((
16369 Self::new(DType::Float64, mantissa)?,
16370 Self::new(DType::Int64, exponent)?,
16371 ))
16372 }
16373
16374 pub fn nextafter(&self, other: &Self) -> Result<Self, ColumnError> {
16379 if self.len() != other.len() {
16380 return Err(ColumnError::LengthMismatch {
16381 left: self.len(),
16382 right: other.len(),
16383 });
16384 }
16385 let mut out = Vec::with_capacity(self.values.len());
16386 for (v1, v2) in self.values.iter().zip(other.values.iter()) {
16387 if v1.is_missing() || v2.is_missing() {
16388 out.push(Scalar::Float64(f64::NAN));
16389 continue;
16390 }
16391 let x = v1.to_f64().map_err(ColumnError::Type)?;
16392 let y = v2.to_f64().map_err(ColumnError::Type)?;
16393 let result = if x.is_nan() || y.is_nan() {
16394 f64::NAN
16395 } else if x == y {
16396 x
16397 } else if x == 0.0 {
16398 if y > 0.0 {
16400 f64::from_bits(1) } else {
16402 -f64::from_bits(1) }
16404 } else {
16405 let bits = x.to_bits() as i64;
16406 let next_bits = if (x > 0.0) == (y > x) {
16407 bits + 1
16408 } else {
16409 bits - 1
16410 };
16411 f64::from_bits(next_bits as u64)
16412 };
16413 out.push(Scalar::Float64(result));
16414 }
16415 Self::new(DType::Float64, out)
16416 }
16417
16418 pub fn isneginf(&self) -> Result<Self, ColumnError> {
16423 let mut out = Vec::with_capacity(self.values.len());
16424 for v in &self.values {
16425 if v.is_missing() {
16426 out.push(Scalar::Bool(false));
16427 continue;
16428 }
16429 match v {
16430 Scalar::Int64(_) => out.push(Scalar::Bool(false)),
16431 Scalar::Float64(x) => out.push(Scalar::Bool(*x == f64::NEG_INFINITY)),
16432 _ => out.push(Scalar::Bool(false)),
16433 }
16434 }
16435 Self::new(DType::Bool, out)
16436 }
16437
16438 pub fn isposinf(&self) -> Result<Self, ColumnError> {
16443 let mut out = Vec::with_capacity(self.values.len());
16444 for v in &self.values {
16445 if v.is_missing() {
16446 out.push(Scalar::Bool(false));
16447 continue;
16448 }
16449 match v {
16450 Scalar::Int64(_) => out.push(Scalar::Bool(false)),
16451 Scalar::Float64(x) => out.push(Scalar::Bool(*x == f64::INFINITY)),
16452 _ => out.push(Scalar::Bool(false)),
16453 }
16454 }
16455 Self::new(DType::Bool, out)
16456 }
16457
16458 pub fn exp2(&self) -> Result<Self, ColumnError> {
16462 if let Some(data) = self.as_f64_slice() {
16466 return Ok(Self::from_f64_values(
16467 data.iter().map(|&x| x.exp2()).collect(),
16468 ));
16469 }
16470 if let Some(data) = self.as_i64_slice() {
16471 return Ok(Self::from_f64_values(
16472 data.iter().map(|&x| 2.0_f64.powi(x as i32)).collect(),
16473 ));
16474 }
16475 let mut out = Vec::with_capacity(self.values.len());
16476 for v in &self.values {
16477 if v.is_missing() {
16478 out.push(Scalar::Float64(f64::NAN));
16479 continue;
16480 }
16481 match v {
16482 Scalar::Int64(x) => out.push(Scalar::Float64(2.0_f64.powi(*x as i32))),
16483 Scalar::Float64(x) => out.push(Scalar::Float64(x.exp2())),
16484 _ => {
16485 return Err(ColumnError::Type(TypeError::NonNumericValue {
16486 value: format!("{v:?}"),
16487 dtype: self.dtype,
16488 }));
16489 }
16490 }
16491 }
16492 Self::new(DType::Float64, out)
16493 }
16494
16495 pub fn sinc(&self) -> Result<Self, ColumnError> {
16499 if let Some(out) = self.typed_float_unary(|x| {
16502 if x == 0.0 {
16503 1.0
16504 } else {
16505 let px = std::f64::consts::PI * x;
16506 px.sin() / px
16507 }
16508 }) {
16509 return Ok(out);
16510 }
16511 let mut out = Vec::with_capacity(self.values.len());
16512 for v in &self.values {
16513 if v.is_missing() {
16514 out.push(Scalar::Float64(f64::NAN));
16515 continue;
16516 }
16517 match v {
16518 Scalar::Int64(x) => {
16519 if *x == 0 {
16520 out.push(Scalar::Float64(1.0));
16521 } else {
16522 let px = std::f64::consts::PI * (*x as f64);
16523 out.push(Scalar::Float64(px.sin() / px));
16524 }
16525 }
16526 Scalar::Float64(x) => {
16527 if *x == 0.0 {
16528 out.push(Scalar::Float64(1.0));
16529 } else if x.is_nan() {
16530 out.push(Scalar::Float64(f64::NAN));
16531 } else {
16532 let px = std::f64::consts::PI * x;
16533 out.push(Scalar::Float64(px.sin() / px));
16534 }
16535 }
16536 _ => {
16537 return Err(ColumnError::Type(TypeError::NonNumericValue {
16538 value: format!("{v:?}"),
16539 dtype: self.dtype,
16540 }));
16541 }
16542 }
16543 }
16544 Self::new(DType::Float64, out)
16545 }
16546
16547 pub fn logaddexp(&self, other: &Self) -> Result<Self, ColumnError> {
16552 if self.len() != other.len() {
16553 return Err(ColumnError::LengthMismatch {
16554 left: self.len(),
16555 right: other.len(),
16556 });
16557 }
16558 let mut out = Vec::with_capacity(self.values.len());
16559 for (v1, v2) in self.values.iter().zip(other.values.iter()) {
16560 if v1.is_missing() || v2.is_missing() {
16561 out.push(Scalar::Float64(f64::NAN));
16562 continue;
16563 }
16564 let x = v1.to_f64().map_err(ColumnError::Type)?;
16565 let y = v2.to_f64().map_err(ColumnError::Type)?;
16566 let result = if x.is_nan() || y.is_nan() {
16567 f64::NAN
16568 } else if x == f64::NEG_INFINITY {
16569 y
16570 } else if y == f64::NEG_INFINITY {
16571 x
16572 } else if x == f64::INFINITY || y == f64::INFINITY {
16573 f64::INFINITY
16574 } else if x >= y {
16575 x + (y - x).exp().ln_1p()
16576 } else {
16577 y + (x - y).exp().ln_1p()
16578 };
16579 out.push(Scalar::Float64(result));
16580 }
16581 Self::new(DType::Float64, out)
16582 }
16583
16584 pub fn logaddexp2(&self, other: &Self) -> Result<Self, ColumnError> {
16588 if self.len() != other.len() {
16589 return Err(ColumnError::LengthMismatch {
16590 left: self.len(),
16591 right: other.len(),
16592 });
16593 }
16594 let ln2 = std::f64::consts::LN_2;
16595 let mut out = Vec::with_capacity(self.values.len());
16596 for (v1, v2) in self.values.iter().zip(other.values.iter()) {
16597 if v1.is_missing() || v2.is_missing() {
16598 out.push(Scalar::Float64(f64::NAN));
16599 continue;
16600 }
16601 let x = v1.to_f64().map_err(ColumnError::Type)?;
16602 let y = v2.to_f64().map_err(ColumnError::Type)?;
16603 let result = if x.is_nan() || y.is_nan() {
16604 f64::NAN
16605 } else if x == f64::NEG_INFINITY {
16606 y
16607 } else if y == f64::NEG_INFINITY {
16608 x
16609 } else if x == f64::INFINITY || y == f64::INFINITY {
16610 f64::INFINITY
16611 } else if x >= y {
16612 x + ((y - x) * ln2).exp().ln_1p() / ln2
16613 } else {
16614 y + ((x - y) * ln2).exp().ln_1p() / ln2
16615 };
16616 out.push(Scalar::Float64(result));
16617 }
16618 Self::new(DType::Float64, out)
16619 }
16620
16621 pub fn spacing(&self) -> Result<Self, ColumnError> {
16626 let mut out = Vec::with_capacity(self.values.len());
16627 for v in &self.values {
16628 if v.is_missing() {
16629 out.push(Scalar::Float64(f64::NAN));
16630 continue;
16631 }
16632 match v {
16633 Scalar::Int64(x) => {
16634 let f = (*x as f64).abs();
16635 if f == 0.0 {
16636 out.push(Scalar::Float64(f64::from_bits(1)));
16637 } else {
16638 let bits = f.to_bits();
16639 let next = f64::from_bits(bits + 1);
16640 out.push(Scalar::Float64(next - f));
16641 }
16642 }
16643 Scalar::Float64(x) => {
16644 if x.is_nan() || x.is_infinite() {
16645 out.push(Scalar::Float64(f64::NAN));
16646 } else {
16647 let f = x.abs();
16648 if f == 0.0 {
16649 out.push(Scalar::Float64(f64::from_bits(1)));
16650 } else {
16651 let bits = f.to_bits();
16652 let next = f64::from_bits(bits + 1);
16653 out.push(Scalar::Float64(next - f));
16654 }
16655 }
16656 }
16657 _ => {
16658 return Err(ColumnError::Type(TypeError::NonNumericValue {
16659 value: format!("{v:?}"),
16660 dtype: self.dtype,
16661 }));
16662 }
16663 }
16664 }
16665 Self::new(DType::Float64, out)
16666 }
16667
16668 pub fn radians(&self) -> Result<Self, ColumnError> {
16670 if let Some(out) = self.typed_float_unary(f64::to_radians) {
16671 return Ok(out);
16672 }
16673 let mut out = Vec::with_capacity(self.values.len());
16674 for v in &self.values {
16675 if v.is_missing() {
16676 out.push(Scalar::Float64(f64::NAN));
16677 continue;
16678 }
16679 match v {
16680 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).to_radians())),
16681 Scalar::Float64(x) => out.push(Scalar::Float64(x.to_radians())),
16682 _ => {
16683 return Err(ColumnError::Type(TypeError::NonNumericValue {
16684 value: format!("{v:?}"),
16685 dtype: self.dtype,
16686 }));
16687 }
16688 }
16689 }
16690 Self::new(DType::Float64, out)
16691 }
16692
16693 pub fn deg2rad(&self) -> Result<Self, ColumnError> {
16695 self.radians()
16696 }
16697
16698 pub fn degrees(&self) -> Result<Self, ColumnError> {
16700 if let Some(out) = self.typed_float_unary(f64::to_degrees) {
16701 return Ok(out);
16702 }
16703 let mut out = Vec::with_capacity(self.values.len());
16704 for v in &self.values {
16705 if v.is_missing() {
16706 out.push(Scalar::Float64(f64::NAN));
16707 continue;
16708 }
16709 match v {
16710 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).to_degrees())),
16711 Scalar::Float64(x) => out.push(Scalar::Float64(x.to_degrees())),
16712 _ => {
16713 return Err(ColumnError::Type(TypeError::NonNumericValue {
16714 value: format!("{v:?}"),
16715 dtype: self.dtype,
16716 }));
16717 }
16718 }
16719 }
16720 Self::new(DType::Float64, out)
16721 }
16722
16723 pub fn rad2deg(&self) -> Result<Self, ColumnError> {
16725 self.degrees()
16726 }
16727
16728 pub fn reciprocal(&self) -> Result<Self, ColumnError> {
16730 if let Some(out) = self.typed_float_unary(|x| 1.0 / x) {
16731 return Ok(out);
16732 }
16733 let mut out = Vec::with_capacity(self.values.len());
16734 for v in &self.values {
16735 if v.is_missing() {
16736 out.push(Scalar::Float64(f64::NAN));
16737 continue;
16738 }
16739 match v {
16740 Scalar::Int64(x) => out.push(Scalar::Float64(1.0 / (*x as f64))),
16741 Scalar::Float64(x) => out.push(Scalar::Float64(1.0 / x)),
16742 _ => {
16743 return Err(ColumnError::Type(TypeError::NonNumericValue {
16744 value: format!("{v:?}"),
16745 dtype: self.dtype,
16746 }));
16747 }
16748 }
16749 }
16750 Self::new(DType::Float64, out)
16751 }
16752
16753 pub fn square(&self) -> Result<Self, ColumnError> {
16755 if let Some(data) = self.as_i64_slice() {
16759 return Ok(Self::from_i64_values(data.iter().map(|&x| x * x).collect()));
16760 }
16761 if let Some(data) = self.as_f64_slice() {
16762 return Ok(Self::from_f64_values(data.iter().map(|&x| x * x).collect()));
16763 }
16764 let mut out = Vec::with_capacity(self.values.len());
16765 for v in &self.values {
16766 if v.is_missing() {
16767 out.push(Scalar::Float64(f64::NAN));
16768 continue;
16769 }
16770 match v {
16771 Scalar::Int64(x) => out.push(Scalar::Int64(x * x)),
16772 Scalar::Float64(x) => out.push(Scalar::Float64(x * x)),
16773 _ => {
16774 return Err(ColumnError::Type(TypeError::NonNumericValue {
16775 value: format!("{v:?}"),
16776 dtype: self.dtype,
16777 }));
16778 }
16779 }
16780 }
16781 let dtype = match self.dtype {
16782 DType::Int64 => DType::Int64,
16783 _ => DType::Float64,
16784 };
16785 Self::new(dtype, out)
16786 }
16787
16788 pub fn shift(&self, periods: i64, fill: Scalar) -> Result<Self, ColumnError> {
16795 let len = self.values.len();
16796 if len == 0 || periods == 0 {
16797 return Ok(self.clone());
16798 }
16799 let abs = periods.unsigned_abs() as usize;
16800 if fill.is_missing()
16809 && let Some(data) = self.as_f64_slice()
16810 {
16811 let mut out = vec![f64::NAN; len];
16812 if abs < len {
16813 if periods > 0 {
16814 out[abs..].copy_from_slice(&data[..len - abs]);
16815 } else {
16816 out[..len - abs].copy_from_slice(&data[abs..]);
16817 }
16818 }
16819 return Ok(Self::from_f64_values(out));
16820 }
16821 let mut out: Vec<Scalar> = Vec::with_capacity(len);
16822 if abs >= len {
16823 for _ in 0..len {
16824 out.push(fill.clone());
16825 }
16826 } else if periods > 0 {
16827 for _ in 0..abs {
16828 out.push(fill.clone());
16829 }
16830 out.extend_from_slice(&self.values[..len - abs]);
16831 } else {
16832 out.extend_from_slice(&self.values[abs..]);
16833 for _ in 0..abs {
16834 out.push(fill.clone());
16835 }
16836 }
16837 Self::new(self.dtype, out)
16838 }
16839
16840 pub fn clip(&self, lower: Option<f64>, upper: Option<f64>) -> Result<Self, ColumnError> {
16847 let lower = lower.filter(|v| !v.is_nan());
16848 let upper = upper.filter(|v| !v.is_nan());
16849 let clamp = |mut x: f64| {
16857 if let Some(lo) = lower
16858 && x < lo
16859 {
16860 x = lo;
16861 }
16862 if let Some(hi) = upper
16863 && x > hi
16864 {
16865 x = hi;
16866 }
16867 x
16868 };
16869 if let Some(data) = self.as_f64_slice() {
16870 let out: Vec<f64> = data.iter().map(|&x| clamp(x)).collect();
16871 return Ok(Self::from_f64_values(out));
16872 }
16873 if let Some(data) = self.as_i64_slice() {
16874 let out: Vec<f64> = data.iter().map(|&x| clamp(x as f64)).collect();
16875 return Ok(Self::from_f64_values(out));
16876 }
16877
16878 let mut out = Vec::with_capacity(self.values.len());
16879 for v in &self.values {
16880 if v.is_missing() {
16881 out.push(v.clone());
16882 continue;
16883 }
16884 let numeric = match v.to_f64() {
16885 Ok(x) => x,
16886 Err(err) => return Err(ColumnError::Type(err)),
16887 };
16888 let mut clipped = numeric;
16889 if let Some(lo) = lower
16890 && clipped < lo
16891 {
16892 clipped = lo;
16893 }
16894 if let Some(hi) = upper
16895 && clipped > hi
16896 {
16897 clipped = hi;
16898 }
16899 out.push(Scalar::Float64(clipped));
16900 }
16901 Self::new(DType::Float64, out)
16902 }
16903
16904 pub fn round(&self, decimals: i32) -> Result<Self, ColumnError> {
16912 if matches!(self.dtype, DType::Bool) || (self.dtype == DType::Int64 && decimals >= 0) {
16913 return Ok(self.clone());
16914 }
16915 if self.dtype == DType::Int64 {
16916 let out = self
16917 .values
16918 .iter()
16919 .map(|v| match v {
16920 Scalar::Int64(value) => {
16921 Scalar::Int64(round_i64_negative_decimals(*value, decimals))
16922 }
16923 Scalar::Null(kind) => Scalar::Null(*kind),
16924 other => other.clone(),
16925 })
16926 .collect();
16927 return Self::new(DType::Int64, out);
16928 }
16929 let factor = 10f64.powi(decimals);
16930 if let Some(data) = self.as_f64_slice() {
16938 return Ok(Self::from_f64_values(
16939 data.iter()
16940 .map(|&x| (x * factor).round_ties_even() / factor)
16941 .collect(),
16942 ));
16943 }
16944 let mut out = Vec::with_capacity(self.values.len());
16945 for v in &self.values {
16946 if v.is_missing() {
16947 out.push(v.clone());
16948 continue;
16949 }
16950 match v.to_f64() {
16951 Ok(x) => out.push(Scalar::Float64((x * factor).round_ties_even() / factor)),
16952 Err(err) => return Err(ColumnError::Type(err)),
16953 }
16954 }
16955 Self::new(DType::Float64, out)
16956 }
16957
16958 pub fn isin(&self, needles: &[Scalar]) -> Result<Self, ColumnError> {
16964 #[derive(Hash, PartialEq, Eq)]
16965 enum Key<'a> {
16966 Bool(bool),
16967 Int64(i64),
16968 FloatBits(u64),
16969 Utf8(&'a str),
16970 Timedelta64(i64),
16971 Datetime64(i64),
16972 Period(i64),
16973 Interval(u64, u64, IntervalClosed),
16974 }
16975 fn key_of(v: &Scalar) -> Option<Key<'_>> {
16976 if v.is_missing() {
16977 return None;
16978 }
16979 Some(match v {
16980 Scalar::Bool(b) => Key::Bool(*b),
16981 Scalar::Int64(i) => Key::Int64(*i),
16982 Scalar::Float64(f) => {
16983 let norm = if *f == 0.0 { 0.0 } else { *f };
16984 Key::FloatBits(norm.to_bits())
16985 }
16986 Scalar::Utf8(s) => Key::Utf8(s.as_str()),
16987 Scalar::Timedelta64(v) => Key::Timedelta64(*v),
16988 Scalar::Datetime64(v) => Key::Datetime64(*v),
16989 Scalar::Period(p) => Key::Period(p.ordinal),
16990 Scalar::Interval(v) => {
16991 let (left, right, closed) = interval_key(v);
16992 Key::Interval(left, right, closed)
16993 }
16994 Scalar::Null(_) => return None,
16995 })
16996 }
16997
16998 if let Some(data) = self.as_i64_slice() {
17007 let mut n_min = i64::MAX;
17008 let mut n_max = i64::MIN;
17009 let mut saw_int_needle = false;
17010 for needle in needles {
17011 if let Scalar::Int64(v) = needle {
17012 saw_int_needle = true;
17013 n_min = n_min.min(*v);
17014 n_max = n_max.max(*v);
17015 }
17016 }
17017 if !saw_int_needle {
17018 return Ok(Self::from_bool_values(vec![false; data.len()]));
17019 }
17020 let span = i128::from(n_max) - i128::from(n_min) + 1;
17021 if span > 0 && span <= (1i128 << 24) {
17022 let mut present = vec![false; span as usize];
17023 for needle in needles {
17024 if let Scalar::Int64(v) = needle {
17025 present[(v - n_min) as usize] = true;
17026 }
17027 }
17028 let out: Vec<bool> = data
17029 .iter()
17030 .map(|&v| v >= n_min && v <= n_max && present[(v - n_min) as usize])
17031 .collect();
17032 return Ok(Self::from_bool_values(out));
17033 }
17034 }
17035
17036 let mut lookup: FxHashSet<Key<'_>> = FxHashSet::default();
17037 for n in needles {
17038 if let Some(k) = key_of(n) {
17039 lookup.insert(k);
17040 }
17041 }
17042
17043 let out: Vec<bool> = self
17049 .values
17050 .iter()
17051 .map(|v| match key_of(v) {
17052 Some(k) => lookup.contains(&k),
17053 None => false,
17054 })
17055 .collect();
17056 Ok(Self::from_bool_values(out))
17057 }
17058
17059 pub fn unique(&self) -> Result<Self, ColumnError> {
17065 if let Some(data) = self.as_i64_slice()
17072 && let Some((min, range)) = i64_direct_address_range(data)
17073 {
17074 let mut seen = vec![false; range];
17075 let mut out: Vec<i64> = Vec::new();
17076 for &v in data {
17077 let slot = (v as i128 - min as i128) as usize;
17078 if !seen[slot] {
17079 seen[slot] = true;
17080 out.push(v);
17081 }
17082 }
17083 return Ok(Self::from_i64_values(out));
17084 }
17085
17086 #[derive(Hash, PartialEq, Eq)]
17087 enum Key<'a> {
17088 Bool(bool),
17089 Int64(i64),
17090 FloatBits(u64),
17091 Utf8(&'a str),
17092 Timedelta64(i64),
17093 Datetime64(i64),
17094 Period(i64),
17095 Interval(u64, u64, IntervalClosed),
17096 }
17097
17098 let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
17099 let mut out = Vec::new();
17100 for v in &self.values {
17101 if v.is_missing() {
17102 continue;
17103 }
17104 let key = match v {
17105 Scalar::Bool(b) => Key::Bool(*b),
17106 Scalar::Int64(i) => Key::Int64(*i),
17107 Scalar::Float64(f) => {
17108 let norm = if *f == 0.0 { 0.0 } else { *f };
17109 Key::FloatBits(norm.to_bits())
17110 }
17111 Scalar::Utf8(s) => Key::Utf8(s.as_str()),
17112 Scalar::Timedelta64(v) => Key::Timedelta64(*v),
17113 Scalar::Datetime64(v) => Key::Datetime64(*v),
17114 Scalar::Period(p) => Key::Period(p.ordinal),
17115 Scalar::Interval(v) => {
17116 let (left, right, closed) = interval_key(v);
17117 Key::Interval(left, right, closed)
17118 }
17119 Scalar::Null(_) => continue,
17120 };
17121 if seen.insert(key) {
17122 out.push(v.clone());
17123 }
17124 }
17125 Self::new(self.dtype, out)
17126 }
17127
17128 pub fn setdiff1d(&self, other: &Self) -> Result<Self, ColumnError> {
17132 let other_unique = other.unique()?;
17133 let other_set: FxHashSet<SetMemberKey<'_>> = other_unique
17136 .values()
17137 .iter()
17138 .filter_map(set_member_key)
17139 .collect();
17140 let mut seen: FxHashSet<SetMemberKey<'_>> = FxHashSet::default();
17141 let mut out = Vec::new();
17142 for v in &self.values {
17143 let Some(key) = set_member_key(v) else {
17144 continue;
17145 };
17146 if !other_set.contains(&key) && seen.insert(key) {
17147 out.push(v.clone());
17148 }
17149 }
17150 Self::new(self.dtype, out)
17151 }
17152
17153 pub fn intersect1d(&self, other: &Self) -> Result<Self, ColumnError> {
17157 let self_unique = self.unique()?;
17158 let other_unique = other.unique()?;
17159 let other_set: FxHashSet<SetMemberKey<'_>> = other_unique
17160 .values()
17161 .iter()
17162 .filter_map(set_member_key)
17163 .collect();
17164 let mut out = Vec::new();
17165 for v in self_unique.values() {
17166 let Some(key) = set_member_key(v) else {
17167 continue;
17168 };
17169 if other_set.contains(&key) {
17170 out.push(v.clone());
17171 }
17172 }
17173 Self::new(self.dtype, out)
17174 }
17175
17176 pub fn union1d(&self, other: &Self) -> Result<Self, ColumnError> {
17180 let mut combined = self.values.to_vec();
17181 combined.extend(other.values().iter().cloned());
17182 let temp = Self::new(self.dtype, combined)?;
17183 temp.unique()
17184 }
17185
17186 pub fn setxor1d(&self, other: &Self) -> Result<Self, ColumnError> {
17191 let a_unique = self.unique()?;
17192 let b_unique = other.unique()?;
17193 let a_set: FxHashSet<SetMemberKey<'_>> = a_unique
17194 .values()
17195 .iter()
17196 .filter_map(set_member_key)
17197 .collect();
17198 let b_set: FxHashSet<SetMemberKey<'_>> = b_unique
17199 .values()
17200 .iter()
17201 .filter_map(set_member_key)
17202 .collect();
17203 let mut out = Vec::new();
17204 for v in a_unique.values() {
17206 let Some(key) = set_member_key(v) else {
17207 continue;
17208 };
17209 if !b_set.contains(&key) {
17210 out.push(v.clone());
17211 }
17212 }
17213 for v in b_unique.values() {
17215 let Some(key) = set_member_key(v) else {
17216 continue;
17217 };
17218 if !a_set.contains(&key) {
17219 out.push(v.clone());
17220 }
17221 }
17222 Self::new(self.dtype, out)
17223 }
17224
17225 pub fn in1d(&self, other: &Self) -> Result<Self, ColumnError> {
17229 let other_unique = other.unique()?;
17230 let other_set: FxHashSet<SetMemberKey<'_>> = other_unique
17231 .values()
17232 .iter()
17233 .filter_map(set_member_key)
17234 .collect();
17235 let mut out = Vec::with_capacity(self.values.len());
17237 for v in &self.values {
17238 let found = match set_member_key(v) {
17239 Some(key) => other_set.contains(&key),
17240 None => false, };
17242 out.push(found);
17243 }
17244 Ok(Self::from_bool_values(out))
17245 }
17246
17247 pub fn value_counts(&self) -> Result<(Self, Self), ColumnError> {
17253 self.value_counts_with_options(false, true, false, true)
17254 }
17255
17256 pub fn value_counts_with_options(
17262 &self,
17263 normalize: bool,
17264 sort: bool,
17265 ascending: bool,
17266 dropna: bool,
17267 ) -> Result<(Self, Self), ColumnError> {
17268 let mut counts: Vec<(Scalar, usize)> = Vec::new();
17277 let mut missing_count = 0_usize;
17278
17279 let dense_done = 'dense: {
17287 let Some(vals) = self.as_i64_slice() else {
17288 break 'dense false;
17289 };
17290 if vals.is_empty() {
17291 break 'dense false;
17292 }
17293 let (mut lo, mut hi) = (vals[0], vals[0]);
17294 for &v in vals {
17295 if v < lo {
17296 lo = v;
17297 }
17298 if v > hi {
17299 hi = v;
17300 }
17301 }
17302 let range = (hi as i128) - (lo as i128) + 1;
17303 let cap = ((vals.len() as i128) * 4).max(1 << 16);
17304 if range <= 0 || range > cap {
17305 break 'dense false;
17306 }
17307 let mut dense = vec![0_usize; range as usize];
17308 let mut first_seen: Vec<i64> = Vec::new();
17309 for &v in vals {
17310 let idx = (v - lo) as usize;
17311 if dense[idx] == 0 {
17312 first_seen.push(v);
17313 }
17314 dense[idx] += 1;
17315 }
17316 for v in first_seen {
17317 counts.push((Scalar::Int64(v), dense[(v - lo) as usize]));
17318 }
17319 true
17320 };
17321
17322 if !dense_done {
17323 let mut index: rustc_hash::FxHashMap<SetMemberKey<'_>, usize> =
17324 rustc_hash::FxHashMap::default();
17325 for value in &self.values {
17326 if value.is_missing() {
17327 missing_count += 1;
17328 continue;
17329 }
17330 let Some(key) = set_member_key(value) else {
17331 counts.push((value.clone(), 1));
17333 continue;
17334 };
17335 if let Some(&i) = index.get(&key) {
17336 counts[i].1 += 1;
17337 } else {
17338 index.insert(key, counts.len());
17339 counts.push((value.clone(), 1));
17340 }
17341 }
17342 }
17343
17344 if !dropna && missing_count > 0 {
17345 counts.push((Scalar::Null(NullKind::NaN), missing_count));
17346 }
17347
17348 if sort {
17349 if ascending {
17350 counts.sort_by_key(|(_, count)| *count);
17351 } else {
17352 counts.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
17353 }
17354 }
17355
17356 let total = if normalize {
17357 counts.iter().map(|(_, count)| *count).sum::<usize>() as f64
17358 } else {
17359 1.0
17360 };
17361
17362 let mut values_out = Vec::with_capacity(counts.len());
17363 let mut counts_out = Vec::with_capacity(counts.len());
17364 for (value, count) in counts {
17365 values_out.push(value);
17366 if normalize {
17367 let normalized = if total == 0.0 {
17368 0.0
17369 } else {
17370 count as f64 / total
17371 };
17372 counts_out.push(Scalar::Float64(normalized));
17373 } else {
17374 counts_out.push(Scalar::Int64(i64::try_from(count).unwrap_or(i64::MAX)));
17375 }
17376 }
17377
17378 let values = Self::new(self.dtype, values_out)?;
17379 let counts = Self::new(
17380 if normalize {
17381 DType::Float64
17382 } else {
17383 DType::Int64
17384 },
17385 counts_out,
17386 )?;
17387 Ok((values, counts))
17388 }
17389
17390 #[must_use]
17391 pub fn semantic_eq(&self, other: &Self) -> bool {
17392 self.dtype == other.dtype
17393 && self.values.len() == other.values.len()
17394 && self
17395 .values
17396 .iter()
17397 .zip(&other.values)
17398 .all(|(left, right)| left.semantic_eq(right))
17399 }
17400
17401 pub fn isclose(&self, other: &Self, rtol: f64, atol: f64) -> Result<Self, ColumnError> {
17405 if self.len() != other.len() {
17406 return Err(ColumnError::LengthMismatch {
17407 left: self.len(),
17408 right: other.len(),
17409 });
17410 }
17411 let mut out = Vec::with_capacity(self.values.len());
17412 for (a, b) in self.values.iter().zip(&other.values) {
17413 if a.is_missing() || b.is_missing() {
17414 out.push(Scalar::Bool(false));
17415 continue;
17416 }
17417 let af = a.to_f64().map_err(ColumnError::Type)?;
17418 let bf = b.to_f64().map_err(ColumnError::Type)?;
17419 let close = (af - bf).abs() <= atol + rtol * bf.abs();
17420 out.push(Scalar::Bool(close));
17421 }
17422 Self::new(DType::Bool, out)
17423 }
17424
17425 pub fn allclose(&self, other: &Self, rtol: f64, atol: f64) -> Result<bool, ColumnError> {
17429 let close = self.isclose(other, rtol, atol)?;
17430 for v in close.values() {
17431 match v {
17432 Scalar::Bool(true) => continue,
17433 Scalar::Bool(false) => return Ok(false),
17434 _ => return Ok(false),
17435 }
17436 }
17437 Ok(true)
17438 }
17439}
17440
17441pub struct CrackIndex {
17460 perm: Vec<usize>,
17463 cracks: Vec<(f64, usize)>,
17467}
17468
17469impl CrackIndex {
17470 #[must_use]
17472 pub fn new(len: usize) -> Self {
17473 Self {
17474 perm: (0..len).collect(),
17475 cracks: Vec::new(),
17476 }
17477 }
17478
17479 #[must_use]
17481 pub fn num_cracks(&self) -> usize {
17482 self.cracks.len()
17483 }
17484
17485 pub fn filter_gt(&mut self, column: &Column, value: f64) -> Vec<usize> {
17487 let split = self.crack_at(column, value);
17488 self.perm[split..].to_vec()
17489 }
17490
17491 pub fn filter_lte(&mut self, column: &Column, value: f64) -> Vec<usize> {
17493 let split = self.crack_at(column, value);
17494 self.perm[..split]
17495 .iter()
17496 .copied()
17497 .filter(|&idx| {
17498 column
17499 .value(idx)
17500 .and_then(|v| v.to_f64().ok())
17501 .is_some_and(|f| f <= value)
17502 })
17503 .collect()
17504 }
17505
17506 pub fn filter_gte(&mut self, column: &Column, value: f64) -> Vec<usize> {
17508 let split = self.crack_at(column, value);
17511 let mut result: Vec<usize> = self.perm[split..].to_vec();
17514 for &idx in &self.perm[..split] {
17515 if let Some(v) = column.value(idx)
17516 && let Ok(f) = v.to_f64()
17517 && f == value
17518 {
17519 result.push(idx);
17520 }
17521 }
17522 result
17523 }
17524
17525 pub fn filter_lt(&mut self, column: &Column, value: f64) -> Vec<usize> {
17527 let split = self.crack_at(column, value);
17528 self.perm[..split]
17530 .iter()
17531 .copied()
17532 .filter(|&idx| {
17533 column
17534 .value(idx)
17535 .and_then(|v| v.to_f64().ok())
17536 .is_some_and(|f| f < value)
17537 })
17538 .collect()
17539 }
17540
17541 pub fn filter_eq(&mut self, column: &Column, value: f64) -> Vec<usize> {
17543 let split = self.crack_at(column, value);
17544 self.perm[..split]
17546 .iter()
17547 .copied()
17548 .filter(|&idx| {
17549 column
17550 .value(idx)
17551 .and_then(|v| v.to_f64().ok())
17552 .is_some_and(|f| f == value)
17553 })
17554 .collect()
17555 }
17556
17557 fn crack_at(&mut self, column: &Column, value: f64) -> usize {
17560 if let Ok(pos) = self.cracks.binary_search_by(|probe| {
17562 probe
17563 .0
17564 .partial_cmp(&value)
17565 .unwrap_or(std::cmp::Ordering::Equal)
17566 }) {
17567 return self.cracks[pos].1;
17568 }
17569
17570 let (region_start, region_end) = self.find_region(value);
17572
17573 let split = self.partition_region(column, region_start, region_end, value);
17576
17577 let insert_pos = self
17579 .cracks
17580 .binary_search_by(|probe| {
17581 probe
17582 .0
17583 .partial_cmp(&value)
17584 .unwrap_or(std::cmp::Ordering::Equal)
17585 })
17586 .unwrap_or_else(|pos| pos);
17587 self.cracks.insert(insert_pos, (value, split));
17588
17589 split
17590 }
17591
17592 fn find_region(&self, value: f64) -> (usize, usize) {
17594 let mut start = 0;
17595 let mut end = self.perm.len();
17596
17597 for &(crack_val, crack_pos) in &self.cracks {
17598 if crack_val < value {
17599 start = start.max(crack_pos);
17600 } else {
17601 end = end.min(crack_pos);
17602 break;
17603 }
17604 }
17605
17606 (start, end)
17607 }
17608
17609 fn partition_region(&mut self, column: &Column, start: usize, end: usize, pivot: f64) -> usize {
17612 let region = &mut self.perm[start..end];
17614 let mut write = 0;
17615
17616 for read in 0..region.len() {
17617 let idx = region[read];
17618 let val = column
17619 .value(idx)
17620 .and_then(|v| v.to_f64().ok())
17621 .unwrap_or(f64::NEG_INFINITY); if val <= pivot {
17624 region.swap(write, read);
17625 write += 1;
17626 }
17627 }
17628
17629 start + write
17630 }
17631}
17632
17633#[cfg(test)]
17634mod tests {
17635 use std::sync::Arc;
17636
17637 use fp_types::{
17638 DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
17639 };
17640
17641 use super::{
17642 ArithmeticOp, BoolAffineSelectionWitness, Column, ColumnData, ColumnError, ScalarValues,
17643 SparseColumn, ValidityMask,
17644 };
17645
17646 #[test]
17647 fn reindex_injects_missing_values() {
17648 let column = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)])
17649 .expect("column should build");
17650
17651 let out = column
17652 .reindex_by_positions(&[Some(1), None, Some(0)])
17653 .expect("reindex should work");
17654
17655 assert_eq!(
17656 out.values(),
17657 &[
17658 Scalar::Int64(20),
17659 Scalar::Null(NullKind::Null),
17660 Scalar::Int64(10)
17661 ]
17662 );
17663 }
17664
17665 #[test]
17666 fn take_positions_matches_validated_materialization() {
17667 let column = Column::new(
17668 DType::Float64,
17669 vec![
17670 Scalar::Float64(1.5),
17671 Scalar::Null(NullKind::NaN),
17672 Scalar::Float64(3.5),
17673 ],
17674 )
17675 .expect("column should build");
17676
17677 let positions = [2, 1, 0, 2];
17678 let gathered = column.take_positions(&positions);
17679 let expected_values = positions
17680 .iter()
17681 .map(|&position| column.values()[position].clone())
17682 .collect::<Vec<_>>();
17683 let expected =
17684 Column::new(column.dtype(), expected_values).expect("validated materialization");
17685
17686 assert_eq!(gathered.dtype(), expected.dtype());
17687 assert_eq!(gathered.values(), expected.values());
17688 assert_eq!(gathered.validity(), expected.validity());
17689
17690 let empty = column.take_positions(&[]);
17691 assert_eq!(empty.dtype(), column.dtype());
17692 assert!(empty.values().is_empty());
17693 assert_eq!(empty.validity(), &ValidityMask::all_invalid(0));
17694 }
17695
17696 #[test]
17697 fn take_position_runs_nullable_float64_matches_take_positions() {
17698 let column =
17699 Column::from_f64_values(vec![1.0, 2.0, f64::NAN, 4.0, 5.0, 6.0, f64::NAN, 8.0]);
17700 let runs = [(0, 2), (3, 3), (7, 1)];
17701 let positions = [0, 1, 3, 4, 5, 7];
17702
17703 assert!(column.supports_fast_position_run_gather());
17704 let gathered = column.take_position_runs(&runs, positions.len());
17705 let expected = column.take_positions(&positions);
17706
17707 assert_eq!(gathered.dtype(), expected.dtype());
17708 assert_eq!(gathered.values(), expected.values());
17709 assert_eq!(gathered.validity(), expected.validity());
17710 assert!(matches!(
17711 &gathered.values,
17712 ScalarValues::LazyAllValidFloat64 { .. } | ScalarValues::LazyNullableFloat64 { .. }
17713 ));
17714 }
17715
17716 #[test]
17717 fn take_positions_all_valid_primitives_match_validated_materialization() {
17718 let cases = [
17719 (
17720 DType::Bool,
17721 vec![Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(false)],
17722 ),
17723 (
17724 DType::Int64,
17725 vec![Scalar::Int64(10), Scalar::Int64(-5), Scalar::Int64(42)],
17726 ),
17727 (
17728 DType::Float64,
17729 vec![
17730 Scalar::Float64(1.25),
17731 Scalar::Float64(-0.0),
17732 Scalar::Float64(9.5),
17733 ],
17734 ),
17735 (
17736 DType::Timedelta64,
17737 vec![
17738 Scalar::Timedelta64(10),
17739 Scalar::Timedelta64(-5),
17740 Scalar::Timedelta64(42),
17741 ],
17742 ),
17743 (
17744 DType::Datetime64,
17745 vec![
17746 Scalar::Datetime64(10),
17747 Scalar::Datetime64(-5),
17748 Scalar::Datetime64(42),
17749 ],
17750 ),
17751 (
17752 DType::Period,
17753 vec![
17754 Scalar::Period(Period::new(10, PeriodFreq::Daily)),
17755 Scalar::Period(Period::new(-5, PeriodFreq::Daily)),
17756 Scalar::Period(Period::new(42, PeriodFreq::Daily)),
17757 ],
17758 ),
17759 ];
17760
17761 let positions = [2, 0, 2, 1];
17762 for (dtype, values) in cases {
17763 let column = Column::new(dtype, values).expect("column should build");
17764 let gathered = column.take_positions(&positions);
17765 let expected_values = positions
17766 .iter()
17767 .map(|&position| column.values()[position].clone())
17768 .collect::<Vec<_>>();
17769 let expected =
17770 Column::new(column.dtype(), expected_values).expect("validated materialization");
17771
17772 assert_eq!(gathered.dtype(), expected.dtype());
17773 assert_eq!(gathered.values(), expected.values());
17774 assert_eq!(gathered.validity(), expected.validity());
17775 }
17776 }
17777
17778 #[test]
17779 fn take_positions_preserves_exact_null_kind_contract() {
17780 for (dtype, real) in [
17792 (DType::Float64, Scalar::Float64(2.5)),
17793 (DType::Int64, Scalar::Int64(7)),
17794 ] {
17795 let source = Column::new(
17796 dtype,
17797 vec![
17798 Scalar::Null(NullKind::NaN),
17799 Scalar::Null(NullKind::NaT),
17800 Scalar::Null(NullKind::Null),
17801 real,
17802 ],
17803 )
17804 .expect("column builds");
17805 let stored = source.values().to_vec();
17809 let positions = [3, 2, 1, 0, 1];
17810 let gathered = source.take_positions(&positions);
17811 for (out_idx, &pos) in positions.iter().enumerate() {
17812 assert_eq!(
17813 gathered.values()[out_idx],
17814 stored[pos],
17815 "dtype {dtype:?}: take_positions must reproduce the exact stored scalar \
17816 (incl. NullKind) for source position {pos}",
17817 );
17818 assert_eq!(
17820 gathered.validity().get(out_idx),
17821 source.validity().get(pos),
17822 "dtype {dtype:?}: validity must follow the gathered position {pos}",
17823 );
17824 }
17825 }
17826 }
17827
17828 #[test]
17829 fn primitive_columns_cache_typed_data_for_take_positions() {
17830 let column = Column::new(
17831 DType::Float64,
17832 vec![
17833 Scalar::Float64(1.25),
17834 Scalar::Float64(-0.0),
17835 Scalar::Float64(9.5),
17836 ],
17837 )
17838 .expect("column should build");
17839
17840 assert!(matches!(column.data, Some(ColumnData::Float64(_))));
17841 let positions = [2, 0, 1, 2];
17842 let gathered = column.take_positions(&positions);
17843 let expected = Column::new(
17844 DType::Float64,
17845 positions
17846 .iter()
17847 .map(|&position| column.values()[position].clone())
17848 .collect(),
17849 )
17850 .expect("validated materialization");
17851
17852 assert_eq!(gathered.values(), expected.values());
17853 assert_eq!(gathered.validity(), expected.validity());
17854 }
17855
17856 #[test]
17857 fn float64_take_positions_defers_scalar_materialization() {
17858 let column = Column::new(
17859 DType::Float64,
17860 vec![
17861 Scalar::Float64(1.25),
17862 Scalar::Float64(-0.0),
17863 Scalar::Float64(9.5),
17864 ],
17865 )
17866 .expect("column should build");
17867
17868 let positions = [2, 0, 1, 2];
17869 let gathered = column.take_positions(&positions);
17870
17871 assert!(
17872 matches!(&gathered.values, ScalarValues::LazyAllValidFloat64 { .. }),
17873 "Float64 gather should defer scalar materialization"
17874 );
17875 if let ScalarValues::LazyAllValidFloat64 { data, values, .. } = &gathered.values {
17876 assert_eq!(
17877 data.iter().map(|value| value.to_bits()).collect::<Vec<_>>(),
17878 vec![
17879 9.5f64.to_bits(),
17880 1.25f64.to_bits(),
17881 (-0.0f64).to_bits(),
17882 9.5f64.to_bits(),
17883 ]
17884 );
17885 assert!(values.get().is_none());
17886 }
17887 assert_eq!(gathered.len(), positions.len());
17888 assert_eq!(
17889 gathered.validity(),
17890 &ValidityMask::all_valid(positions.len())
17891 );
17892
17893 let expected = Column::new(
17894 DType::Float64,
17895 positions
17896 .iter()
17897 .map(|&position| column.values()[position].clone())
17898 .collect(),
17899 )
17900 .expect("validated materialization");
17901
17902 assert_eq!(gathered.values(), expected.values());
17903 assert!(
17904 matches!(&gathered.values, ScalarValues::LazyAllValidFloat64 { .. }),
17905 "Float64 gather should stay lazy after read"
17906 );
17907 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &gathered.values {
17908 assert!(values.get().is_some());
17909 }
17910 assert_eq!(gathered.validity(), expected.validity());
17911 }
17912
17913 #[test]
17914 fn float64_take_positions_contiguous_range_returns_slice_view() {
17915 let data: Vec<f64> = (0..160)
17916 .map(|i| match i {
17917 40 => -0.0,
17918 41 => f64::INFINITY,
17919 42 => f64::from_bits(1),
17920 _ => i as f64 + 0.5,
17921 })
17922 .collect();
17923 let expected_bits: Vec<u64> = data[32..112].iter().map(|value| value.to_bits()).collect();
17924 let column = Column::from_f64_values(data);
17925 let positions: Vec<usize> = (32..112).collect();
17926
17927 let gathered = column.take_positions(&positions);
17928
17929 assert!(
17930 matches!(
17931 &gathered.values,
17932 ScalarValues::LazyAllValidFloat64Slice { .. }
17933 ),
17934 "large contiguous Float64 takes should share the source buffer"
17935 );
17936 if let ScalarValues::LazyAllValidFloat64Slice {
17937 start, len, values, ..
17938 } = &gathered.values
17939 {
17940 assert_eq!((*start, *len), (32, 80));
17941 assert!(values.get().is_none());
17942 }
17943 assert_eq!(
17944 gathered.as_f64_slice().map(|values| {
17945 values
17946 .iter()
17947 .map(|value| value.to_bits())
17948 .collect::<Vec<_>>()
17949 }),
17950 Some(expected_bits)
17951 );
17952
17953 let expected = Column::from_f64_values(
17954 column.as_f64_slice().expect("source stays typed")[32..112].to_vec(),
17955 );
17956 assert_eq!(gathered.values(), expected.values());
17957 assert_eq!(gathered.validity(), expected.validity());
17958 if let ScalarValues::LazyAllValidFloat64Slice { values, .. } = &gathered.values {
17959 assert!(values.get().is_some());
17960 }
17961 }
17962
17963 #[test]
17964 fn float64_take_positions_contiguous_range_slices_existing_slice_view() {
17965 let data: Vec<f64> = (0..192).map(|i| (i as f64).mul_add(0.25, -7.0)).collect();
17966 let column = Column::from_f64_values(data);
17967 let first_positions: Vec<usize> = (20..128).collect();
17968 let first = column.take_positions(&first_positions);
17969 let second_positions: Vec<usize> = (10..74).collect();
17970
17971 let second = first.take_positions(&second_positions);
17972
17973 assert!(
17974 matches!(
17975 &second.values,
17976 ScalarValues::LazyAllValidFloat64Slice { .. }
17977 ),
17978 "nested contiguous Float64 take should remain a slice view"
17979 );
17980 if let ScalarValues::LazyAllValidFloat64Slice {
17981 start, len, values, ..
17982 } = &second.values
17983 {
17984 assert_eq!((*start, *len), (30, 64));
17985 assert!(values.get().is_none());
17986 }
17987 let expected = Column::from_f64_values(
17988 column.as_f64_slice().expect("source stays typed")[30..94].to_vec(),
17989 );
17990 assert_eq!(second.as_f64_slice(), expected.as_f64_slice());
17991 assert_eq!(second.values(), expected.values());
17992 }
17993
17994 #[test]
17995 fn take_contiguous_range_uses_typed_views_without_positions() {
17996 let f64_data: Vec<f64> = (0..160)
17997 .map(|i| if i == 72 { -0.0 } else { i as f64 * 0.5 })
17998 .collect();
17999 let f64_column = Column::from_f64_values(f64_data);
18000 let f64_range = f64_column.take_contiguous_range(64, 80);
18001 assert!(
18002 matches!(
18003 &f64_range.values,
18004 ScalarValues::LazyAllValidFloat64Slice { .. }
18005 ),
18006 "Float64 range gather should be a zero-copy slice view"
18007 );
18008 assert_eq!(
18009 f64_range.as_f64_slice().map(|values| {
18010 values
18011 .iter()
18012 .map(|value| value.to_bits())
18013 .collect::<Vec<_>>()
18014 }),
18015 f64_column.as_f64_slice().map(|values| values[64..144]
18016 .iter()
18017 .map(|value| value.to_bits())
18018 .collect::<Vec<_>>())
18019 );
18020
18021 let mut bytes = Vec::new();
18022 let mut offsets = Vec::with_capacity(6);
18023 offsets.push(0);
18024 for value in ["k000", "k001", "k002", "k003", "k004"] {
18025 bytes.extend_from_slice(value.as_bytes());
18026 offsets.push(bytes.len());
18027 }
18028 let utf8_column = Column::from_utf8_contiguous(bytes, offsets);
18029 let utf8_range = utf8_column.take_contiguous_range(1, 3);
18030 assert!(
18031 matches!(&utf8_range.values, ScalarValues::LazyUtf8Slice { .. }),
18032 "Utf8 range gather should be a zero-copy slice view"
18033 );
18034 assert_eq!(
18035 utf8_range.values(),
18036 &[
18037 Scalar::Utf8("k001".to_owned()),
18038 Scalar::Utf8("k002".to_owned()),
18039 Scalar::Utf8("k003".to_owned())
18040 ]
18041 );
18042 }
18043
18044 #[test]
18045 fn float64_take_positions_regular_stride_defers_contiguous_gather() {
18046 let data: Vec<f64> = (0..4096)
18047 .map(|i| match i {
18048 4 => -0.0,
18049 19 => f64::INFINITY,
18050 _ => i as f64 * 0.25,
18051 })
18052 .collect();
18053 let column = Column::from_f64_values(data.clone());
18054 let positions: Vec<usize> = (0..1024).map(|i| 3 + i * 4).collect();
18055
18056 let gathered = column.take_positions(&positions);
18057
18058 assert!(
18059 matches!(&gathered.values, ScalarValues::LazyStridedFloat64 { .. }),
18060 "wide regular Float64 gather should carry a strided view"
18061 );
18062 if let ScalarValues::LazyStridedFloat64 {
18063 start,
18064 step,
18065 len,
18066 expanded,
18067 values,
18068 ..
18069 } = &gathered.values
18070 {
18071 assert_eq!((*start, *step, *len), (3, 4, positions.len()));
18072 assert!(expanded.get().is_none());
18073 assert!(values.get().is_none());
18074 }
18075
18076 let expected_bits: Vec<u64> = positions.iter().map(|&pos| data[pos].to_bits()).collect();
18077 let gathered_bits: Vec<u64> = gathered
18078 .as_f64_slice()
18079 .expect("strided Float64 view must expose a contiguous typed view")
18080 .iter()
18081 .map(|value| value.to_bits())
18082 .collect();
18083 assert_eq!(gathered_bits, expected_bits);
18084 assert_eq!(
18085 gathered.validity(),
18086 &ValidityMask::all_valid(positions.len())
18087 );
18088
18089 let expected = Column::new(
18090 DType::Float64,
18091 positions
18092 .iter()
18093 .map(|&position| column.values()[position].clone())
18094 .collect(),
18095 )
18096 .expect("validated materialization");
18097 assert_eq!(gathered.values(), expected.values());
18098 assert_eq!(gathered.validity(), expected.validity());
18099 }
18100
18101 #[test]
18102 fn take_positions_with_affine_certificate_uses_lazy_strided_float64() {
18103 let data: Vec<f64> = (0..4096)
18104 .map(|i| match i {
18105 8 => -0.0,
18106 23 => f64::NEG_INFINITY,
18107 _ => i as f64 * 0.5,
18108 })
18109 .collect();
18110 let column = Column::from_f64_values(data.clone());
18111 let positions: Vec<usize> = (0..1024).map(|i| 2 + i * 3).collect();
18112
18113 let gathered = column.take_positions_with_affine_certificate(&positions, 2, 3);
18114
18115 assert!(
18116 matches!(&gathered.values, ScalarValues::LazyStridedFloat64 { .. }),
18117 "certified wide regular Float64 gather should carry a strided view"
18118 );
18119 if let ScalarValues::LazyStridedFloat64 {
18120 start,
18121 step,
18122 len,
18123 expanded,
18124 values,
18125 ..
18126 } = &gathered.values
18127 {
18128 assert_eq!((*start, *step, *len), (2, 3, positions.len()));
18129 assert!(expanded.get().is_none());
18130 assert!(values.get().is_none());
18131 }
18132
18133 let expected_bits: Vec<u64> = positions.iter().map(|&pos| data[pos].to_bits()).collect();
18134 let gathered_bits: Vec<u64> = gathered
18135 .as_f64_slice()
18136 .expect("certified strided Float64 view must expose typed data")
18137 .iter()
18138 .map(|value| value.to_bits())
18139 .collect();
18140 assert_eq!(gathered_bits, expected_bits);
18141 assert_eq!(
18142 gathered.validity(),
18143 &ValidityMask::all_valid(positions.len())
18144 );
18145 }
18146
18147 #[test]
18148 fn bounded_arithmetic_progression_positions_rejects_non_affine_or_oob() {
18149 assert_eq!(
18150 Column::bounded_arithmetic_progression_positions(&[3, 7, 11, 15], 16),
18151 Some((3, 4))
18152 );
18153 assert_eq!(
18154 Column::bounded_arithmetic_progression_positions(&[3, 7, 12], 16),
18155 None
18156 );
18157 assert_eq!(
18158 Column::bounded_arithmetic_progression_positions(&[3, 3, 3], 16),
18159 None
18160 );
18161 assert_eq!(
18162 Column::bounded_arithmetic_progression_positions(&[3, 7, 11, 15], 15),
18163 None
18164 );
18165 assert_eq!(
18166 Column::bounded_arithmetic_progression_positions(&[usize::MAX - 1, usize::MAX], 8),
18167 None
18168 );
18169 }
18170
18171 #[test]
18172 fn reindex_all_present_matches_materialization_and_keeps_float64_lazy() {
18173 let column = Column::from_f64_values(vec![1.25, -0.0, f64::INFINITY]);
18174
18175 let positions = [Some(2), Some(0), Some(1), Some(2)];
18176 let gathered = column
18177 .reindex_by_positions(&positions)
18178 .expect("all-present reindex should gather");
18179
18180 assert!(
18181 matches!(&gathered.values, ScalarValues::LazyAllValidFloat64 { .. }),
18182 "all-present Float64 reindex should defer scalar materialization"
18183 );
18184 if let ScalarValues::LazyAllValidFloat64 { data, values, .. } = &gathered.values {
18185 assert_eq!(
18186 data.iter().map(|value| value.to_bits()).collect::<Vec<_>>(),
18187 vec![
18188 f64::INFINITY.to_bits(),
18189 1.25f64.to_bits(),
18190 (-0.0f64).to_bits(),
18191 f64::INFINITY.to_bits(),
18192 ]
18193 );
18194 assert!(values.get().is_none());
18195 }
18196
18197 let expected = Column::new(
18198 DType::Float64,
18199 positions
18200 .iter()
18201 .map(|&position| column.values()[position.expect("present position")].clone())
18202 .collect(),
18203 )
18204 .expect("validated scalar materialization");
18205
18206 assert_eq!(gathered.dtype(), expected.dtype());
18207 assert_eq!(gathered.values(), expected.values());
18208 assert_eq!(gathered.validity(), expected.validity());
18209 }
18210
18211 #[test]
18212 fn column_equality_ignores_skipped_typed_cache() {
18213 let column = Column::new(
18214 DType::Int64,
18215 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
18216 )
18217 .expect("column should build");
18218
18219 let json = serde_json::to_string(&column).expect("serialize");
18220 let roundtrip: Column = serde_json::from_str(&json).expect("deserialize");
18221
18222 assert!(column.data.is_some());
18223 assert!(roundtrip.data.is_none());
18224 assert_eq!(column, roundtrip);
18225 }
18226
18227 #[test]
18228 fn column_clone_preserves_values_without_copying_private_cache() {
18229 let column = Column::new(
18230 DType::Int64,
18231 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
18232 )
18233 .expect("column should build");
18234
18235 let cloned = column.clone();
18236
18237 assert!(column.data.is_some());
18238 assert!(cloned.data.is_none());
18239 assert_eq!(column, cloned);
18240 }
18241
18242 #[test]
18243 fn dense_primitive_clone_defers_float64_scalar_materialization_from_typed_cache() {
18244 let column = Column::new(
18245 DType::Float64,
18246 vec![
18247 Scalar::Float64(1.5),
18248 Scalar::Float64(-0.0),
18249 Scalar::Float64(3.25),
18250 ],
18251 )
18252 .expect("column should build");
18253
18254 let cloned_values = column
18255 .clone_dense_values_from_cache()
18256 .expect("all-valid Float64 typed cache should clone");
18257 assert!(
18258 matches!(&cloned_values, ScalarValues::LazyAllValidFloat64 { .. }),
18259 "Float64 clone should defer scalar materialization"
18260 );
18261 if let ScalarValues::LazyAllValidFloat64 { data, values, .. } = &cloned_values {
18262 assert_eq!(
18263 data.iter().map(|value| value.to_bits()).collect::<Vec<_>>(),
18264 vec![1.5f64.to_bits(), (-0.0f64).to_bits(), 3.25f64.to_bits()]
18265 );
18266 assert!(values.get().is_none());
18267 }
18268
18269 let cloned = column.clone();
18270 assert!(
18271 matches!(&cloned.values, ScalarValues::LazyAllValidFloat64 { .. }),
18272 "Column::clone should keep all-valid Float64 clone values lazy"
18273 );
18274 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &cloned.values {
18275 assert!(values.get().is_none());
18276 }
18277 assert_eq!(cloned.values(), column.values());
18278 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &cloned.values {
18279 assert!(values.get().is_some());
18280 }
18281 assert_eq!(cloned.validity(), column.validity());
18282 assert!(cloned.data.is_none());
18283 }
18284
18285 #[test]
18286 fn dense_primitive_clone_falls_back_for_missing_values() {
18287 let column = Column::new(
18288 DType::Float64,
18289 vec![
18290 Scalar::Float64(1.5),
18291 Scalar::Null(NullKind::NaN),
18292 Scalar::Null(NullKind::Null),
18293 ],
18294 )
18295 .expect("column should build");
18296
18297 assert!(column.clone_dense_values_from_cache().is_none());
18298 let cloned = column.clone();
18299 assert_eq!(cloned.values(), column.values());
18300 assert_eq!(cloned.validity(), column.validity());
18301 assert!(cloned.data.is_none());
18302 }
18303
18304 #[test]
18305 fn numeric_addition_propagates_missing() {
18306 let left = Column::from_values(vec![
18307 Scalar::Int64(1),
18308 Scalar::Null(NullKind::Null),
18309 Scalar::Float64(f64::NAN),
18310 ])
18311 .expect("left");
18312 let right = Column::from_values(vec![Scalar::Int64(2), Scalar::Int64(5), Scalar::Int64(3)])
18313 .expect("right");
18314
18315 let out = left
18316 .binary_numeric(&right, ArithmeticOp::Add)
18317 .expect("add should pass");
18318
18319 assert_eq!(out.values()[0], Scalar::Float64(3.0));
18320 assert_eq!(out.values()[1], Scalar::Null(NullKind::NaN));
18321 assert_eq!(out.values()[2], Scalar::Null(NullKind::NaN));
18322 }
18323
18324 #[test]
18325 fn sparse_column_omits_fill_values_and_materializes_dense() {
18326 let dtype = SparseDType::new(DType::Int64, Scalar::Int64(0)).expect("sparse dtype");
18327 let sparse = SparseColumn::from_dense(
18328 dtype,
18329 vec![
18330 Scalar::Int64(0),
18331 Scalar::Int64(5),
18332 Scalar::Int64(0),
18333 Scalar::Int64(-2),
18334 ],
18335 )
18336 .expect("sparse column");
18337
18338 assert_eq!(sparse.value_dtype(), DType::Int64);
18339 assert_eq!(sparse.fill_value(), &Scalar::Int64(0));
18340 assert_eq!(sparse.len(), 4);
18341 assert_eq!(sparse.npoints(), 2);
18342 assert_eq!(sparse.indices(), &[1, 3]);
18343 assert_eq!(
18344 sparse.stored_values(),
18345 &[Scalar::Int64(5), Scalar::Int64(-2)]
18346 );
18347
18348 let dense = sparse.to_dense_column().expect("dense column");
18349 assert_eq!(dense.dtype(), DType::Int64);
18350 assert_eq!(
18351 dense.values(),
18352 &[
18353 Scalar::Int64(0),
18354 Scalar::Int64(5),
18355 Scalar::Int64(0),
18356 Scalar::Int64(-2),
18357 ]
18358 );
18359 }
18360
18361 #[test]
18362 fn sparse_column_preserves_nulls_when_fill_is_not_missing() {
18363 let dtype = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).expect("sparse dtype");
18364 let sparse = SparseColumn::from_dense(
18365 dtype,
18366 vec![
18367 Scalar::Float64(0.0),
18368 Scalar::Null(NullKind::NaN),
18369 Scalar::Float64(2.5),
18370 ],
18371 )
18372 .expect("sparse column");
18373
18374 assert_eq!(sparse.indices(), &[1, 2]);
18375 assert_eq!(sparse.npoints(), 2);
18376 assert!((sparse.density() - (2.0 / 3.0)).abs() < f64::EPSILON);
18377 assert!(sparse.stored_values()[0].is_missing());
18378 assert_eq!(sparse.stored_values()[1], Scalar::Float64(2.5));
18379
18380 let dense = sparse.to_dense_column().expect("dense column");
18381 assert_eq!(
18382 dense.values(),
18383 &[
18384 Scalar::Float64(0.0),
18385 Scalar::Null(NullKind::NaN),
18386 Scalar::Float64(2.5),
18387 ]
18388 );
18389 }
18390
18391 #[test]
18392 fn sparse_column_missing_fill_omits_missing_values() {
18393 let dtype =
18394 SparseDType::new(DType::Float64, Scalar::Null(NullKind::NaN)).expect("sparse dtype");
18395 let sparse = SparseColumn::from_dense(
18396 dtype,
18397 vec![
18398 Scalar::Null(NullKind::Null),
18399 Scalar::Float64(1.5),
18400 Scalar::Float64(f64::NAN),
18401 ],
18402 )
18403 .expect("sparse column");
18404
18405 assert_eq!(sparse.fill_value(), &Scalar::Null(NullKind::NaN));
18406 assert_eq!(sparse.indices(), &[1]);
18407 assert_eq!(sparse.stored_values(), &[Scalar::Float64(1.5)]);
18408 assert_eq!(
18409 sparse.to_dense_values(),
18410 vec![
18411 Scalar::Null(NullKind::NaN),
18412 Scalar::Float64(1.5),
18413 Scalar::Null(NullKind::NaN),
18414 ]
18415 );
18416 }
18417
18418 #[test]
18421 fn validity_mask_from_values_packs_correctly() {
18422 let values = vec![
18423 Scalar::Int64(1),
18424 Scalar::Null(NullKind::Null),
18425 Scalar::Int64(3),
18426 ];
18427 let mask = ValidityMask::from_values(&values);
18428 assert_eq!(mask.len(), 3);
18429 assert!(mask.get(0));
18430 assert!(!mask.get(1));
18431 assert!(mask.get(2));
18432 assert_eq!(mask.count_valid(), 2);
18433 }
18434
18435 #[test]
18436 fn validity_mask_all_valid() {
18437 let mask = ValidityMask::all_valid(100);
18438 assert_eq!(mask.len(), 100);
18439 assert_eq!(mask.count_valid(), 100);
18440 assert!(
18441 mask.words.is_empty(),
18442 "all-valid masks store only the logical length"
18443 );
18444 for i in 0..100 {
18445 assert!(mask.get(i), "bit {i} should be valid");
18446 }
18447 }
18448
18449 #[test]
18450 fn validity_mask_all_valid_sentinel_matches_explicit_words() {
18451 for len in [1, 2, 63, 64, 65, 127, 128, 129] {
18452 let sentinel = ValidityMask::all_valid(len);
18453 let explicit =
18454 ValidityMask::from_words(ValidityMask::materialized_all_valid_words(len), len);
18455
18456 assert_eq!(sentinel, explicit, "len {len}");
18457 assert_eq!(
18458 sentinel.bits().collect::<Vec<_>>(),
18459 explicit.bits().collect::<Vec<_>>(),
18460 "len {len}"
18461 );
18462 assert!(sentinel.all(), "len {len}");
18463 assert_eq!(sentinel.count_invalid(), 0, "len {len}");
18464 }
18465 }
18466
18467 #[test]
18468 fn validity_mask_all_valid_sentinel_materializes_on_clear() {
18469 let mut mask = ValidityMask::all_valid(130);
18470 mask.set(64, true);
18471 assert!(
18472 mask.words.is_empty(),
18473 "setting a valid bit preserves the sentinel"
18474 );
18475
18476 mask.set(64, false);
18477 assert!(!mask.words.is_empty(), "clearing a bit materializes words");
18478 assert_eq!(mask.len(), 130);
18479 assert_eq!(mask.count_valid(), 129);
18480 assert!(!mask.get(64));
18481 assert!(mask.get(63));
18482 assert!(mask.get(65));
18483 assert_eq!(mask.bits().filter(|valid| *valid).count(), 129);
18484 }
18485
18486 #[test]
18487 fn validity_mask_sparse_invalid_ranges_match_explicit_bitmap() {
18488 let sparse = ValidityMask::from_invalid_ranges(Arc::from(vec![(2, 3), (9, 2)]), 12);
18489 let mut explicit = ValidityMask::all_valid(12);
18490 for idx in [2, 3, 4, 9, 10] {
18491 explicit.set(idx, false);
18492 }
18493
18494 assert!(sparse.words.is_empty());
18495 assert!(sparse.invalid_ranges.is_some());
18496 assert_eq!(sparse, explicit);
18497 assert_eq!(sparse.count_valid(), 7);
18498 assert_eq!(sparse.count_invalid(), 5);
18499 assert!(sparse.get(1));
18500 assert!(!sparse.get(3));
18501 assert!(sparse.get(8));
18502 assert!(!sparse.get(10));
18503 assert_eq!(sparse.slice(1, 6), explicit.slice(1, 6));
18504 assert_eq!(sparse.not_mask(), explicit.not_mask());
18505
18506 let mut mutated = sparse.clone();
18507 mutated.set(2, true);
18508 explicit.set(2, true);
18509 assert_eq!(mutated, explicit);
18510 assert!(mutated.invalid_ranges.is_none());
18511 }
18512
18513 #[test]
18514 fn validity_mask_invalid_range_visitor_merges_word_boundaries() {
18515 let mut mask = ValidityMask::all_valid(140);
18516 for idx in 60..68 {
18517 mask.set(idx, false);
18518 }
18519 for idx in [3, 90, 91, 139] {
18520 mask.set(idx, false);
18521 }
18522
18523 let mut ranges = Vec::new();
18524 mask.for_each_invalid_range(|start, len| ranges.push((start, len)));
18525 assert_eq!(ranges, vec![(3, 1), (60, 8), (90, 2), (139, 1)]);
18526
18527 let sparse = ValidityMask::from_invalid_ranges(Arc::from(ranges.clone()), 140);
18528 let mut sparse_ranges = Vec::new();
18529 sparse.for_each_invalid_range(|start, len| sparse_ranges.push((start, len)));
18530 assert_eq!(sparse_ranges, ranges);
18531 }
18532
18533 #[test]
18534 fn validity_mask_all_invalid() {
18535 let mask = ValidityMask::all_invalid(100);
18536 assert_eq!(mask.len(), 100);
18537 assert_eq!(mask.count_valid(), 0);
18538 for i in 0..100 {
18539 assert!(!mask.get(i), "bit {i} should be invalid");
18540 }
18541 }
18542
18543 #[test]
18544 fn validity_mask_set_and_get() {
18545 let mut mask = ValidityMask::all_invalid(128);
18546 mask.set(0, true);
18547 mask.set(63, true);
18548 mask.set(64, true);
18549 mask.set(127, true);
18550 assert!(mask.get(0));
18551 assert!(mask.get(63));
18552 assert!(mask.get(64));
18553 assert!(mask.get(127));
18554 assert!(!mask.get(1));
18555 assert_eq!(mask.count_valid(), 4);
18556
18557 mask.set(63, false);
18558 assert!(!mask.get(63));
18559 assert_eq!(mask.count_valid(), 3);
18560 }
18561
18562 #[test]
18563 fn validity_mask_and_or_not() {
18564 let mut a = ValidityMask::all_invalid(4);
18565 a.set(0, true);
18566 a.set(1, true);
18567
18568 let mut b = ValidityMask::all_invalid(4);
18569 b.set(1, true);
18570 b.set(2, true);
18571
18572 let and = a.and_mask(&b);
18573 assert!(and.get(1));
18574 assert!(!and.get(0));
18575 assert!(!and.get(2));
18576 assert_eq!(and.count_valid(), 1);
18577
18578 let or = a.or_mask(&b);
18579 assert!(or.get(0));
18580 assert!(or.get(1));
18581 assert!(or.get(2));
18582 assert!(!or.get(3));
18583 assert_eq!(or.count_valid(), 3);
18584
18585 let not_a = a.not_mask();
18586 assert!(!not_a.get(0));
18587 assert!(!not_a.get(1));
18588 assert!(not_a.get(2));
18589 assert!(not_a.get(3));
18590 assert_eq!(not_a.count_valid(), 2);
18591 }
18592
18593 #[test]
18594 fn validity_mask_sentinel_mask_algebra_matches_explicit_bitmap() {
18595 let all = ValidityMask::all_valid(5);
18596 let nullable = ValidityMask::from_values(&[
18597 Scalar::Int64(1),
18598 Scalar::Null(NullKind::Null),
18599 Scalar::Int64(3),
18600 Scalar::Null(NullKind::NaN),
18601 Scalar::Int64(5),
18602 ]);
18603
18604 assert_eq!(all.and_mask(&nullable), nullable);
18605 assert_eq!(nullable.and_mask(&all), nullable);
18606 assert_eq!(all.or_mask(&nullable), all);
18607 assert_eq!(nullable.or_mask(&all), all);
18608 assert_eq!(
18609 all.xor_mask(&nullable).bits().collect::<Vec<_>>(),
18610 vec![false, true, false, true, false]
18611 );
18612 assert_eq!(
18613 all.not_mask().bits().collect::<Vec<_>>(),
18614 vec![false, false, false, false, false]
18615 );
18616 assert_eq!(
18617 all.slice(1, 3).bits().collect::<Vec<_>>(),
18618 vec![true, true, true]
18619 );
18620 assert_eq!(
18621 all.concat(&ValidityMask::all_valid(2)),
18622 ValidityMask::all_valid(7)
18623 );
18624 }
18625
18626 #[test]
18627 fn validity_mask_bits_iterator() {
18628 let values = vec![
18629 Scalar::Int64(1),
18630 Scalar::Null(NullKind::Null),
18631 Scalar::Int64(3),
18632 Scalar::Float64(f64::NAN),
18633 ];
18634 let mask = ValidityMask::from_values(&values);
18635 let bits: Vec<bool> = mask.bits().collect();
18636 assert_eq!(bits, vec![true, false, true, false]);
18637 }
18638
18639 #[test]
18640 fn validity_mask_serde_round_trip() {
18641 let values = vec![
18642 Scalar::Int64(1),
18643 Scalar::Null(NullKind::Null),
18644 Scalar::Int64(3),
18645 ];
18646 let mask = ValidityMask::from_values(&values);
18647 let json = serde_json::to_string(&mask).expect("serialize");
18648 let back: ValidityMask = serde_json::from_str(&json).expect("deserialize");
18649 assert_eq!(mask, back);
18650 assert!(json.contains("\"bits\""), "should serialize as bits field");
18652 }
18653
18654 #[test]
18655 fn validity_mask_empty() {
18656 let mask = ValidityMask::from_values(&[]);
18657 assert!(mask.is_empty());
18658 assert_eq!(mask.len(), 0);
18659 assert_eq!(mask.count_valid(), 0);
18660 assert_eq!(mask.bits().count(), 0);
18661 }
18662
18663 #[test]
18664 fn validity_mask_count_invalid_matches_complement() {
18665 let mask = ValidityMask::from_values(&[
18666 Scalar::Int64(1),
18667 Scalar::Null(NullKind::NaN),
18668 Scalar::Int64(2),
18669 Scalar::Null(NullKind::Null),
18670 Scalar::Int64(3),
18671 ]);
18672 assert_eq!(mask.count_valid(), 3);
18673 assert_eq!(mask.count_invalid(), 2);
18674 assert_eq!(mask.count_valid() + mask.count_invalid(), mask.len());
18675 }
18676
18677 #[test]
18678 fn validity_mask_any_and_all() {
18679 let all_set = ValidityMask::all_valid(4);
18680 assert!(all_set.any());
18681 assert!(all_set.all());
18682
18683 let none_set = ValidityMask::all_invalid(4);
18684 assert!(!none_set.any());
18685 assert!(!none_set.all());
18686
18687 let mixed = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::NaN)]);
18688 assert!(mixed.any());
18689 assert!(!mixed.all());
18690
18691 let empty = ValidityMask::all_invalid(0);
18692 assert!(!empty.any());
18693 assert!(empty.all()); }
18695
18696 #[test]
18697 fn validity_mask_xor_finds_differences() {
18698 let a = ValidityMask::from_values(&[
18699 Scalar::Int64(1),
18700 Scalar::Int64(2),
18701 Scalar::Null(NullKind::NaN),
18702 Scalar::Int64(4),
18703 ]);
18704 let b = ValidityMask::from_values(&[
18705 Scalar::Int64(1),
18706 Scalar::Null(NullKind::NaN),
18707 Scalar::Null(NullKind::NaN),
18708 Scalar::Int64(4),
18709 ]);
18710 let diff = a.xor_mask(&b);
18711 assert_eq!(diff.len(), 4);
18712 assert!(!diff.get(0));
18717 assert!(diff.get(1));
18718 assert!(!diff.get(2));
18719 assert!(!diff.get(3));
18720 }
18721
18722 #[test]
18723 fn validity_mask_slice_extracts_range() {
18724 let mask = ValidityMask::from_values(&[
18725 Scalar::Int64(1), Scalar::Null(NullKind::NaN), Scalar::Int64(3), Scalar::Int64(4), Scalar::Null(NullKind::NaN), ]);
18731 let sub = mask.slice(1, 3);
18732 assert_eq!(sub.len(), 3);
18733 assert!(!sub.get(0));
18734 assert!(sub.get(1));
18735 assert!(sub.get(2));
18736 }
18737
18738 #[test]
18739 fn validity_mask_slice_past_end_clamps() {
18740 let mask = ValidityMask::all_valid(3);
18741 let sub = mask.slice(2, 10);
18742 assert_eq!(sub.len(), 1);
18743 assert!(sub.get(0));
18744
18745 let empty = mask.slice(100, 5);
18746 assert!(empty.is_empty());
18747 }
18748
18749 #[test]
18750 fn validity_mask_concat_appends() {
18751 let a = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::NaN)]);
18752 let b = ValidityMask::from_values(&[Scalar::Int64(2), Scalar::Int64(3)]);
18753 let merged = a.concat(&b);
18754 assert_eq!(merged.len(), 4);
18755 assert!(merged.get(0));
18756 assert!(!merged.get(1));
18757 assert!(merged.get(2));
18758 assert!(merged.get(3));
18759 }
18760
18761 #[test]
18762 fn validity_mask_first_last_valid() {
18763 let mask = ValidityMask::from_values(&[
18764 Scalar::Null(NullKind::NaN),
18765 Scalar::Null(NullKind::NaN),
18766 Scalar::Int64(1),
18767 Scalar::Int64(2),
18768 Scalar::Null(NullKind::NaN),
18769 ]);
18770 assert_eq!(mask.first_valid(), Some(2));
18771 assert_eq!(mask.last_valid(), Some(3));
18772
18773 let none_set = ValidityMask::all_invalid(3);
18774 assert_eq!(none_set.first_valid(), None);
18775 assert_eq!(none_set.last_valid(), None);
18776 }
18777
18778 #[test]
18779 fn validity_mask_boundary_65_elements() {
18780 let mut values = vec![Scalar::Int64(1); 65];
18781 values[64] = Scalar::Null(NullKind::Null);
18782 let mask = ValidityMask::from_values(&values);
18783 assert_eq!(mask.len(), 65);
18784 assert_eq!(mask.count_valid(), 64);
18785 assert!(mask.get(63));
18786 assert!(!mask.get(64));
18787 }
18788
18789 #[test]
18790 fn validity_mask_equality() {
18791 let a = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::Null)]);
18792 let b = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::Null)]);
18793 let c = ValidityMask::from_values(&[Scalar::Null(NullKind::Null), Scalar::Int64(1)]);
18794 assert_eq!(a, b);
18795 assert_ne!(a, c);
18796 }
18797
18798 #[test]
18799 fn validity_mask_nan_is_invalid() {
18800 let values = vec![
18801 Scalar::Float64(1.0),
18802 Scalar::Float64(f64::NAN),
18803 Scalar::Null(NullKind::NaN),
18804 ];
18805 let mask = ValidityMask::from_values(&values);
18806 assert!(mask.get(0));
18807 assert!(!mask.get(1), "Float64(NaN) should be invalid");
18808 assert!(!mask.get(2), "Null(NaN) should be invalid");
18809 assert_eq!(mask.count_valid(), 1);
18810 }
18811
18812 #[test]
18813 fn validity_mask_dense_null_half() {
18814 let values: Vec<Scalar> = (0..1000)
18815 .map(|i| {
18816 if i % 2 == 0 {
18817 Scalar::Int64(i)
18818 } else {
18819 Scalar::Null(NullKind::Null)
18820 }
18821 })
18822 .collect();
18823 let mask = ValidityMask::from_values(&values);
18824 assert_eq!(mask.len(), 1000);
18825 assert_eq!(mask.count_valid(), 500);
18826 }
18827
18828 #[test]
18831 fn column_data_float64_roundtrip() {
18832 let values = vec![
18833 Scalar::Float64(1.5),
18834 Scalar::Null(NullKind::NaN),
18835 Scalar::Float64(3.0),
18836 ];
18837 let validity = ValidityMask::from_values(&values);
18838 let data = super::ColumnData::from_scalars(&values, fp_types::DType::Float64);
18839 let back = data.to_scalars(fp_types::DType::Float64, &validity);
18840 assert_eq!(back.len(), 3);
18841 assert_eq!(back[0], Scalar::Float64(1.5));
18842 assert!(back[1].is_nan(), "position 1 should be NaN-missing");
18843 assert_eq!(back[2], Scalar::Float64(3.0));
18844 }
18845
18846 #[test]
18847 fn column_data_int64_roundtrip() {
18848 let values = vec![
18849 Scalar::Int64(10),
18850 Scalar::Null(NullKind::Null),
18851 Scalar::Int64(30),
18852 ];
18853 let validity = ValidityMask::from_values(&values);
18854 let data = super::ColumnData::from_scalars(&values, fp_types::DType::Int64);
18855 assert_eq!(data.len(), 3);
18856 let back = data.to_scalars(fp_types::DType::Int64, &validity);
18857 assert_eq!(back[0], Scalar::Int64(10));
18858 assert!(back[1].is_missing());
18859 assert_eq!(back[2], Scalar::Int64(30));
18860 }
18861
18862 #[test]
18863 fn column_data_interval_roundtrip_and_column_uniques_5g5uj() {
18864 let first = Interval::new(0.0, 1.0, IntervalClosed::Right);
18865 let second = Interval::new(1.0, 2.0, IntervalClosed::Right);
18866 let values = vec![
18867 Scalar::Interval(first),
18868 Scalar::Null(NullKind::Null),
18869 Scalar::Interval(second),
18870 Scalar::Interval(first),
18871 ];
18872 let validity = ValidityMask::from_values(&values);
18873 let data = super::ColumnData::from_scalars(&values, DType::Interval);
18874 assert_eq!(data.len(), 4);
18875 let back = data.to_scalars(DType::Interval, &validity);
18876 assert_eq!(back[0], Scalar::Interval(first));
18877 assert!(back[1].is_missing());
18878 assert_eq!(back[2], Scalar::Interval(second));
18879 assert_eq!(back[3], Scalar::Interval(first));
18880
18881 let column = Column::new(DType::Interval, values).expect("interval column");
18882 assert_eq!(column.dtype(), DType::Interval);
18883 assert!(column.has_duplicates());
18884 let uniques = column.unique().expect("unique intervals");
18885 assert_eq!(
18886 uniques.values(),
18887 &[Scalar::Interval(first), Scalar::Interval(second)]
18888 );
18889 }
18890
18891 #[test]
18892 fn vectorized_f64_addition_matches_scalar() {
18893 let left = Column::from_values(vec![
18894 Scalar::Float64(1.0),
18895 Scalar::Float64(2.0),
18896 Scalar::Float64(3.0),
18897 ])
18898 .expect("left");
18899 let right = Column::from_values(vec![
18900 Scalar::Float64(10.0),
18901 Scalar::Float64(20.0),
18902 Scalar::Float64(30.0),
18903 ])
18904 .expect("right");
18905
18906 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
18907 assert_eq!(result.values()[0], Scalar::Float64(11.0));
18908 assert_eq!(result.values()[1], Scalar::Float64(22.0));
18909 assert_eq!(result.values()[2], Scalar::Float64(33.0));
18910 }
18911
18912 #[test]
18913 fn vectorized_i64_addition_matches_scalar() {
18914 let left = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
18915 .expect("left");
18916 let right = Column::from_values(vec![
18917 Scalar::Int64(10),
18918 Scalar::Int64(20),
18919 Scalar::Int64(30),
18920 ])
18921 .expect("right");
18922
18923 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
18924 assert_eq!(result.values()[0], Scalar::Int64(11));
18925 assert_eq!(result.values()[1], Scalar::Int64(22));
18926 assert_eq!(result.values()[2], Scalar::Int64(33));
18927 }
18928
18929 #[test]
18930 fn vectorized_binary_all_valid_keeps_typed_output_lazy() {
18931 let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
18932 let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
18933
18934 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
18935
18936 assert!(result.validity().all());
18937 assert_eq!(result.as_f64_slice(), Some([11.0, 22.0, 33.0].as_slice()));
18938 assert!(matches!(
18939 &result.values,
18940 ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
18941 ));
18942 }
18943
18944 #[test]
18945 fn vectorized_binary_operation_nan_matches_scalar_validity() {
18946 let left = Column::from_f64_values(vec![f64::INFINITY]);
18947 let right = Column::from_f64_values(vec![f64::INFINITY]);
18948
18949 let result = left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub");
18950
18951 assert!(!result.validity().get(0));
18952 assert!(matches!(result.values()[0], Scalar::Float64(v) if v.is_nan()));
18953 }
18954
18955 #[test]
18956 fn vectorized_f64_with_nulls_propagates_missing() {
18957 let left = Column::from_values(vec![
18958 Scalar::Float64(1.0),
18959 Scalar::Null(NullKind::NaN),
18960 Scalar::Float64(3.0),
18961 ])
18962 .expect("left");
18963 let right = Column::from_values(vec![
18964 Scalar::Float64(10.0),
18965 Scalar::Float64(20.0),
18966 Scalar::Null(NullKind::NaN),
18967 ])
18968 .expect("right");
18969
18970 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
18971 assert_eq!(result.values()[0], Scalar::Float64(11.0));
18972 assert!(result.values()[1].is_nan(), "null+valid should be NaN");
18973 assert!(result.values()[2].is_nan(), "valid+null should be NaN");
18974 }
18975
18976 #[test]
18977 fn aligned_binary_f64_matches_reindex_then_binary_numeric() {
18978 let left = Column::new(
18979 DType::Float64,
18980 vec![
18981 Scalar::Float64(1.0),
18982 Scalar::Float64(f64::NAN),
18983 Scalar::Float64(3.5),
18984 ],
18985 )
18986 .expect("left");
18987 let right = Column::new(
18988 DType::Float64,
18989 vec![
18990 Scalar::Float64(10.0),
18991 Scalar::Float64(20.0),
18992 Scalar::Null(NullKind::NaN),
18993 ],
18994 )
18995 .expect("right");
18996 let left_positions = [Some(2), None, Some(1), Some(0)];
18997 let right_positions = [None, Some(0), Some(2), Some(1)];
18998
18999 let expected_left = left
19000 .reindex_by_positions(&left_positions)
19001 .expect("left reindex");
19002 let expected_right = right
19003 .reindex_by_positions(&right_positions)
19004 .expect("right reindex");
19005 let expected = expected_left
19006 .binary_numeric(&expected_right, ArithmeticOp::Add)
19007 .expect("generic add");
19008 let actual = left
19009 .aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
19010 .expect("aligned add");
19011
19012 assert_eq!(actual.dtype(), expected.dtype());
19013 assert_eq!(actual.values(), expected.values());
19014 assert_eq!(actual.validity().len(), expected.validity().len());
19015 for idx in 0..actual.len() {
19016 assert_eq!(actual.validity().get(idx), expected.validity().get(idx));
19017 }
19018 }
19019
19020 #[test]
19021 fn aligned_binary_f64_all_valid_keeps_typed_output_lazy() {
19022 let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
19023 let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
19024 let left_positions = [Some(0), Some(1), Some(2)];
19025 let right_positions = [Some(0), Some(1), Some(2)];
19026
19027 let actual = left
19028 .aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
19029 .expect("aligned add");
19030
19031 assert!(actual.validity().all());
19032 assert_eq!(actual.as_f64_slice(), Some([11.0, 22.0, 33.0].as_slice()));
19033 assert!(matches!(
19034 &actual.values,
19035 ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
19036 ));
19037 }
19038
19039 #[test]
19040 fn aligned_binary_f64_nullable_gaps_keep_typed_output_lazy() {
19041 let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
19042 let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
19043 let left_positions = [Some(0), Some(1), Some(2), None];
19044 let right_positions = [None, Some(0), Some(1), Some(2)];
19045
19046 let expected_left = left
19047 .reindex_by_positions(&left_positions)
19048 .expect("left reindex");
19049 let expected_right = right
19050 .reindex_by_positions(&right_positions)
19051 .expect("right reindex");
19052 let expected = expected_left
19053 .binary_numeric(&expected_right, ArithmeticOp::Add)
19054 .expect("generic add");
19055 let actual = left
19056 .aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
19057 .expect("aligned add");
19058
19059 assert_eq!(actual.dtype(), expected.dtype());
19060 assert_eq!(actual.validity(), expected.validity());
19061 assert!(matches!(
19062 &actual.values,
19063 ScalarValues::LazyNullableFloat64 { values, .. } if values.get().is_none()
19064 ));
19065 assert_eq!(actual.values(), expected.values());
19066 }
19067
19068 #[test]
19069 fn aligned_binary_f64_int64_unit_ranges_matches_position_alignment() {
19070 let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
19071 let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
19072 let left_positions = [Some(0), Some(1), Some(2), None];
19073 let right_positions = [None, Some(0), Some(1), Some(2)];
19074
19075 let expected = left
19076 .aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
19077 .expect("position aligned add");
19078 let actual = left
19079 .aligned_binary_f64_int64_unit_ranges(&right, (0, 2), (1, 3), (0, 3), ArithmeticOp::Add)
19080 .expect("unit range aligned add");
19081
19082 assert_eq!(actual.dtype(), expected.dtype());
19083 assert_eq!(actual.validity(), expected.validity());
19084 assert!(matches!(
19085 &actual.values,
19086 ScalarValues::LazyNullableFloat64 { values, .. } if values.get().is_none()
19087 ));
19088 assert_eq!(actual.values(), expected.values());
19089 }
19090
19091 #[test]
19092 fn aligned_binary_f64_operation_nan_keeps_float_nan_materialization() {
19093 let left = Column::from_f64_values(vec![f64::INFINITY]);
19094 let right = Column::from_f64_values(vec![f64::INFINITY]);
19095 let positions = [Some(0)];
19096
19097 let actual = left
19098 .aligned_binary_f64(&right, &positions, &positions, ArithmeticOp::Sub)
19099 .expect("aligned sub");
19100
19101 assert!(!actual.validity().get(0));
19102 assert!(matches!(
19103 &actual.values,
19104 ScalarValues::LazyNullableFloat64 { values, .. } if values.get().is_none()
19105 ));
19106 assert!(matches!(actual.values()[0], Scalar::Float64(value) if value.is_nan()));
19107 }
19108
19109 #[test]
19110 fn apply_f64_slices_matches_fn_pointer_per_element_f64simd() {
19111 let vals = [
19116 0.0_f64,
19117 -0.0,
19118 1.0,
19119 -1.0,
19120 2.5,
19121 -3.0,
19122 4.0,
19123 0.5,
19124 f64::NAN,
19125 f64::INFINITY,
19126 f64::NEG_INFINITY,
19127 1e300,
19128 -1e-300,
19129 ];
19130 let a: Vec<f64> = vals.to_vec();
19131 for op in [
19132 ArithmeticOp::Add,
19133 ArithmeticOp::Sub,
19134 ArithmeticOp::Mul,
19135 ArithmeticOp::Div,
19136 ArithmeticOp::Mod,
19137 ArithmeticOp::Pow,
19138 ArithmeticOp::FloorDiv,
19139 ] {
19140 for shift in 0..vals.len() {
19141 let b: Vec<f64> = (0..vals.len())
19142 .map(|i| vals[(i + shift) % vals.len()])
19143 .collect();
19144 let got = super::apply_f64_slices_nan_tracked(op, &a, &b).0;
19145 let apply = super::binary_f64_apply(op);
19146 let expected: Vec<f64> = a.iter().zip(&b).map(|(x, y)| apply(*x, *y)).collect();
19147 for i in 0..a.len() {
19148 assert_eq!(
19149 got[i].to_bits(),
19150 expected[i].to_bits(),
19151 "op={op:?} a={} b={}",
19152 a[i],
19153 b[i]
19154 );
19155 }
19156 }
19157 }
19158 }
19159
19160 #[test]
19161 fn apply_f64_slices_parallel_matches_serial_nan_tracking() {
19162 let n = (1usize << 20) + 17;
19163 let mut a: Vec<f64> = (0..n).map(|i| i as f64 * 0.25 + 1.0).collect();
19164 let mut b: Vec<f64> = (0..n).map(|i| i as f64 * 0.125 - 7.0).collect();
19165 a[1024] = f64::NAN;
19166 a[n - 3] = f64::INFINITY;
19167 b[n - 3] = f64::INFINITY;
19168
19169 let (got, got_input_nan, got_output_nan) =
19170 super::apply_f64_slices_nan_tracked(ArithmeticOp::Sub, &a, &b);
19171 let mut expected = vec![0.0_f64; n];
19172 let (expected_input_nan, expected_output_nan) =
19173 super::apply_f64_slices_nan_tracked_into(ArithmeticOp::Sub, &a, &b, &mut expected);
19174
19175 assert_eq!(got_input_nan, expected_input_nan);
19176 assert_eq!(got_output_nan, expected_output_nan);
19177 for i in 0..n {
19178 assert_eq!(got[i].to_bits(), expected[i].to_bits(), "i={i}");
19179 }
19180 }
19181
19182 #[test]
19183 fn aligned_binary_f64_same_positions_matches_identity_alignment() {
19184 let left = Column::new(
19185 DType::Float64,
19186 vec![
19187 Scalar::Float64(1.0),
19188 Scalar::Float64(f64::NAN),
19189 Scalar::Float64(3.0),
19190 ],
19191 )
19192 .expect("left");
19193 let right = Column::new(
19194 DType::Float64,
19195 vec![
19196 Scalar::Float64(10.0),
19197 Scalar::Float64(20.0),
19198 Scalar::Null(NullKind::NaN),
19199 ],
19200 )
19201 .expect("right");
19202 let positions = [Some(0), Some(1), Some(2)];
19203
19204 let expected = left
19205 .aligned_binary_f64(&right, &positions, &positions, ArithmeticOp::Add)
19206 .expect("identity aligned add");
19207 let actual = left
19208 .aligned_binary_f64_same_positions(&right, ArithmeticOp::Add)
19209 .expect("same-position add");
19210
19211 assert_eq!(actual.dtype(), expected.dtype());
19212 assert_eq!(actual.values(), expected.values());
19213 for idx in 0..actual.len() {
19214 assert_eq!(actual.validity().get(idx), expected.validity().get(idx));
19215 }
19216 }
19217
19218 #[test]
19219 fn aligned_binary_f64_same_positions_matches_general_path_for_all_ops_with_nan_inf() {
19220 let make = |data: Vec<f64>| -> Column {
19233 let len = data.len();
19234 Column {
19235 dtype: DType::Float64,
19236 values: ScalarValues::lazy_all_valid_float64(data),
19237 validity: ValidityMask::all_valid(len),
19238 data: None,
19239 }
19240 };
19241 let left = make(vec![1.0, f64::NAN, 2.0, f64::INFINITY, 1.0, f64::NAN, -3.5]);
19242 let right = make(vec![10.0, 3.0, f64::NAN, f64::INFINITY, f64::NAN, 0.0, 2.0]);
19243 assert!(left.validity().all());
19244 assert!(right.validity().all());
19245 let n = left.len();
19246 let positions: Vec<Option<usize>> = (0..n).map(Some).collect();
19247
19248 for op in [
19249 ArithmeticOp::Add,
19250 ArithmeticOp::Sub,
19251 ArithmeticOp::Mul,
19252 ArithmeticOp::Div,
19253 ArithmeticOp::Mod,
19254 ArithmeticOp::Pow,
19255 ArithmeticOp::FloorDiv,
19256 ] {
19257 let expected = left
19258 .aligned_binary_f64(&right, &positions, &positions, op)
19259 .expect("general aligned path");
19260 let actual = left
19261 .aligned_binary_f64_same_positions(&right, op)
19262 .expect("same-position fast path");
19263
19264 assert_eq!(actual.dtype(), expected.dtype(), "dtype op={op:?}");
19265 assert_eq!(actual.len(), expected.len(), "len op={op:?}");
19266 let got = actual.values();
19267 let want = expected.values();
19268 for i in 0..n {
19269 match (&got[i], &want[i]) {
19271 (Scalar::Float64(g), Scalar::Float64(w)) => {
19272 assert_eq!(g.to_bits(), w.to_bits(), "value bits op={op:?} slot={i}")
19273 }
19274 (g, w) => assert_eq!(g, w, "scalar op={op:?} slot={i}"),
19275 }
19276 assert_eq!(
19277 actual.validity().get(i),
19278 expected.validity().get(i),
19279 "validity op={op:?} slot={i}"
19280 );
19281 }
19282 }
19283 }
19284
19285 #[test]
19286 fn aligned_binary_f64_borrows_lazy_float64_clone_data() {
19287 let left = Column::from_f64_values(vec![1.0, f64::NAN, 4.0]).clone();
19288 let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]).clone();
19289
19290 assert!(left.data.is_none());
19291 assert!(right.data.is_none());
19292 assert!(matches!(
19293 &left.values,
19294 ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
19295 ));
19296 assert!(matches!(
19297 &right.values,
19298 ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
19299 ));
19300
19301 let left_positions = [Some(0), Some(1), Some(2), None];
19302 let right_positions = [Some(2), Some(1), None, Some(0)];
19303 let actual = left
19304 .aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
19305 .expect("aligned add");
19306
19307 assert_eq!(
19308 actual.values(),
19309 &[
19310 Scalar::Float64(31.0),
19311 Scalar::Null(NullKind::NaN),
19312 Scalar::Null(NullKind::NaN),
19313 Scalar::Null(NullKind::NaN),
19314 ]
19315 );
19316 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &left.values {
19317 assert!(values.get().is_none());
19318 }
19319 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &right.values {
19320 assert!(values.get().is_none());
19321 }
19322 }
19323
19324 #[test]
19325 fn from_f64_values_marks_nan_missing_like_scalar_path() {
19326 let typed = Column::from_f64_values(vec![1.0, f64::NAN, 3.0, f64::NAN]);
19330 let scalar = Column::new(
19331 DType::Float64,
19332 vec![
19333 Scalar::Float64(1.0),
19334 Scalar::Float64(f64::NAN),
19335 Scalar::Float64(3.0),
19336 Scalar::Float64(f64::NAN),
19337 ],
19338 )
19339 .expect("scalar col");
19340
19341 for idx in 0..typed.len() {
19343 assert_eq!(
19344 typed.validity().get(idx),
19345 scalar.validity().get(idx),
19346 "validity mismatch at {idx}"
19347 );
19348 }
19349 assert!(typed.validity().get(0));
19350 assert!(!typed.validity().get(1));
19351 assert!(typed.validity().get(2));
19352 assert!(!typed.validity().get(3));
19353 assert_eq!(typed.validity().count_valid(), 2);
19354
19355 assert!(typed.as_f64_slice().is_none());
19358
19359 let clean = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
19361 assert!(clean.validity().all());
19362 assert_eq!(clean.as_f64_slice(), Some([1.0, 2.0, 3.0].as_slice()));
19363 }
19364
19365 #[test]
19366 fn repeated_slices_float64_exposes_cached_typed_slice() {
19367 let column = Column::from_f64_repeated_slices_shared(
19368 vec![11.0, 22.0, 33.0, 44.0],
19369 Arc::from([(1usize, 2usize), (0, 3), (3, 1)].as_slice()),
19370 6,
19371 );
19372 let expected = [22.0, 33.0, 11.0, 22.0, 33.0, 44.0];
19373
19374 assert_eq!(column.as_f64_slice(), Some(expected.as_slice()));
19375 assert_eq!(column.as_f64_slice(), Some(expected.as_slice()));
19376 assert_eq!(column.all_valid_f64_to_vec(), Some(expected.to_vec()));
19377 assert_eq!(
19378 column.values(),
19379 &[
19380 Scalar::Float64(22.0),
19381 Scalar::Float64(33.0),
19382 Scalar::Float64(11.0),
19383 Scalar::Float64(22.0),
19384 Scalar::Float64(33.0),
19385 Scalar::Float64(44.0),
19386 ]
19387 );
19388 }
19389
19390 #[test]
19391 fn repeated_slices_float64_expands_periodic_prefix() {
19392 let column = Column::from_f64_repeated_slices_shared(
19393 vec![1.0, 2.0, 3.0],
19394 Arc::from([(0usize, 3usize), (0, 3), (0, 2)].as_slice()),
19395 8,
19396 );
19397
19398 assert_eq!(
19399 column.as_f64_slice(),
19400 Some([1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0].as_slice())
19401 );
19402 assert_eq!(
19403 column.all_valid_f64_to_vec(),
19404 Some(vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0])
19405 );
19406 }
19407
19408 #[test]
19409 fn finite_float64_arc_view_uses_constructor_witness() {
19410 let finite = Column::from_values(vec![
19411 Scalar::Float64(1.0),
19412 Scalar::Float64(-0.0),
19413 Scalar::Float64(3.5),
19414 ])
19415 .expect("finite float column");
19416 assert!(
19417 finite.as_f64_finite_arc_view_source(3).is_some(),
19418 "all-finite Float64 columns should expose the finite Arc view"
19419 );
19420 assert!(
19421 finite.clone().as_f64_finite_arc_view_source(3).is_some(),
19422 "finite witness should survive Column::clone"
19423 );
19424
19425 let with_infinity =
19426 Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(f64::INFINITY)])
19427 .expect("infinite float column");
19428 assert!(
19429 with_infinity.as_f64_finite_arc_view_source(2).is_none(),
19430 "infinity is valid Float64 data but must not enter finite dot fast paths"
19431 );
19432
19433 let with_nan = Column::from_f64_values(vec![1.0, f64::NAN]);
19434 assert!(
19435 with_nan.as_f64_finite_arc_view_source(2).is_none(),
19436 "NaN-bearing Float64 columns are nullable and must not expose all-valid views"
19437 );
19438 }
19439
19440 #[test]
19441 fn from_f64_all_valid_chunks_materializes_in_chunk_order() {
19442 let first: Arc<[f64]> = Arc::from(vec![9.0, 1.0, 2.0, 8.0]);
19443 let second: Arc<[f64]> = Arc::from(vec![3.0, 4.0, 5.0]);
19444 let column = Column::from_f64_all_valid_chunks(
19445 vec![(Arc::clone(&first), 1, 2), (Arc::clone(&second), 0, 3)],
19446 5,
19447 );
19448
19449 assert_eq!(column.len(), 5);
19450 assert!(column.validity().all());
19451 assert_eq!(
19452 column.as_f64_slice(),
19453 Some([1.0, 2.0, 3.0, 4.0, 5.0].as_slice())
19454 );
19455 assert_eq!(
19456 column.values(),
19457 &[
19458 Scalar::Float64(1.0),
19459 Scalar::Float64(2.0),
19460 Scalar::Float64(3.0),
19461 Scalar::Float64(4.0),
19462 Scalar::Float64(5.0),
19463 ]
19464 );
19465 }
19466
19467 #[test]
19468 fn from_i64_all_valid_chunks_materializes_in_chunk_order() {
19469 let first: Arc<[i64]> = Arc::from(vec![99, 1, 2, 88]);
19470 let second: Arc<[i64]> = Arc::from(vec![3, 4, 5]);
19471 let column = Column::from_i64_all_valid_chunks(
19472 vec![(Arc::clone(&first), 1, 2), (Arc::clone(&second), 0, 3)],
19473 5,
19474 );
19475
19476 assert_eq!(column.len(), 5);
19477 assert!(column.validity().all());
19478 assert_eq!(column.as_i64_slice(), Some([1, 2, 3, 4, 5].as_slice()));
19479 assert_eq!(
19480 column.values(),
19481 &[
19482 Scalar::Int64(1),
19483 Scalar::Int64(2),
19484 Scalar::Int64(3),
19485 Scalar::Int64(4),
19486 Scalar::Int64(5),
19487 ]
19488 );
19489 assert_eq!(column.clone(), Column::from_i64_values(vec![1, 2, 3, 4, 5]));
19490 }
19491
19492 #[test]
19493 fn from_f64_all_valid_dot_product_materializes_left_fold_rows() {
19494 let a0: Arc<[f64]> = Arc::from(vec![99.0, 1.0, 3.0, 5.0]);
19495 let a1: Arc<[f64]> = Arc::from(vec![2.0, 4.0, 6.0]);
19496 let b: Arc<[f64]> = Arc::from(vec![10.0, 0.5]);
19497 let column = Column::from_f64_all_valid_dot_product(
19498 vec![(Arc::clone(&a0), 1), (Arc::clone(&a1), 0)],
19499 b,
19500 3,
19501 );
19502
19503 assert_eq!(column.len(), 3);
19504 assert!(column.validity().all());
19505 assert_eq!(column.as_f64_slice(), Some([11.0, 32.0, 53.0].as_slice()));
19506 assert_eq!(
19507 column.values(),
19508 &[
19509 Scalar::Float64(11.0),
19510 Scalar::Float64(32.0),
19511 Scalar::Float64(53.0),
19512 ]
19513 );
19514 }
19515
19516 #[test]
19517 fn vectorized_i64_with_nulls_propagates_missing() {
19518 let left = Column::from_values(vec![
19519 Scalar::Int64(1),
19520 Scalar::Null(NullKind::Null),
19521 Scalar::Int64(3),
19522 ])
19523 .expect("left");
19524 let right = Column::from_values(vec![
19525 Scalar::Int64(10),
19526 Scalar::Int64(20),
19527 Scalar::Null(NullKind::Null),
19528 ])
19529 .expect("right");
19530
19531 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
19532 assert_eq!(result.values()[0], Scalar::Int64(11));
19533 assert!(result.values()[1].is_missing());
19534 assert!(result.values()[2].is_missing());
19535 }
19536
19537 #[test]
19538 fn column_from_values_preserves_mixed_utf8_numeric_scalars() {
19539 let column = Column::from_values(vec![Scalar::Utf8("x".into()), Scalar::Int64(1)])
19540 .expect("mixed object-like constructor should succeed");
19541
19542 assert_eq!(column.dtype(), DType::Utf8);
19543 assert_eq!(
19544 column.values(),
19545 &[Scalar::Utf8("x".into()), Scalar::Int64(1)]
19546 );
19547 }
19548
19549 #[test]
19550 fn vectorized_division_promotes_to_float64() {
19551 let left = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(21)]).expect("left");
19552 let right = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(7)]).expect("right");
19553
19554 let result = left.binary_numeric(&right, ArithmeticOp::Div).expect("div");
19555 assert_eq!(result.dtype(), fp_types::DType::Float64);
19557 assert!(matches!(result.values()[0], Scalar::Float64(v) if (v - 10.0/3.0).abs() < 1e-10));
19558 assert_eq!(result.values()[1], Scalar::Float64(3.0));
19559 }
19560
19561 #[test]
19562 fn vectorized_all_four_ops_f64() {
19563 let left = Column::from_values(vec![Scalar::Float64(10.0)]).expect("left");
19564 let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
19565
19566 let add = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
19567 let sub = left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub");
19568 let mul = left.binary_numeric(&right, ArithmeticOp::Mul).expect("mul");
19569 let div = left.binary_numeric(&right, ArithmeticOp::Div).expect("div");
19570
19571 assert_eq!(add.values()[0], Scalar::Float64(13.0));
19572 assert_eq!(sub.values()[0], Scalar::Float64(7.0));
19573 assert_eq!(mul.values()[0], Scalar::Float64(30.0));
19574 assert!(matches!(div.values()[0], Scalar::Float64(v) if (v - 10.0/3.0).abs() < 1e-10));
19575 }
19576
19577 #[test]
19578 fn pandas_arithmetic_aliases_match_binary_numeric() {
19579 let left = Column::from_values(vec![Scalar::Float64(10.0)]).expect("left");
19580 let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
19581
19582 assert_eq!(
19583 left.add(&right).expect("add"),
19584 left.binary_numeric(&right, ArithmeticOp::Add).expect("add")
19585 );
19586 assert_eq!(
19587 left.sub(&right).expect("sub"),
19588 left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub")
19589 );
19590 assert_eq!(
19591 left.mul(&right).expect("mul"),
19592 left.binary_numeric(&right, ArithmeticOp::Mul).expect("mul")
19593 );
19594 assert_eq!(
19595 left.div(&right).expect("div"),
19596 left.binary_numeric(&right, ArithmeticOp::Div).expect("div")
19597 );
19598 assert_eq!(
19599 left.divide(&right).expect("divide"),
19600 left.div(&right).expect("div")
19601 );
19602 }
19603
19604 #[test]
19605 fn remaining_pandas_arithmetic_aliases_match_binary_numeric() {
19606 let left = Column::from_values(vec![Scalar::Float64(10.0)]).expect("left");
19607 let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
19608
19609 assert_eq!(
19610 left.subtract(&right).expect("subtract"),
19611 left.sub(&right).expect("sub")
19612 );
19613 assert_eq!(
19614 left.multiply(&right).expect("multiply"),
19615 left.mul(&right).expect("mul")
19616 );
19617 assert_eq!(
19618 left.truediv(&right).expect("truediv"),
19619 left.div(&right).expect("div")
19620 );
19621 assert_eq!(
19622 left.floordiv(&right).expect("floordiv"),
19623 left.binary_numeric(&right, ArithmeticOp::FloorDiv)
19624 .expect("floordiv")
19625 );
19626 assert_eq!(
19627 left.r#mod(&right).expect("mod"),
19628 left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod")
19629 );
19630 assert_eq!(
19631 left.pow(&right).expect("pow"),
19632 left.binary_numeric(&right, ArithmeticOp::Pow).expect("pow")
19633 );
19634 }
19635
19636 #[test]
19637 fn pandas_reverse_arithmetic_aliases_swap_operands() {
19638 let series = Column::from_values(vec![Scalar::Float64(10.0)]).expect("series");
19639 let other = Column::from_values(vec![Scalar::Float64(3.0)]).expect("other");
19640
19641 assert_eq!(
19642 series.radd(&other).expect("radd"),
19643 other
19644 .binary_numeric(&series, ArithmeticOp::Add)
19645 .expect("add")
19646 );
19647 assert_eq!(
19648 series.rsub(&other).expect("rsub"),
19649 other
19650 .binary_numeric(&series, ArithmeticOp::Sub)
19651 .expect("sub")
19652 );
19653 assert_eq!(
19654 series.rmul(&other).expect("rmul"),
19655 other
19656 .binary_numeric(&series, ArithmeticOp::Mul)
19657 .expect("mul")
19658 );
19659 assert_eq!(
19660 series.rdiv(&other).expect("rdiv"),
19661 other
19662 .binary_numeric(&series, ArithmeticOp::Div)
19663 .expect("div")
19664 );
19665 assert_eq!(
19666 series.rtruediv(&other).expect("rtruediv"),
19667 series.rdiv(&other).expect("rdiv")
19668 );
19669 assert_eq!(
19670 series.rfloordiv(&other).expect("rfloordiv"),
19671 other
19672 .binary_numeric(&series, ArithmeticOp::FloorDiv)
19673 .expect("floordiv")
19674 );
19675 assert_eq!(
19676 series.rmod(&other).expect("rmod"),
19677 other
19678 .binary_numeric(&series, ArithmeticOp::Mod)
19679 .expect("mod")
19680 );
19681 assert_eq!(
19682 series.rpow(&other).expect("rpow"),
19683 other
19684 .binary_numeric(&series, ArithmeticOp::Pow)
19685 .expect("pow")
19686 );
19687 }
19688
19689 #[test]
19690 fn vectorized_f64_mod_pow_floordiv() {
19691 let left = Column::from_values(vec![
19692 Scalar::Float64(10.0),
19693 Scalar::Float64(2.0),
19694 Scalar::Float64(-3.0),
19695 ])
19696 .expect("left");
19697 let right = Column::from_values(vec![
19698 Scalar::Float64(3.0),
19699 Scalar::Float64(3.0),
19700 Scalar::Float64(2.0),
19701 ])
19702 .expect("right");
19703
19704 let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
19705 assert_eq!(modulo.dtype(), DType::Float64);
19706 assert!(matches!(modulo.values()[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
19707 assert!(matches!(modulo.values()[1], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
19708 assert!(matches!(modulo.values()[2], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
19709
19710 let pow = left.binary_numeric(&right, ArithmeticOp::Pow).expect("pow");
19711 assert_eq!(pow.dtype(), DType::Float64);
19712 assert!(matches!(pow.values()[0], Scalar::Float64(v) if (v - 1000.0).abs() < 1e-10));
19713 assert!(matches!(pow.values()[1], Scalar::Float64(v) if (v - 8.0).abs() < 1e-10));
19714 assert!(matches!(pow.values()[2], Scalar::Float64(v) if (v - 9.0).abs() < 1e-10));
19715
19716 let floordiv = left
19717 .binary_numeric(&right, ArithmeticOp::FloorDiv)
19718 .expect("floordiv");
19719 assert_eq!(floordiv.dtype(), DType::Float64);
19720 assert!(matches!(floordiv.values()[0], Scalar::Float64(v) if (v - 3.0).abs() < 1e-10));
19721 assert!(matches!(floordiv.values()[1], Scalar::Float64(v) if (v - 0.0).abs() < 1e-10));
19722 assert!(matches!(floordiv.values()[2], Scalar::Float64(v) if (v - -2.0).abs() < 1e-10));
19723 }
19724
19725 #[test]
19726 fn int_pow_stays_int64_and_negative_exponent_raises_3w0xn() {
19727 let base = Column::from_values(vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(10)])
19730 .expect("base");
19731 let exp = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(2), Scalar::Int64(2)])
19732 .expect("exp");
19733 let pow = base
19734 .binary_numeric(&exp, ArithmeticOp::Pow)
19735 .expect("int pow");
19736 assert_eq!(pow.dtype(), DType::Int64);
19737 assert_eq!(pow.values()[0], Scalar::Int64(8));
19738 assert_eq!(pow.values()[1], Scalar::Int64(9));
19739 assert_eq!(pow.values()[2], Scalar::Int64(100));
19740
19741 let neg_exp =
19743 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(-1), Scalar::Int64(2)])
19744 .expect("neg_exp");
19745 let err = base
19746 .binary_numeric(&neg_exp, ArithmeticOp::Pow)
19747 .expect_err("negative integer power must raise");
19748 assert!(matches!(err, ColumnError::NegativeIntegerPower));
19749
19750 let exp_f = Column::from_values(vec![
19752 Scalar::Float64(3.0),
19753 Scalar::Float64(2.0),
19754 Scalar::Float64(2.0),
19755 ])
19756 .expect("exp_f");
19757 let pow_f = base
19758 .binary_numeric(&exp_f, ArithmeticOp::Pow)
19759 .expect("mixed int/float pow");
19760 assert_eq!(pow_f.dtype(), DType::Float64);
19761 assert!(matches!(pow_f.values()[0], Scalar::Float64(v) if (v - 8.0).abs() < 1e-10));
19762 }
19763
19764 #[test]
19765 fn int64_mod_floordiv_preserves_dtype() {
19766 let left = Column::from_values(vec![
19768 Scalar::Int64(10),
19769 Scalar::Int64(20),
19770 Scalar::Int64(30),
19771 ])
19772 .expect("left");
19773 let right = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(7), Scalar::Int64(4)])
19774 .expect("right");
19775
19776 let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
19777 assert_eq!(modulo.dtype(), DType::Int64, "mod should preserve Int64");
19778 assert_eq!(modulo.values()[0], Scalar::Int64(1));
19779 assert_eq!(modulo.values()[1], Scalar::Int64(6));
19780 assert_eq!(modulo.values()[2], Scalar::Int64(2));
19781
19782 let floordiv = left
19783 .binary_numeric(&right, ArithmeticOp::FloorDiv)
19784 .expect("floordiv");
19785 assert_eq!(
19786 floordiv.dtype(),
19787 DType::Int64,
19788 "floordiv should preserve Int64"
19789 );
19790 assert_eq!(floordiv.values()[0], Scalar::Int64(3));
19791 assert_eq!(floordiv.values()[1], Scalar::Int64(2));
19792 assert_eq!(floordiv.values()[2], Scalar::Int64(7));
19793 }
19794
19795 #[test]
19796 fn int64_mod_floordiv_match_pandas_negative_operand_signs() {
19797 let left = Column::from_values(vec![
19798 Scalar::Int64(7),
19799 Scalar::Int64(-7),
19800 Scalar::Int64(-7),
19801 Scalar::Int64(7),
19802 ])
19803 .expect("left");
19804 let right = Column::from_values(vec![
19805 Scalar::Int64(-3),
19806 Scalar::Int64(3),
19807 Scalar::Int64(-3),
19808 Scalar::Int64(3),
19809 ])
19810 .expect("right");
19811
19812 let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
19813 assert_eq!(modulo.dtype(), DType::Int64);
19814 assert_eq!(
19815 modulo.values(),
19816 &[
19817 Scalar::Int64(-2),
19818 Scalar::Int64(2),
19819 Scalar::Int64(-1),
19820 Scalar::Int64(1)
19821 ]
19822 );
19823
19824 let floordiv = left
19825 .binary_numeric(&right, ArithmeticOp::FloorDiv)
19826 .expect("floordiv");
19827 assert_eq!(floordiv.dtype(), DType::Int64);
19828 assert_eq!(
19829 floordiv.values(),
19830 &[
19831 Scalar::Int64(-3),
19832 Scalar::Int64(-3),
19833 Scalar::Int64(2),
19834 Scalar::Int64(2)
19835 ]
19836 );
19837 }
19838
19839 #[test]
19840 fn float64_mod_floordiv_match_pandas_negative_operand_signs() {
19841 let left = Column::from_values(vec![
19842 Scalar::Float64(7.0),
19843 Scalar::Float64(-7.0),
19844 Scalar::Float64(-7.0),
19845 Scalar::Float64(7.0),
19846 ])
19847 .expect("left");
19848 let right = Column::from_values(vec![
19849 Scalar::Float64(-3.0),
19850 Scalar::Float64(3.0),
19851 Scalar::Float64(-3.0),
19852 Scalar::Float64(3.0),
19853 ])
19854 .expect("right");
19855
19856 let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
19857 assert_eq!(modulo.dtype(), DType::Float64);
19858 assert!(matches!(modulo.values()[0], Scalar::Float64(v) if (v + 2.0).abs() < 1e-10));
19859 assert!(matches!(modulo.values()[1], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
19860 assert!(matches!(modulo.values()[2], Scalar::Float64(v) if (v + 1.0).abs() < 1e-10));
19861 assert!(matches!(modulo.values()[3], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
19862
19863 let floordiv = left
19864 .binary_numeric(&right, ArithmeticOp::FloorDiv)
19865 .expect("floordiv");
19866 assert_eq!(floordiv.dtype(), DType::Float64);
19867 assert!(matches!(floordiv.values()[0], Scalar::Float64(v) if (v + 3.0).abs() < 1e-10));
19868 assert!(matches!(floordiv.values()[1], Scalar::Float64(v) if (v + 3.0).abs() < 1e-10));
19869 assert!(matches!(floordiv.values()[2], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
19870 assert!(matches!(floordiv.values()[3], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
19871 }
19872
19873 #[test]
19874 fn int64_mod_floordiv_with_zero_promotes_to_float() {
19875 let left = Column::from_values(vec![
19877 Scalar::Int64(10),
19878 Scalar::Int64(20),
19879 Scalar::Int64(30),
19880 ])
19881 .expect("left");
19882 let right = Column::from_values(vec![
19883 Scalar::Int64(3),
19884 Scalar::Int64(0), Scalar::Int64(4),
19886 ])
19887 .expect("right");
19888
19889 let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
19890 assert_eq!(
19891 modulo.dtype(),
19892 DType::Float64,
19893 "mod with zero should promote to Float64"
19894 );
19895 assert!(matches!(modulo.values()[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
19896 assert!(matches!(modulo.values()[1], Scalar::Float64(v) if v.is_nan()));
19897 assert!(matches!(modulo.values()[2], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
19898
19899 let floordiv = left
19900 .binary_numeric(&right, ArithmeticOp::FloorDiv)
19901 .expect("floordiv");
19902 assert_eq!(
19903 floordiv.dtype(),
19904 DType::Float64,
19905 "floordiv with zero should promote to Float64"
19906 );
19907 assert!(matches!(floordiv.values()[0], Scalar::Float64(v) if (v - 3.0).abs() < 1e-10));
19908 assert!(matches!(floordiv.values()[1], Scalar::Float64(v) if v.is_infinite()));
19909 assert!(matches!(floordiv.values()[2], Scalar::Float64(v) if (v - 7.0).abs() < 1e-10));
19910 }
19911
19912 #[test]
19913 fn vectorized_empty_columns() {
19914 let left = Column::from_values(vec![]).expect("left");
19915 let right = Column::from_values(vec![]).expect("right");
19916 let result = left
19917 .binary_numeric(&right, ArithmeticOp::Add)
19918 .expect("add empty");
19919 assert!(result.is_empty());
19920 }
19921
19922 #[test]
19923 fn vectorized_large_column_matches_scalar_semantics() {
19924 let n = 4096;
19926 let left_values: Vec<Scalar> = (0..n).map(|i| Scalar::Float64(i as f64)).collect();
19927 let right_values: Vec<Scalar> = (0..n).map(|i| Scalar::Float64((n - i) as f64)).collect();
19928
19929 let left = Column::from_values(left_values).expect("left");
19930 let right = Column::from_values(right_values).expect("right");
19931
19932 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
19933
19934 for (i, v) in result.values().iter().enumerate() {
19936 assert_eq!(*v, Scalar::Float64(n as f64), "position {i} should be {n}");
19937 }
19938 }
19939
19940 #[test]
19941 fn vectorized_nan_vs_null_distinction_preserved() {
19942 let left =
19944 Column::from_values(vec![Scalar::Float64(f64::NAN), Scalar::Null(NullKind::NaN)])
19945 .expect("left");
19946 let right =
19947 Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("right");
19948
19949 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
19950 assert!(result.values()[0].is_nan(), "NaN + valid = NaN");
19952 assert!(result.values()[1].is_nan(), "NaN-null + valid = NaN");
19953 }
19954
19955 #[test]
19956 fn vectorized_mixed_type_falls_back_to_scalar() {
19957 let left = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("left");
19959 let right =
19960 Column::from_values(vec![Scalar::Float64(0.5), Scalar::Float64(1.5)]).expect("right");
19961
19962 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
19963 assert_eq!(result.dtype(), fp_types::DType::Float64);
19964 assert_eq!(result.values()[0], Scalar::Float64(1.5));
19965 assert_eq!(result.values()[1], Scalar::Float64(3.5));
19966 }
19967
19968 #[test]
19969 fn vectorized_i64_sub_and_mul() {
19970 let left = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("left");
19971 let right = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(5)]).expect("right");
19972
19973 let sub = left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub");
19974 assert_eq!(sub.values()[0], Scalar::Int64(7));
19975 assert_eq!(sub.values()[1], Scalar::Int64(15));
19976
19977 let mul = left.binary_numeric(&right, ArithmeticOp::Mul).expect("mul");
19978 assert_eq!(mul.values()[0], Scalar::Int64(30));
19979 assert_eq!(mul.values()[1], Scalar::Int64(100));
19980 }
19981
19982 mod crack_tests {
19985 use fp_types::Scalar;
19986
19987 use super::super::*;
19988
19989 fn make_column(values: &[f64]) -> Column {
19990 Column::from_values(values.iter().map(|&v| Scalar::Float64(v)).collect()).expect("col")
19991 }
19992
19993 #[test]
19994 fn crack_filter_gt_basic() {
19995 let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
19996 let mut crack = CrackIndex::new(col.len());
19997
19998 let gt3 = crack.filter_gt(&col, 3.0);
19999 let mut gt3_vals: Vec<f64> = gt3
20000 .iter()
20001 .map(|&i| col.values()[i].to_f64().unwrap())
20002 .collect();
20003 gt3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
20004 assert_eq!(gt3_vals, vec![5.0, 7.0]);
20005 assert_eq!(crack.num_cracks(), 1);
20006 }
20007
20008 #[test]
20009 fn crack_filter_lte_basic() {
20010 let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
20011 let mut crack = CrackIndex::new(col.len());
20012
20013 let lte3 = crack.filter_lte(&col, 3.0);
20014 let mut lte3_vals: Vec<f64> = lte3
20015 .iter()
20016 .map(|&i| col.values()[i].to_f64().unwrap())
20017 .collect();
20018 lte3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
20019 assert_eq!(lte3_vals, vec![1.0, 2.0, 3.0]);
20020 }
20021
20022 #[test]
20023 fn crack_filter_eq() {
20024 let col = make_column(&[1.0, 3.0, 3.0, 7.0, 3.0]);
20025 let mut crack = CrackIndex::new(col.len());
20026
20027 let eq3 = crack.filter_eq(&col, 3.0);
20028 assert_eq!(eq3.len(), 3, "three values equal to 3.0");
20029 for &idx in &eq3 {
20030 assert_eq!(col.values()[idx].to_f64().unwrap(), 3.0);
20031 }
20032 }
20033
20034 #[test]
20035 fn crack_filter_lt() {
20036 let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
20037 let mut crack = CrackIndex::new(col.len());
20038
20039 let lt3 = crack.filter_lt(&col, 3.0);
20040 let mut lt3_vals: Vec<f64> = lt3
20041 .iter()
20042 .map(|&i| col.values()[i].to_f64().unwrap())
20043 .collect();
20044 lt3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
20045 assert_eq!(lt3_vals, vec![1.0, 2.0]);
20046 }
20047
20048 #[test]
20049 fn crack_filter_gte() {
20050 let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
20051 let mut crack = CrackIndex::new(col.len());
20052
20053 let gte3 = crack.filter_gte(&col, 3.0);
20054 let mut gte3_vals: Vec<f64> = gte3
20055 .iter()
20056 .map(|&i| col.values()[i].to_f64().unwrap())
20057 .collect();
20058 gte3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
20059 assert_eq!(gte3_vals, vec![3.0, 5.0, 7.0]);
20060 }
20061
20062 #[test]
20063 fn crack_progressive_refinement() {
20064 let col = make_column(&[10.0, 2.0, 8.0, 4.0, 6.0, 1.0, 9.0, 3.0, 7.0, 5.0]);
20065 let mut crack = CrackIndex::new(col.len());
20066
20067 let gt5 = crack.filter_gt(&col, 5.0);
20069 assert_eq!(gt5.len(), 5);
20070 assert_eq!(crack.num_cracks(), 1);
20071
20072 let gt3 = crack.filter_gt(&col, 3.0);
20074 assert_eq!(gt3.len(), 7); assert_eq!(crack.num_cracks(), 2);
20076
20077 let gt7 = crack.filter_gt(&col, 7.0);
20079 assert_eq!(gt7.len(), 3); assert_eq!(crack.num_cracks(), 3);
20081 }
20082
20083 #[test]
20084 fn crack_duplicate_crack_point_is_idempotent() {
20085 let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
20086 let mut crack = CrackIndex::new(col.len());
20087
20088 let gt3_first = crack.filter_gt(&col, 3.0);
20089 let gt3_second = crack.filter_gt(&col, 3.0);
20090
20091 let mut a: Vec<usize> = gt3_first;
20093 let mut b: Vec<usize> = gt3_second;
20094 a.sort_unstable();
20095 b.sort_unstable();
20096 assert_eq!(a, b);
20097 assert_eq!(crack.num_cracks(), 1, "no duplicate crack point");
20098 }
20099
20100 #[test]
20101 fn crack_empty_column() {
20102 let col = make_column(&[]);
20103 let mut crack = CrackIndex::new(col.len());
20104
20105 assert!(crack.filter_gt(&col, 5.0).is_empty());
20106 assert!(crack.filter_lte(&col, 5.0).is_empty());
20107 }
20108
20109 #[test]
20110 fn crack_single_element() {
20111 let col = make_column(&[42.0]);
20112 let mut crack = CrackIndex::new(col.len());
20113
20114 assert!(crack.filter_gt(&col, 42.0).is_empty());
20115 assert_eq!(crack.filter_lte(&col, 42.0).len(), 1);
20116 assert_eq!(crack.filter_eq(&col, 42.0).len(), 1);
20117 }
20118
20119 #[test]
20120 fn crack_all_same_values() {
20121 let col = make_column(&[5.0, 5.0, 5.0, 5.0]);
20122 let mut crack = CrackIndex::new(col.len());
20123
20124 assert!(crack.filter_gt(&col, 5.0).is_empty());
20125 assert_eq!(crack.filter_lte(&col, 5.0).len(), 4);
20126 assert_eq!(crack.filter_eq(&col, 5.0).len(), 4);
20127 }
20128
20129 #[test]
20130 fn crack_isomorphism_with_full_scan() {
20131 let col = make_column(&[10.0, 2.0, 8.0, 4.0, 6.0, 1.0, 9.0, 3.0, 7.0, 5.0]);
20133 let mut crack = CrackIndex::new(col.len());
20134
20135 for pivot in [1.0, 3.0, 5.0, 7.0, 9.0, 0.0, 11.0] {
20136 let mut cracked: Vec<usize> = crack.filter_gt(&col, pivot);
20137 cracked.sort_unstable();
20138
20139 let mut naive: Vec<usize> = (0..col.len())
20140 .filter(|&i| col.values()[i].to_f64().unwrap() > pivot)
20141 .collect();
20142 naive.sort_unstable();
20143
20144 assert_eq!(
20145 cracked, naive,
20146 "cracked vs naive mismatch for pivot={pivot}"
20147 );
20148 }
20149 }
20150
20151 #[test]
20152 fn crack_int64_column() {
20153 let col = Column::from_values(vec![
20154 Scalar::Int64(10),
20155 Scalar::Int64(5),
20156 Scalar::Int64(3),
20157 Scalar::Int64(8),
20158 Scalar::Int64(1),
20159 ])
20160 .expect("col");
20161 let mut crack = CrackIndex::new(col.len());
20162
20163 let gt5 = crack.filter_gt(&col, 5.0);
20164 let mut gt5_vals: Vec<i64> = gt5
20165 .iter()
20166 .filter_map(|&i| match &col.values()[i] {
20167 Scalar::Int64(v) => Some(*v),
20168 _ => None,
20169 })
20170 .collect();
20171 assert_eq!(gt5_vals.len(), gt5.len(), "expected Int64 values");
20172 gt5_vals.sort_unstable();
20173 assert_eq!(gt5_vals, vec![8, 10]);
20174 }
20175
20176 #[test]
20177 fn crack_large_column_correctness() {
20178 let n = 1000;
20179 let values: Vec<f64> = (0..n).map(|i| ((i * 7 + 13) % n) as f64).collect();
20180 let col = make_column(&values);
20181 let mut crack = CrackIndex::new(col.len());
20182
20183 for pivot in [100.0, 500.0, 250.0, 750.0, 50.0, 900.0] {
20185 let mut cracked: Vec<usize> = crack.filter_gt(&col, pivot);
20186 cracked.sort_unstable();
20187
20188 let mut naive: Vec<usize> =
20189 (0..n as usize).filter(|&i| values[i] > pivot).collect();
20190 naive.sort_unstable();
20191
20192 assert_eq!(cracked, naive, "large column mismatch for pivot={pivot}");
20193 }
20194 }
20195 }
20196
20197 mod comparison_tests {
20200 use fp_types::{NullKind, Scalar};
20201
20202 use super::super::*;
20203
20204 #[test]
20205 fn comparison_gt_int64() {
20206 let left =
20207 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(3)])
20208 .expect("left");
20209 let right =
20210 Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(3), Scalar::Int64(3)])
20211 .expect("right");
20212
20213 let result = left
20214 .binary_comparison(&right, ComparisonOp::Gt)
20215 .expect("gt");
20216 assert_eq!(result.dtype(), fp_types::DType::Bool);
20217 assert_eq!(result.values()[0], Scalar::Bool(false));
20218 assert_eq!(result.values()[1], Scalar::Bool(true));
20219 assert_eq!(result.values()[2], Scalar::Bool(false));
20220 }
20221
20222 #[test]
20223 fn comparison_all_ops_numeric() {
20224 let left = Column::from_values(vec![Scalar::Float64(5.0)]).expect("left");
20225 let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
20226
20227 let gt = left
20228 .binary_comparison(&right, ComparisonOp::Gt)
20229 .expect("gt");
20230 let lt = left
20231 .binary_comparison(&right, ComparisonOp::Lt)
20232 .expect("lt");
20233 let eq = left
20234 .binary_comparison(&right, ComparisonOp::Eq)
20235 .expect("eq");
20236 let ne = left
20237 .binary_comparison(&right, ComparisonOp::Ne)
20238 .expect("ne");
20239 let ge = left
20240 .binary_comparison(&right, ComparisonOp::Ge)
20241 .expect("ge");
20242 let le = left
20243 .binary_comparison(&right, ComparisonOp::Le)
20244 .expect("le");
20245
20246 assert_eq!(gt.values()[0], Scalar::Bool(true));
20247 assert_eq!(lt.values()[0], Scalar::Bool(false));
20248 assert_eq!(eq.values()[0], Scalar::Bool(false));
20249 assert_eq!(ne.values()[0], Scalar::Bool(true));
20250 assert_eq!(ge.values()[0], Scalar::Bool(true));
20251 assert_eq!(le.values()[0], Scalar::Bool(false));
20252 }
20253
20254 #[test]
20255 fn pandas_comparison_aliases_match_binary_comparison() {
20256 let left = Column::from_values(vec![Scalar::Float64(5.0)]).expect("left");
20257 let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
20258
20259 assert_eq!(
20260 left.eq(&right).expect("eq"),
20261 left.binary_comparison(&right, ComparisonOp::Eq)
20262 .expect("eq")
20263 );
20264 assert_eq!(
20265 left.ne(&right).expect("ne"),
20266 left.binary_comparison(&right, ComparisonOp::Ne)
20267 .expect("ne")
20268 );
20269 assert_eq!(
20270 left.lt(&right).expect("lt"),
20271 left.binary_comparison(&right, ComparisonOp::Lt)
20272 .expect("lt")
20273 );
20274 assert_eq!(
20275 left.le(&right).expect("le"),
20276 left.binary_comparison(&right, ComparisonOp::Le)
20277 .expect("le")
20278 );
20279 assert_eq!(
20280 left.gt(&right).expect("gt"),
20281 left.binary_comparison(&right, ComparisonOp::Gt)
20282 .expect("gt")
20283 );
20284 assert_eq!(
20285 left.ge(&right).expect("ge"),
20286 left.binary_comparison(&right, ComparisonOp::Ge)
20287 .expect("ge")
20288 );
20289 }
20290
20291 #[test]
20292 fn comparison_equality_equal_values() {
20293 let col = Column::from_values(vec![Scalar::Int64(42)]).expect("col");
20294 let result = col.binary_comparison(&col, ComparisonOp::Eq).expect("eq");
20295 assert_eq!(result.values()[0], Scalar::Bool(true));
20296
20297 let ne = col.binary_comparison(&col, ComparisonOp::Ne).expect("ne");
20298 assert_eq!(ne.values()[0], Scalar::Bool(false));
20299 }
20300
20301 #[test]
20302 fn comparison_null_propagation() {
20303 let left = Column::from_values(vec![
20304 Scalar::Int64(1),
20305 Scalar::Null(NullKind::Null),
20306 Scalar::Int64(3),
20307 ])
20308 .expect("left");
20309 let right = Column::from_values(vec![
20310 Scalar::Int64(2),
20311 Scalar::Int64(2),
20312 Scalar::Null(NullKind::Null),
20313 ])
20314 .expect("right");
20315
20316 let result = left
20317 .binary_comparison(&right, ComparisonOp::Gt)
20318 .expect("gt");
20319 assert_eq!(result.values()[0], Scalar::Bool(false));
20320 assert!(result.values()[1].is_missing(), "null op valid = null");
20321 assert!(result.values()[2].is_missing(), "valid op null = null");
20322 }
20323
20324 #[test]
20325 fn comparison_utf8_lexicographic() {
20326 let left = Column::from_values(vec![
20327 Scalar::Utf8("banana".to_string()),
20328 Scalar::Utf8("apple".to_string()),
20329 ])
20330 .expect("left");
20331 let right = Column::from_values(vec![
20332 Scalar::Utf8("apple".to_string()),
20333 Scalar::Utf8("cherry".to_string()),
20334 ])
20335 .expect("right");
20336
20337 let gt = left
20338 .binary_comparison(&right, ComparisonOp::Gt)
20339 .expect("gt");
20340 assert_eq!(gt.values()[0], Scalar::Bool(true));
20341 assert_eq!(gt.values()[1], Scalar::Bool(false));
20342 }
20343
20344 #[test]
20345 fn compare_scalar_gt() {
20346 let col = Column::from_values(vec![
20347 Scalar::Int64(1),
20348 Scalar::Int64(5),
20349 Scalar::Null(NullKind::Null),
20350 Scalar::Int64(3),
20351 ])
20352 .expect("col");
20353
20354 let result = col
20355 .compare_scalar(&Scalar::Int64(3), ComparisonOp::Gt)
20356 .expect("gt");
20357 assert_eq!(result.values()[0], Scalar::Bool(false));
20358 assert_eq!(result.values()[1], Scalar::Bool(true));
20359 assert!(result.values()[2].is_missing());
20360 assert_eq!(result.values()[3], Scalar::Bool(false));
20361 }
20362
20363 #[test]
20364 fn compare_scalar_with_missing_scalar() {
20365 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
20366
20367 let result = col
20368 .compare_scalar(&Scalar::Null(NullKind::Null), ComparisonOp::Eq)
20369 .expect("eq");
20370 assert!(result.values()[0].is_missing());
20371 assert!(result.values()[1].is_missing());
20372 }
20373
20374 #[test]
20375 fn filter_by_mask_basic() {
20376 let col = Column::from_values(vec![
20377 Scalar::Int64(10),
20378 Scalar::Int64(20),
20379 Scalar::Int64(30),
20380 Scalar::Int64(40),
20381 ])
20382 .expect("col");
20383 let mask = Column::from_values(vec![
20384 Scalar::Bool(true),
20385 Scalar::Bool(false),
20386 Scalar::Bool(true),
20387 Scalar::Bool(false),
20388 ])
20389 .expect("mask");
20390
20391 let result = col.filter_by_mask(&mask).expect("filter");
20392 assert_eq!(result.len(), 2);
20393 assert_eq!(result.values()[0], Scalar::Int64(10));
20394 assert_eq!(result.values()[1], Scalar::Int64(30));
20395 }
20396
20397 #[test]
20398 fn filter_by_mask_float64_typed_path_matches_scalar() {
20399 let col = Column::from_f64_values(vec![1.5, -0.0, 2.5, f64::INFINITY, 0.0]);
20403 let mask = Column::from_values(vec![
20404 Scalar::Bool(true),
20405 Scalar::Bool(true),
20406 Scalar::Bool(false),
20407 Scalar::Bool(true),
20408 Scalar::Null(NullKind::Null), ])
20410 .expect("mask");
20411 let result = col.filter_by_mask(&mask).expect("filter");
20412 assert_eq!(result.dtype(), DType::Float64);
20413 assert_eq!(
20414 result.values(),
20415 &[
20416 Scalar::Float64(1.5),
20417 Scalar::Float64(-0.0),
20418 Scalar::Float64(f64::INFINITY),
20419 ]
20420 );
20421 }
20422
20423 #[test]
20424 fn compare_scalar_typed_path_matches_scalar_compare() {
20425 let f64_vals = vec![1.5f64, -0.0, 0.0, 2.5, -3.0, f64::INFINITY, 100.0];
20429 let i64_vals = vec![1i64, -2, 0, 5, 100, -7];
20430 let ops = [
20431 ComparisonOp::Gt,
20432 ComparisonOp::Lt,
20433 ComparisonOp::Eq,
20434 ComparisonOp::Ne,
20435 ComparisonOp::Ge,
20436 ComparisonOp::Le,
20437 ];
20438 for op in ops {
20439 for &probe in &[0.0f64, 1.5, 2.5, -3.0, f64::INFINITY] {
20441 let got = Column::from_f64_values(f64_vals.clone())
20442 .compare_scalar(&Scalar::Float64(probe), op)
20443 .expect("f64 cmp");
20444 let expected: Vec<Scalar> = f64_vals
20445 .iter()
20446 .map(|&v| {
20447 Scalar::Bool(
20448 scalar_compare(&Scalar::Float64(v), &Scalar::Float64(probe), op)
20449 .unwrap(),
20450 )
20451 })
20452 .collect();
20453 assert_eq!(
20454 got.values(),
20455 expected.as_slice(),
20456 "f64 op {op:?} probe {probe}"
20457 );
20458 }
20459 let got = Column::from_f64_values(f64_vals.clone())
20461 .compare_scalar(&Scalar::Int64(2), op)
20462 .expect("f64-vs-i64 cmp");
20463 let expected: Vec<Scalar> = f64_vals
20464 .iter()
20465 .map(|&v| {
20466 Scalar::Bool(
20467 scalar_compare(&Scalar::Float64(v), &Scalar::Int64(2), op).unwrap(),
20468 )
20469 })
20470 .collect();
20471 assert_eq!(got.values(), expected.as_slice(), "f64-vs-i64 op {op:?}");
20472 let got = Column::from_i64_values(i64_vals.clone())
20474 .compare_scalar(&Scalar::Int64(0), op)
20475 .expect("i64 cmp");
20476 let expected: Vec<Scalar> = i64_vals
20477 .iter()
20478 .map(|&v| {
20479 Scalar::Bool(
20480 scalar_compare(&Scalar::Int64(v), &Scalar::Int64(0), op).unwrap(),
20481 )
20482 })
20483 .collect();
20484 assert_eq!(got.values(), expected.as_slice(), "i64 op {op:?}");
20485 }
20486 }
20487
20488 #[test]
20489 #[ignore = "perf timing harness, run with --ignored"]
20490 fn compare_scalar_typed_vs_aos_timing() {
20491 use std::time::Instant;
20492 let n = 5_000_000usize;
20493 let raw: Vec<f64> = (0..n).map(|i| (i % 1000) as f64 - 500.0).collect();
20494 let scalars: Vec<Scalar> = raw.iter().map(|&v| Scalar::Float64(v)).collect();
20495 let probe = Scalar::Float64(0.0);
20496 let op = ComparisonOp::Gt;
20497
20498 let t = Instant::now();
20500 let aos: Vec<Scalar> = scalars
20501 .iter()
20502 .map(|v| Scalar::Bool(scalar_compare(v, &probe, op).unwrap()))
20503 .collect();
20504 let aos_ns = t.elapsed().as_nanos();
20505 std::hint::black_box(&aos);
20506
20507 let col = Column::from_f64_values(raw.clone());
20509 let t = Instant::now();
20510 let typed = col.compare_scalar(&probe, op).expect("typed cmp");
20511 let typed_ns = t.elapsed().as_nanos();
20512 std::hint::black_box(&typed);
20513
20514 assert_eq!(typed.values(), aos.as_slice(), "typed must match AoS");
20515 let ratio = aos_ns as f64 / typed_ns as f64;
20516 println!(
20517 "compare_scalar Gt n={n}: AoS {aos_ns}ns typed {typed_ns}ns Score={ratio:.2}x"
20518 );
20519 }
20520
20521 #[test]
20522 fn filter_by_mask_null_treated_as_false() {
20523 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
20524 let mask = Column::from_values(vec![Scalar::Bool(true), Scalar::Null(NullKind::Null)])
20525 .expect("mask");
20526
20527 let result = col.filter_by_mask(&mask).expect("filter");
20528 assert_eq!(result.len(), 1);
20529 assert_eq!(result.values()[0], Scalar::Int64(1));
20530 }
20531
20532 #[test]
20533 fn filter_by_mask_rejects_non_boolean_mask() {
20534 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
20535 let mask = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(0)]).expect("mask");
20536
20537 let err = col.filter_by_mask(&mask).expect_err("non-bool mask");
20538 assert!(matches!(err, ColumnError::InvalidMaskType { .. }));
20539 }
20540
20541 #[test]
20542 fn filter_by_mask_empty_result() {
20543 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
20544 let mask =
20545 Column::from_values(vec![Scalar::Bool(false), Scalar::Bool(false)]).expect("mask");
20546
20547 let result = col.filter_by_mask(&mask).expect("filter");
20548 assert!(result.is_empty());
20549 }
20550
20551 #[test]
20552 fn filter_by_mask_matches_scalar_oracle_7mlq1() {
20553 fn next(seed: &mut u64) -> u64 {
20556 *seed = seed
20557 .wrapping_mul(6364136223846793005)
20558 .wrapping_add(1442695040888963407);
20559 *seed
20560 }
20561
20562 fn mask_values(seed: &mut u64, len: usize) -> Vec<Scalar> {
20563 let mut mask = Vec::with_capacity(len);
20564 for _ in 0..len {
20565 mask.push(match next(seed) % 5 {
20566 0 => Scalar::Null(NullKind::Null),
20567 1 | 2 => Scalar::Bool(false),
20568 _ => Scalar::Bool(true),
20569 });
20570 }
20571 mask
20572 }
20573
20574 fn assert_filter(case: usize, family: &str, values: Vec<Scalar>, mask: Vec<Scalar>) {
20575 let input = Column::from_values(values).expect("column");
20576 let mask = Column::from_values(mask).expect("mask");
20577 let expected = input
20578 .values()
20579 .iter()
20580 .zip(mask.values().iter())
20581 .filter_map(|(value, mask_value)| {
20582 matches!(mask_value, Scalar::Bool(true)).then_some(value.clone())
20583 })
20584 .collect::<Vec<_>>();
20585
20586 let filtered = input.filter_by_mask(&mask).expect("filter_by_mask");
20587 assert_eq!(
20588 filtered.dtype(),
20589 input.dtype(),
20590 "case={case} family={family}: dtype changed"
20591 );
20592 assert_eq!(
20593 filtered.len(),
20594 expected.len(),
20595 "case={case} family={family}: length mismatch"
20596 );
20597 for (pos, (actual, expected)) in filtered.values().iter().zip(&expected).enumerate()
20598 {
20599 assert!(
20600 actual.semantic_eq(expected),
20601 "case={case} family={family} pos={pos}: expected {expected:?}, got {actual:?}"
20602 );
20603 }
20604 }
20605
20606 let mut seed = 0x7f11_7e12_5ca1_ab1e_u64;
20607 for case in 0..180 {
20608 let len = (next(&mut seed) % 79 + 1) as usize;
20609
20610 let mut floats = Vec::with_capacity(len);
20611 floats.push(Scalar::Float64(case as f64 / 7.0));
20612 for _ in 1..len {
20613 let raw = (next(&mut seed) % 12_001) as i64 - 6_000;
20614 floats.push(match next(&mut seed) % 8 {
20615 0 => Scalar::Float64(f64::NAN),
20616 1 => Scalar::Float64(f64::INFINITY),
20617 2 => Scalar::Float64(f64::NEG_INFINITY),
20618 3 => Scalar::Float64(-0.0),
20619 _ => Scalar::Float64(raw as f64 / 31.0),
20620 });
20621 }
20622 assert_filter(case, "float", floats, mask_values(&mut seed, len));
20623
20624 let mut ints = Vec::with_capacity(len);
20625 ints.push(Scalar::Int64(case as i64));
20626 for _ in 1..len {
20627 let raw = (next(&mut seed) % 67) as i64 - 33;
20628 ints.push(match next(&mut seed) % 6 {
20629 0 => Scalar::Null(NullKind::Null),
20630 1 => Scalar::Null(NullKind::NaN),
20631 _ => Scalar::Int64(raw),
20632 });
20633 }
20634 assert_filter(case, "int", ints, mask_values(&mut seed, len));
20635
20636 let mut bools = Vec::with_capacity(len);
20637 bools.push(Scalar::Bool(case & 1 == 0));
20638 for _ in 1..len {
20639 bools.push(match next(&mut seed) % 5 {
20640 0 => Scalar::Null(NullKind::Null),
20641 1 => Scalar::Null(NullKind::NaN),
20642 raw => Scalar::Bool(raw & 1 == 0),
20643 });
20644 }
20645 assert_filter(case, "bool", bools, mask_values(&mut seed, len));
20646
20647 let mut utf8 = Vec::with_capacity(len);
20648 utf8.push(Scalar::Utf8(format!("mask{}", case % 23)));
20649 for pos in 1..len {
20650 utf8.push(match next(&mut seed) % 7 {
20651 0 => Scalar::Null(NullKind::Null),
20652 1 => Scalar::Null(NullKind::NaN),
20653 raw => Scalar::Utf8(format!("mask{}_{}", raw, pos % 17)),
20654 });
20655 }
20656 assert_filter(case, "utf8", utf8, mask_values(&mut seed, len));
20657
20658 let mut timedeltas = Vec::with_capacity(len);
20659 timedeltas.push(Scalar::Timedelta64(case as i64 - 45));
20660 for _ in 1..len {
20661 let raw = (next(&mut seed) % 181) as i64 - 90;
20662 timedeltas.push(match next(&mut seed) % 7 {
20663 0 => Scalar::Null(NullKind::Null),
20664 1 => Scalar::Timedelta64(i64::MIN),
20665 _ => Scalar::Timedelta64(raw),
20666 });
20667 }
20668 assert_filter(case, "timedelta", timedeltas, mask_values(&mut seed, len));
20669 }
20670 }
20671
20672 #[test]
20673 fn fillna_replaces_missing() {
20674 let col = Column::from_values(vec![
20675 Scalar::Int64(1),
20676 Scalar::Null(NullKind::Null),
20677 Scalar::Int64(3),
20678 Scalar::Null(NullKind::Null),
20679 ])
20680 .expect("col");
20681
20682 let result = col.fillna(&Scalar::Int64(0)).expect("fillna");
20683 assert_eq!(result.values()[0], Scalar::Int64(1));
20684 assert_eq!(result.values()[1], Scalar::Int64(0));
20685 assert_eq!(result.values()[2], Scalar::Int64(3));
20686 assert_eq!(result.values()[3], Scalar::Int64(0));
20687 assert_eq!(result.validity().count_valid(), 4);
20688 }
20689
20690 #[test]
20691 fn fillna_matches_scalar_replacement_oracle_56isx() {
20692 fn next(seed: &mut u64) -> u64 {
20695 *seed = seed
20696 .wrapping_mul(3202034522624059733)
20697 .wrapping_add(4354685564936845319);
20698 *seed
20699 }
20700
20701 fn assert_fillna(case: usize, family: &str, values: Vec<Scalar>, fill: Scalar) {
20702 let input = Column::from_values(values).expect("column");
20703 let expected = input
20704 .values()
20705 .iter()
20706 .map(|value| {
20707 if value.is_missing() {
20708 fill.clone()
20709 } else {
20710 value.clone()
20711 }
20712 })
20713 .collect::<Vec<_>>();
20714
20715 let filled = input.fillna(&fill).expect("fillna");
20716 assert_eq!(
20717 filled.dtype(),
20718 input.dtype(),
20719 "case={case} family={family}: dtype changed"
20720 );
20721 assert_eq!(
20722 filled.len(),
20723 input.len(),
20724 "case={case} family={family}: length changed"
20725 );
20726 assert_eq!(
20727 filled.values(),
20728 expected.as_slice(),
20729 "case={case} family={family}: replacement mismatch"
20730 );
20731 assert_eq!(
20732 filled.validity().count_valid(),
20733 filled.len(),
20734 "case={case} family={family}: fillna left invalid positions"
20735 );
20736 }
20737
20738 let mut seed = 0xf111_ca5c_a1a5_56a1_u64;
20739 for case in 0..180 {
20740 let len = (next(&mut seed) % 73 + 1) as usize;
20741
20742 let mut floats = Vec::with_capacity(len);
20743 floats.push(Scalar::Float64(case as f64 / 5.0));
20744 for _ in 1..len {
20745 let raw = (next(&mut seed) % 16_001) as i64 - 8_000;
20746 floats.push(match next(&mut seed) % 7 {
20747 0 | 1 => Scalar::Float64(f64::NAN),
20748 2 => Scalar::Float64(f64::INFINITY),
20749 3 => Scalar::Float64(f64::NEG_INFINITY),
20750 _ => Scalar::Float64(raw as f64 / 37.0),
20751 });
20752 }
20753 assert_fillna(case, "float", floats, Scalar::Float64(-123.5));
20754
20755 let mut ints = Vec::with_capacity(len);
20756 ints.push(Scalar::Int64(case as i64 - 90));
20757 for _ in 1..len {
20758 let raw = (next(&mut seed) % 101) as i64 - 50;
20759 ints.push(match next(&mut seed) % 6 {
20760 0 => Scalar::Null(NullKind::Null),
20761 1 => Scalar::Null(NullKind::NaN),
20762 _ => Scalar::Int64(raw),
20763 });
20764 }
20765 assert_fillna(case, "int", ints, Scalar::Int64(-777));
20766
20767 let mut bools = Vec::with_capacity(len);
20768 bools.push(Scalar::Bool(case & 1 == 0));
20769 for _ in 1..len {
20770 bools.push(match next(&mut seed) % 5 {
20771 0 => Scalar::Null(NullKind::Null),
20772 1 => Scalar::Null(NullKind::NaN),
20773 raw => Scalar::Bool(raw & 1 == 0),
20774 });
20775 }
20776 assert_fillna(case, "bool", bools, Scalar::Bool(true));
20777
20778 let mut utf8 = Vec::with_capacity(len);
20779 utf8.push(Scalar::Utf8(format!("fill{}", case % 19)));
20780 for pos in 1..len {
20781 utf8.push(match next(&mut seed) % 7 {
20782 0 => Scalar::Null(NullKind::Null),
20783 1 => Scalar::Null(NullKind::NaN),
20784 raw => Scalar::Utf8(format!("fill{}_{}", raw, pos % 13)),
20785 });
20786 }
20787 assert_fillna(case, "utf8", utf8, Scalar::Utf8("filled".into()));
20788
20789 let mut timedeltas = Vec::with_capacity(len);
20790 timedeltas.push(Scalar::Timedelta64(case as i64));
20791 for _ in 1..len {
20792 let raw = (next(&mut seed) % 149) as i64 - 74;
20793 timedeltas.push(match next(&mut seed) % 7 {
20794 0 => Scalar::Null(NullKind::Null),
20795 1 => Scalar::Timedelta64(i64::MIN),
20796 _ => Scalar::Timedelta64(raw),
20797 });
20798 }
20799 assert_fillna(case, "timedelta", timedeltas, Scalar::Timedelta64(123_456));
20800 }
20801 }
20802
20803 #[test]
20804 fn dropna_removes_missing() {
20805 let col = Column::from_values(vec![
20806 Scalar::Int64(1),
20807 Scalar::Null(NullKind::Null),
20808 Scalar::Int64(3),
20809 Scalar::Null(NullKind::NaN),
20810 ])
20811 .expect("col");
20812
20813 let result = col.dropna().expect("dropna");
20814 assert_eq!(result.len(), 2);
20815 assert_eq!(result.values()[0], Scalar::Int64(1));
20816 assert_eq!(result.values()[1], Scalar::Int64(3));
20817 }
20818
20819 #[test]
20820 fn dropna_matches_order_preserving_scalar_oracle_vbbe4() {
20821 fn next(seed: &mut u64) -> u64 {
20824 *seed = seed
20825 .wrapping_mul(2862933555777941757)
20826 .wrapping_add(3037000493);
20827 *seed
20828 }
20829
20830 fn assert_dropna(case: usize, family: &str, values: Vec<Scalar>) {
20831 let input = Column::from_values(values).expect("column");
20832 let expected = input
20833 .values()
20834 .iter()
20835 .filter(|value| !value.is_missing())
20836 .cloned()
20837 .collect::<Vec<_>>();
20838
20839 let dropped = input.dropna().expect("dropna");
20840 assert_eq!(
20841 dropped.dtype(),
20842 input.dtype(),
20843 "case={case} family={family}: dtype changed"
20844 );
20845 assert_eq!(
20846 dropped.len(),
20847 expected.len(),
20848 "case={case} family={family}: length mismatch"
20849 );
20850 assert_eq!(
20851 dropped.count(),
20852 expected.len(),
20853 "case={case} family={family}: count mismatch"
20854 );
20855 assert!(
20856 dropped.values().iter().all(|value| !value.is_missing()),
20857 "case={case} family={family}: dropna left missing values in {:?}",
20858 dropped.values()
20859 );
20860 assert_eq!(
20861 dropped.values(),
20862 expected.as_slice(),
20863 "case={case} family={family}: order/value mismatch"
20864 );
20865 }
20866
20867 assert_dropna(
20868 usize::MAX,
20869 "all_float_missing",
20870 vec![Scalar::Float64(f64::NAN), Scalar::Float64(f64::NAN)],
20871 );
20872 assert_dropna(
20873 usize::MAX - 1,
20874 "all_timedelta_missing",
20875 vec![
20876 Scalar::Timedelta64(i64::MIN),
20877 Scalar::Null(NullKind::Null),
20878 Scalar::Timedelta64(i64::MIN),
20879 ],
20880 );
20881
20882 let mut seed = 0xd20f_ca55_0b5e_7a11_u64;
20883 for case in 0..180 {
20884 let len = (next(&mut seed) % 71 + 1) as usize;
20885
20886 let mut floats = Vec::with_capacity(len);
20887 floats.push(Scalar::Float64(case as f64 / 3.0));
20888 for _ in 1..len {
20889 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
20890 floats.push(match next(&mut seed) % 8 {
20891 0 | 1 => Scalar::Float64(f64::NAN),
20892 2 => Scalar::Float64(f64::INFINITY),
20893 3 => Scalar::Float64(f64::NEG_INFINITY),
20894 4 => Scalar::Float64(-0.0),
20895 _ => Scalar::Float64(raw as f64 / 29.0),
20896 });
20897 }
20898 assert_dropna(case, "float", floats);
20899
20900 let mut ints = Vec::with_capacity(len);
20901 ints.push(Scalar::Int64(case as i64));
20902 for _ in 1..len {
20903 let raw = (next(&mut seed) % 59) as i64 - 29;
20904 ints.push(match next(&mut seed) % 6 {
20905 0 => Scalar::Null(NullKind::Null),
20906 1 => Scalar::Null(NullKind::NaN),
20907 _ => Scalar::Int64(raw),
20908 });
20909 }
20910 assert_dropna(case, "int", ints);
20911
20912 let mut bools = Vec::with_capacity(len);
20913 bools.push(Scalar::Bool(case & 1 == 0));
20914 for _ in 1..len {
20915 bools.push(match next(&mut seed) % 5 {
20916 0 => Scalar::Null(NullKind::Null),
20917 1 => Scalar::Null(NullKind::NaN),
20918 raw => Scalar::Bool(raw & 1 == 1),
20919 });
20920 }
20921 assert_dropna(case, "bool", bools);
20922
20923 let mut utf8 = Vec::with_capacity(len);
20924 utf8.push(Scalar::Utf8(format!("u{}", case % 17)));
20925 for pos in 1..len {
20926 utf8.push(match next(&mut seed) % 7 {
20927 0 => Scalar::Null(NullKind::Null),
20928 1 => Scalar::Null(NullKind::NaN),
20929 raw => Scalar::Utf8(format!("u{}_{}", raw, pos % 11)),
20930 });
20931 }
20932 assert_dropna(case, "utf8", utf8);
20933
20934 let mut timedeltas = Vec::with_capacity(len);
20935 timedeltas.push(Scalar::Timedelta64(case as i64 - 90));
20936 for _ in 1..len {
20937 let raw = (next(&mut seed) % 123) as i64 - 61;
20938 timedeltas.push(match next(&mut seed) % 7 {
20939 0 => Scalar::Null(NullKind::Null),
20940 1 => Scalar::Timedelta64(i64::MIN),
20941 _ => Scalar::Timedelta64(raw),
20942 });
20943 }
20944 assert_dropna(case, "timedelta", timedeltas);
20945 }
20946 }
20947
20948 #[test]
20949 fn comparison_empty_columns() {
20950 let left = Column::from_values(vec![]).expect("left");
20951 let right = Column::from_values(vec![]).expect("right");
20952 let result = left
20953 .binary_comparison(&right, ComparisonOp::Eq)
20954 .expect("eq");
20955 assert!(result.is_empty());
20956 }
20957
20958 #[test]
20959 fn comparison_length_mismatch_error() {
20960 let left = Column::from_values(vec![Scalar::Int64(1)]).expect("left");
20961 let right =
20962 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("right");
20963 assert!(left.binary_comparison(&right, ComparisonOp::Eq).is_err());
20964 }
20965
20966 #[test]
20967 fn comparison_bool_ordering() {
20968 let left =
20969 Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("left");
20970 let right =
20971 Column::from_values(vec![Scalar::Bool(false), Scalar::Bool(true)]).expect("right");
20972
20973 let gt = left
20974 .binary_comparison(&right, ComparisonOp::Gt)
20975 .expect("gt");
20976 assert_eq!(gt.values()[0], Scalar::Bool(true));
20977 assert_eq!(gt.values()[1], Scalar::Bool(false));
20978 }
20979 }
20980
20981 mod iter_and_predicates {
20982 use fp_types::NullKind;
20983
20984 use super::*;
20985
20986 #[test]
20987 fn iter_values_preserves_order() {
20988 let col =
20989 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
20990 .expect("col");
20991 let collected: Vec<_> = col.iter_values().cloned().collect();
20992 assert_eq!(collected, col.values());
20993 }
20994
20995 #[test]
20996 fn to_vec_returns_owned_clone() {
20997 let col = Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(6)]).expect("col");
20998 let v = col.to_vec();
20999 assert_eq!(v, vec![Scalar::Int64(5), Scalar::Int64(6)]);
21000 assert_eq!(col.len(), 2);
21002 }
21003
21004 #[test]
21005 fn copy_returns_independent_clone() {
21006 let col = Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(6)]).expect("col");
21007 let copied = col.copy();
21008 let viewed = col.view();
21009 let transposed = col.transpose();
21010 assert_eq!(copied, col);
21011 assert_eq!(viewed, col);
21012 assert_eq!(transposed, col);
21013 assert_eq!(col.t(), transposed);
21014 assert_eq!(col.T(), transposed);
21015 assert_ne!(copied.values().as_ptr(), col.values().as_ptr());
21016 assert_ne!(viewed.values().as_ptr(), col.values().as_ptr());
21017 assert_ne!(transposed.values().as_ptr(), col.values().as_ptr());
21018 }
21019
21020 #[test]
21021 fn item_extracts_single_value_and_rejects_other_lengths() {
21022 let single = Column::from_values(vec![Scalar::Int64(5)]).expect("col");
21023 assert_eq!(single.item(), Ok(Scalar::Int64(5)));
21024
21025 let empty = Column::from_values(Vec::<Scalar>::new()).expect("col");
21026 assert_eq!(
21027 empty.item(),
21028 Err(crate::ColumnError::InvalidLength {
21029 operation: "item()",
21030 expected: 1,
21031 actual: 0,
21032 })
21033 );
21034
21035 let multi = Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(6)]).expect("col");
21036 assert_eq!(
21037 multi.item(),
21038 Err(crate::ColumnError::InvalidLength {
21039 operation: "item()",
21040 expected: 1,
21041 actual: 2,
21042 })
21043 );
21044 }
21045
21046 #[test]
21047 fn has_any_missing_detects_null() {
21048 let populated =
21049 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21050 assert!(!populated.has_any_missing());
21051 assert_eq!(populated.hasnans(), populated.has_any_missing());
21052 assert_eq!(populated.nbytes(), populated.memory_usage(false));
21053
21054 let with_null =
21055 Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
21056 .expect("col");
21057 assert!(with_null.has_any_missing());
21058 assert_eq!(with_null.hasnans(), with_null.has_any_missing());
21059 assert_eq!(with_null.nbytes(), with_null.memory_usage(false));
21060 }
21061
21062 #[test]
21063 fn missingness_probes_use_nullable_int64_validity_without_scalar_materialization_eo8jv() {
21064 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(0, 2), (5, 1)]), 6);
21065 let mixed = Column::from_i64_values_with_validity((10_i64..16).collect(), validity);
21066
21067 assert!(mixed.has_any_missing());
21068 assert_eq!(mixed.hasnans(), mixed.has_any_missing());
21069 assert!(!mixed.all_missing());
21070 if let ScalarValues::LazyNullableInt64 { values, .. } = &mixed.values {
21071 assert!(values.get().is_none());
21072 }
21073
21074 let all_invalid =
21075 Column::from_i64_values_with_validity(vec![0, 0, 0], ValidityMask::all_invalid(3));
21076 assert!(all_invalid.has_any_missing());
21077 assert!(all_invalid.all_missing());
21078 if let ScalarValues::LazyNullableInt64 { values, .. } = &all_invalid.values {
21079 assert!(values.get().is_none());
21080 }
21081 }
21082
21083 #[test]
21084 fn missingness_probes_float64_raw_path_checks_nan_eo8jv() {
21085 let mixed = Column {
21086 dtype: DType::Float64,
21087 values: ScalarValues::lazy_all_valid_float64(vec![1.0, f64::NAN, f64::INFINITY]),
21088 validity: ValidityMask::all_valid(3),
21089 data: None,
21090 };
21091 assert!(mixed.has_any_missing());
21092 assert!(!mixed.all_missing());
21093 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &mixed.values {
21094 assert!(values.get().is_none());
21095 }
21096
21097 let all_nan = Column {
21098 dtype: DType::Float64,
21099 values: ScalarValues::lazy_all_valid_float64(vec![f64::NAN, f64::NAN]),
21100 validity: ValidityMask::all_valid(2),
21101 data: None,
21102 };
21103 assert!(all_nan.has_any_missing());
21104 assert!(all_nan.all_missing());
21105 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &all_nan.values {
21106 assert!(values.get().is_none());
21107 }
21108 }
21109
21110 #[test]
21111 fn all_missing_empty_is_true() {
21112 let empty = Column::from_values(Vec::<Scalar>::new()).expect("col");
21113 assert!(empty.all_missing());
21114
21115 let all_null = Column::from_values(vec![
21116 Scalar::Null(NullKind::NaN),
21117 Scalar::Null(NullKind::Null),
21118 ])
21119 .expect("col");
21120 assert!(all_null.all_missing());
21121
21122 let mixed = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
21123 .expect("col");
21124 assert!(!mixed.all_missing());
21125 }
21126
21127 #[test]
21128 fn apply_bool_positive_predicate() {
21129 let col = Column::from_values(vec![
21130 Scalar::Int64(1),
21131 Scalar::Int64(2),
21132 Scalar::Int64(3),
21133 Scalar::Int64(4),
21134 ])
21135 .expect("col");
21136 let even = col
21137 .apply_bool(|v| v.to_f64().map(|f| f as i64 % 2 == 0).unwrap_or(false))
21138 .expect("apply_bool");
21139 assert_eq!(even.dtype(), DType::Bool);
21140 assert_eq!(even.values()[0], Scalar::Bool(false));
21141 assert_eq!(even.values()[1], Scalar::Bool(true));
21142 assert_eq!(even.values()[2], Scalar::Bool(false));
21143 assert_eq!(even.values()[3], Scalar::Bool(true));
21144 }
21145
21146 #[test]
21147 fn first_and_last_return_endpoints() {
21148 let col = Column::from_values(vec![
21149 Scalar::Int64(10),
21150 Scalar::Int64(20),
21151 Scalar::Int64(30),
21152 ])
21153 .expect("col");
21154 assert_eq!(col.first(), Some(&Scalar::Int64(10)));
21155 assert_eq!(col.last(), Some(&Scalar::Int64(30)));
21156
21157 let empty = Column::from_values(Vec::<Scalar>::new()).expect("col");
21158 assert_eq!(empty.first(), None);
21159 assert_eq!(empty.last(), None);
21160 }
21161
21162 #[test]
21163 fn count_matching_ignores_missing_and_mismatches() {
21164 let col = Column::from_values(vec![
21165 Scalar::Int64(1),
21166 Scalar::Int64(2),
21167 Scalar::Null(NullKind::NaN),
21168 Scalar::Int64(4),
21169 Scalar::Int64(6),
21170 ])
21171 .expect("col");
21172 let evens =
21173 col.count_matching(|v| v.to_f64().map(|f| f as i64 % 2 == 0).unwrap_or(false));
21174 assert_eq!(evens, 3); }
21176
21177 #[test]
21178 fn zip_with_elementwise_combine() {
21179 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21180 .expect("a");
21181 let b = Column::from_values(vec![
21182 Scalar::Int64(10),
21183 Scalar::Int64(20),
21184 Scalar::Int64(30),
21185 ])
21186 .expect("b");
21187 let sum = a
21188 .zip_with(&b, |l, r| match (l.to_f64(), r.to_f64()) {
21189 (Ok(lf), Ok(rf)) => Scalar::Float64(lf + rf),
21190 _ => Scalar::Null(NullKind::NaN),
21191 })
21192 .expect("zip_with");
21193 assert_eq!(sum.values()[0], Scalar::Float64(11.0));
21194 assert_eq!(sum.values()[1], Scalar::Float64(22.0));
21195 assert_eq!(sum.values()[2], Scalar::Float64(33.0));
21196 }
21197
21198 #[test]
21199 fn zip_with_length_mismatch_errors() {
21200 let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
21201 let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
21202 assert!(a.zip_with(&b, |l, _| l.clone()).is_err());
21203 }
21204
21205 #[test]
21206 fn iter_enumerate_yields_positions() {
21207 let col = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("col");
21208 let collected: Vec<_> = col.iter_enumerate().map(|(i, v)| (i, v.clone())).collect();
21209 assert_eq!(
21210 collected,
21211 vec![(0, Scalar::Int64(10)), (1, Scalar::Int64(20))]
21212 );
21213 }
21214
21215 #[test]
21216 fn apply_bool_missing_maps_to_false() {
21217 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
21218 .expect("col");
21219 let result = col.apply_bool(|_| true).expect("apply_bool");
21220 assert_eq!(result.values()[0], Scalar::Bool(true));
21221 assert_eq!(result.values()[1], Scalar::Bool(false));
21223 }
21224 }
21225
21226 mod take_slice_concat_repeat {
21227 use super::*;
21228
21229 #[test]
21230 fn take_reorders_rows() {
21231 let col = Column::from_values(vec![
21232 Scalar::Int64(10),
21233 Scalar::Int64(20),
21234 Scalar::Int64(30),
21235 ])
21236 .expect("col");
21237 let picked = col.take(&[2, 0, 1]).expect("take");
21238 assert_eq!(picked.values()[0], Scalar::Int64(30));
21239 assert_eq!(picked.values()[1], Scalar::Int64(10));
21240 assert_eq!(picked.values()[2], Scalar::Int64(20));
21241 }
21242
21243 #[test]
21244 fn take_out_of_bounds_errors() {
21245 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
21246 let err = col.take(&[5]).unwrap_err();
21247 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
21248 }
21249
21250 #[test]
21251 fn slice_returns_contiguous_range() {
21252 let col = Column::from_values(vec![
21253 Scalar::Int64(1),
21254 Scalar::Int64(2),
21255 Scalar::Int64(3),
21256 Scalar::Int64(4),
21257 ])
21258 .expect("col");
21259 let middle = col.slice(1, 2).expect("slice");
21260 assert_eq!(middle.len(), 2);
21261 assert_eq!(middle.values()[0], Scalar::Int64(2));
21262 assert_eq!(middle.values()[1], Scalar::Int64(3));
21263 }
21264
21265 #[test]
21266 fn slice_past_end_yields_empty() {
21267 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21268 let empty = col.slice(10, 5).expect("slice");
21269 assert!(empty.is_empty());
21270 assert_eq!(empty.dtype(), DType::Int64);
21271 }
21272
21273 #[test]
21274 fn slice_len_clamps_to_tail() {
21275 let col = Column::from_values(vec![
21276 Scalar::Float64(1.0),
21277 Scalar::Float64(2.0),
21278 Scalar::Float64(3.0),
21279 ])
21280 .expect("col");
21281 let tail = col.slice(2, 100).expect("slice");
21282 assert_eq!(tail.len(), 1);
21283 assert_eq!(tail.values()[0], Scalar::Float64(3.0));
21284 }
21285
21286 #[test]
21287 fn slice_huge_len_clamps_without_overflow() {
21288 let col =
21289 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21290 .expect("col");
21291 let tail = col.slice(1, usize::MAX).expect("slice");
21292 assert_eq!(tail.values(), &[Scalar::Int64(2), Scalar::Int64(3)]);
21293 }
21294
21295 #[test]
21296 fn head_returns_first_n_values() {
21297 let col = Column::from_values(vec![
21298 Scalar::Int64(10),
21299 Scalar::Int64(20),
21300 Scalar::Int64(30),
21301 Scalar::Int64(40),
21302 ])
21303 .expect("col");
21304 let out = col.head(2).expect("head");
21305 assert_eq!(out.values(), &[Scalar::Int64(10), Scalar::Int64(20)]);
21306 }
21307
21308 #[test]
21309 fn tail_returns_last_n_values() {
21310 let col = Column::from_values(vec![
21311 Scalar::Int64(10),
21312 Scalar::Int64(20),
21313 Scalar::Int64(30),
21314 Scalar::Int64(40),
21315 ])
21316 .expect("col");
21317 let out = col.tail(2).expect("tail");
21318 assert_eq!(out.values(), &[Scalar::Int64(30), Scalar::Int64(40)]);
21319 }
21320
21321 #[test]
21322 fn head_tail_negative_n_match_pandas_style() {
21323 let col = Column::from_values(vec![
21324 Scalar::Int64(10),
21325 Scalar::Int64(20),
21326 Scalar::Int64(30),
21327 Scalar::Int64(40),
21328 Scalar::Int64(50),
21329 ])
21330 .expect("col");
21331 let head = col.head(-2).expect("head");
21332 let tail = col.tail(-2).expect("tail");
21333 assert_eq!(
21334 head.values(),
21335 &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
21336 );
21337 assert_eq!(
21338 tail.values(),
21339 &[Scalar::Int64(30), Scalar::Int64(40), Scalar::Int64(50)]
21340 );
21341 }
21342
21343 #[test]
21344 fn head_tail_large_negative_n_saturate_to_empty() {
21345 let col = Column::from_values(vec![
21346 Scalar::Float64(1.0),
21347 Scalar::Float64(2.0),
21348 Scalar::Float64(3.0),
21349 ])
21350 .expect("col");
21351 let head = col.head(-10).expect("head");
21352 let tail = col.tail(-10).expect("tail");
21353 assert!(head.is_empty());
21354 assert!(tail.is_empty());
21355 assert_eq!(head.dtype(), DType::Float64);
21356 assert_eq!(tail.dtype(), DType::Float64);
21357 }
21358
21359 #[test]
21360 fn concat_appends_same_dtype() {
21361 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("a");
21362 let b = Column::from_values(vec![Scalar::Int64(3)]).expect("b");
21363 let combined = a.concat(&b).expect("concat");
21364 assert_eq!(combined.len(), 3);
21365 assert_eq!(combined.values()[2], Scalar::Int64(3));
21366 }
21367
21368 #[test]
21369 fn concat_different_dtypes_errors() {
21370 let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
21371 let b = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("b");
21372 let err = a.concat(&b).unwrap_err();
21373 assert!(matches!(err, crate::ColumnError::DTypeMismatch { .. }));
21374 }
21375
21376 #[test]
21377 fn repeat_duplicates_contiguously() {
21378 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21379 let out = col.repeat(3).expect("repeat");
21380 assert_eq!(out.len(), 6);
21381 assert_eq!(out.values()[0], Scalar::Int64(1));
21382 assert_eq!(out.values()[1], Scalar::Int64(1));
21383 assert_eq!(out.values()[2], Scalar::Int64(1));
21384 assert_eq!(out.values()[3], Scalar::Int64(2));
21385 }
21386
21387 #[test]
21388 fn repeat_zero_is_empty_same_dtype() {
21389 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
21390 let out = col.repeat(0).expect("repeat");
21391 assert!(out.is_empty());
21392 assert_eq!(out.dtype(), DType::Int64);
21393 }
21394
21395 #[test]
21396 fn repeat_one_is_clone() {
21397 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21398 let out = col.repeat(1).expect("repeat");
21399 assert_eq!(out.values(), col.values());
21400 }
21401 }
21402
21403 mod reverse_head_tail_cumulatives_unique {
21404 use fp_types::NullKind;
21405
21406 use super::*;
21407
21408 #[test]
21409 fn reverse_swaps_order_and_preserves_dtype() {
21410 let col =
21411 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21412 .expect("col");
21413 let r = col.reverse().expect("reverse");
21414 assert_eq!(r.values()[0], Scalar::Int64(3));
21415 assert_eq!(r.values()[2], Scalar::Int64(1));
21416 assert_eq!(r.dtype(), DType::Int64);
21417 }
21418
21419 #[test]
21420 fn head_positive_takes_first_n() {
21421 let col = Column::from_values(vec![
21422 Scalar::Int64(1),
21423 Scalar::Int64(2),
21424 Scalar::Int64(3),
21425 Scalar::Int64(4),
21426 ])
21427 .expect("col");
21428 let h = col.head(2).expect("head");
21429 assert_eq!(h.len(), 2);
21430 assert_eq!(h.values()[0], Scalar::Int64(1));
21431 assert_eq!(h.values()[1], Scalar::Int64(2));
21432 }
21433
21434 #[test]
21435 fn head_negative_drops_last_n() {
21436 let col =
21437 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21438 .expect("col");
21439 let h = col.head(-1).expect("head");
21440 assert_eq!(h.len(), 2);
21441 assert_eq!(h.values()[1], Scalar::Int64(2));
21442 }
21443
21444 #[test]
21445 fn tail_positive_takes_last_n() {
21446 let col = Column::from_values(vec![
21447 Scalar::Int64(1),
21448 Scalar::Int64(2),
21449 Scalar::Int64(3),
21450 Scalar::Int64(4),
21451 ])
21452 .expect("col");
21453 let t = col.tail(2).expect("tail");
21454 assert_eq!(t.len(), 2);
21455 assert_eq!(t.values()[0], Scalar::Int64(3));
21456 assert_eq!(t.values()[1], Scalar::Int64(4));
21457 }
21458
21459 #[test]
21460 fn tail_negative_drops_first_n() {
21461 let col =
21462 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21463 .expect("col");
21464 let t = col.tail(-1).expect("tail");
21465 assert_eq!(t.len(), 2);
21466 assert_eq!(t.values()[0], Scalar::Int64(2));
21467 }
21468
21469 #[test]
21470 fn head_tail_out_of_range_clamps() {
21471 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
21472 assert_eq!(col.head(10).expect("head").len(), 1);
21473 assert_eq!(col.tail(10).expect("tail").len(), 1);
21474 assert_eq!(col.head(-10).expect("head").len(), 0);
21475 assert_eq!(col.tail(-10).expect("tail").len(), 0);
21476 }
21477
21478 #[test]
21479 fn cumsum_produces_float64_running_sum() {
21480 let col = Column::from_values(vec![
21481 Scalar::Float64(1.0),
21482 Scalar::Null(NullKind::NaN),
21483 Scalar::Float64(3.0),
21484 ])
21485 .expect("col");
21486 let c = col.cumsum().expect("cumsum");
21487 assert_eq!(c.dtype(), DType::Float64);
21488 assert_eq!(c.values()[0], Scalar::Float64(1.0));
21489 assert!(c.values()[1].is_missing());
21490 assert_eq!(c.values()[2], Scalar::Float64(4.0));
21491 }
21492
21493 #[test]
21494 fn cumprod_running_product() {
21495 let col = Column::from_values(vec![
21496 Scalar::Float64(2.0),
21497 Scalar::Float64(3.0),
21498 Scalar::Float64(4.0),
21499 ])
21500 .expect("col");
21501 let c = col.cumprod().expect("cumprod");
21502 assert_eq!(c.values()[2], Scalar::Float64(24.0));
21503 }
21504
21505 #[test]
21506 fn cummax_cummin_running_extrema() {
21507 let col = Column::from_values(vec![
21508 Scalar::Float64(3.0),
21509 Scalar::Float64(1.0),
21510 Scalar::Float64(4.0),
21511 Scalar::Float64(1.0),
21512 Scalar::Float64(5.0),
21513 ])
21514 .expect("col");
21515 let mx = col.cummax().expect("cummax");
21516 assert_eq!(mx.values()[4], Scalar::Float64(5.0));
21517 let mn = col.cummin().expect("cummin");
21518 assert_eq!(mn.values()[4], Scalar::Float64(1.0));
21519 }
21520
21521 #[test]
21522 fn unique_preserves_first_seen_order() {
21523 let col = Column::from_values(vec![
21524 Scalar::Int64(3),
21525 Scalar::Int64(1),
21526 Scalar::Int64(3),
21527 Scalar::Int64(2),
21528 Scalar::Int64(1),
21529 ])
21530 .expect("col");
21531 let u = col.unique().expect("unique");
21532 assert_eq!(u.len(), 3);
21533 assert_eq!(u.values()[0], Scalar::Int64(3));
21534 assert_eq!(u.values()[1], Scalar::Int64(1));
21535 assert_eq!(u.values()[2], Scalar::Int64(2));
21536 }
21537
21538 #[test]
21539 fn unique_drops_nulls() {
21540 let col = Column::from_values(vec![
21541 Scalar::Int64(1),
21542 Scalar::Null(NullKind::NaN),
21543 Scalar::Int64(1),
21544 Scalar::Null(NullKind::NaN),
21545 ])
21546 .expect("col");
21547 let u = col.unique().expect("unique");
21548 assert_eq!(u.len(), 1);
21549 assert_eq!(u.values()[0], Scalar::Int64(1));
21550 }
21551 }
21552
21553 mod abs_shift_clip_round_isin {
21554 use fp_types::NullKind;
21555
21556 use super::*;
21557
21558 #[test]
21559 fn abs_int_and_float() {
21560 let int_col =
21561 Column::from_values(vec![Scalar::Int64(-3), Scalar::Int64(0), Scalar::Int64(5)])
21562 .expect("int");
21563 let a = int_col.abs().expect("abs");
21564 assert_eq!(a.values()[0], Scalar::Int64(3));
21565 assert_eq!(a.values()[1], Scalar::Int64(0));
21566
21567 let float_col =
21568 Column::from_values(vec![Scalar::Float64(-1.5), Scalar::Null(NullKind::NaN)])
21569 .expect("float");
21570 let b = float_col.abs().expect("abs");
21571 assert_eq!(b.values()[0], Scalar::Float64(1.5));
21572 assert!(b.values()[1].is_missing());
21573 }
21574
21575 #[test]
21576 fn abs_bool_preserves_dtype() {
21577 let bool_col =
21578 Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("bool");
21579 let result = bool_col.abs().expect("abs");
21580 assert_eq!(result.dtype(), DType::Bool);
21581 assert_eq!(result.values(), &[Scalar::Bool(true), Scalar::Bool(false)]);
21582 }
21583
21584 #[test]
21585 fn abs_utf8_errors() {
21586 let col = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("col");
21587 assert!(col.abs().is_err());
21588 }
21589
21590 #[test]
21591 fn shift_positive_pads_left_with_fill() {
21592 let col =
21593 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21594 .expect("col");
21595 let s = col.shift(1, Scalar::Null(NullKind::NaN)).expect("shift");
21596 assert!(s.values()[0].is_missing());
21597 assert_eq!(s.values()[1], Scalar::Int64(1));
21598 assert_eq!(s.values()[2], Scalar::Int64(2));
21599 }
21600
21601 #[test]
21602 fn shift_negative_pads_right() {
21603 let col =
21604 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21605 .expect("col");
21606 let s = col.shift(-1, Scalar::Int64(0)).expect("shift");
21607 assert_eq!(s.values()[0], Scalar::Int64(2));
21608 assert_eq!(s.values()[1], Scalar::Int64(3));
21609 assert_eq!(s.values()[2], Scalar::Int64(0));
21610 }
21611
21612 #[test]
21613 fn shift_zero_is_clone() {
21614 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21615 let s = col.shift(0, Scalar::Int64(-1)).expect("shift");
21616 assert_eq!(s.values(), col.values());
21617 }
21618
21619 #[test]
21620 fn clip_both_bounds() {
21621 let col = Column::from_values(vec![
21622 Scalar::Float64(-5.0),
21623 Scalar::Float64(3.0),
21624 Scalar::Float64(10.0),
21625 ])
21626 .expect("col");
21627 let c = col.clip(Some(0.0), Some(5.0)).expect("clip");
21628 assert_eq!(c.values()[0], Scalar::Float64(0.0));
21629 assert_eq!(c.values()[1], Scalar::Float64(3.0));
21630 assert_eq!(c.values()[2], Scalar::Float64(5.0));
21631 }
21632
21633 #[test]
21634 fn clip_none_bounds_are_noop() {
21635 let col = Column::from_values(vec![Scalar::Float64(-5.0), Scalar::Float64(10.0)])
21636 .expect("col");
21637 let c = col.clip(None, None).expect("clip");
21638 assert_eq!(c.values()[0], Scalar::Float64(-5.0));
21639 assert_eq!(c.values()[1], Scalar::Float64(10.0));
21640 }
21641
21642 #[test]
21643 fn clip_scalar_bounds_match_clamp_oracle_t3idc() {
21644 fn next(seed: &mut u64) -> u64 {
21647 *seed = seed
21648 .wrapping_mul(1181783497276652981)
21649 .wrapping_add(1013904223);
21650 *seed
21651 }
21652
21653 fn bound(seed: &mut u64) -> Option<f64> {
21654 match next(seed) % 7 {
21655 0 => None,
21656 1 => Some(f64::NAN),
21657 _ => {
21658 let raw = (next(seed) % 20_001) as i64 - 10_000;
21659 Some(raw as f64 / 17.0)
21660 }
21661 }
21662 }
21663
21664 fn normalize(bound: Option<f64>) -> Option<f64> {
21665 bound.filter(|v| !v.is_nan())
21666 }
21667
21668 fn clamp_oracle(mut value: f64, lower: Option<f64>, upper: Option<f64>) -> f64 {
21669 if let Some(lo) = lower
21670 && value < lo
21671 {
21672 value = lo;
21673 }
21674 if let Some(hi) = upper
21675 && value > hi
21676 {
21677 value = hi;
21678 }
21679 value
21680 }
21681
21682 let mut seed = 0x0c11_f0b0_a7e5_d1dc_u64;
21683 for case in 0..220 {
21684 let len = (next(&mut seed) % 61 + 1) as usize;
21685 let mut lower = bound(&mut seed);
21686 let mut upper = bound(&mut seed);
21687 if let (Some(lo), Some(hi)) = (normalize(lower), normalize(upper))
21688 && lo > hi
21689 {
21690 lower = Some(hi);
21691 upper = Some(lo);
21692 }
21693 let expected_lower = normalize(lower);
21694 let expected_upper = normalize(upper);
21695
21696 let mut values = Vec::with_capacity(len);
21697 for _ in 0..len {
21698 let selector = next(&mut seed) % 43;
21699 let whole = (next(&mut seed) % 100_001) as i64 - 50_000;
21700 let frac = (next(&mut seed) % 1000) as f64 / 1000.0;
21701 values.push(match selector {
21702 0 => Scalar::Null(NullKind::NaN),
21703 1 => Scalar::Float64(f64::NAN),
21704 _ => Scalar::Float64(whole as f64 / 19.0 + frac),
21705 });
21706 }
21707
21708 let input = Column::from_values(values.clone()).expect("column");
21709 let clipped = input.clip(lower, upper).expect("clip");
21710 assert_eq!(clipped.dtype(), DType::Float64);
21711 assert_eq!(clipped.values().len(), values.len());
21712 for (pos, (before, after)) in values.iter().zip(clipped.values()).enumerate() {
21713 if before.is_missing() {
21714 assert!(
21715 after.is_missing(),
21716 "case={case} pos={pos}: missing became {after:?}"
21717 );
21718 continue;
21719 }
21720
21721 let expected = match before {
21722 Scalar::Float64(v) => clamp_oracle(*v, expected_lower, expected_upper),
21723 other => panic!("unexpected non-float value: {other:?}"),
21724 };
21725 match after {
21726 Scalar::Float64(got) => assert_eq!(
21727 *got, expected,
21728 "case={case} pos={pos}: got {got}, expected {expected}"
21729 ),
21730 other => panic!("case={case} pos={pos}: expected Float64, got {other:?}"),
21731 }
21732 }
21733 }
21734 }
21735
21736 #[test]
21737 fn round_rounds_floats() {
21738 let col = Column::from_values(vec![
21739 Scalar::Float64(1.234),
21740 Scalar::Float64(5.678),
21741 Scalar::Null(NullKind::NaN),
21742 ])
21743 .expect("col");
21744 let r = col.round(1).expect("round");
21745 assert_eq!(r.values()[0], Scalar::Float64(1.2));
21746 assert_eq!(r.values()[1], Scalar::Float64(5.7));
21747 assert!(r.values()[2].is_missing());
21748 }
21749
21750 #[test]
21751 fn round_int_nonnegative_decimals_is_noop() {
21752 let col = Column::from_values(vec![Scalar::Int64(12), Scalar::Int64(34)]).expect("col");
21753 let r = col.round(2).expect("round");
21754 assert_eq!(r.values(), col.values());
21755 assert_eq!(r.dtype(), DType::Int64);
21756 }
21757
21758 #[test]
21759 fn round_int_negative_decimals_preserves_dtype() {
21760 let col = Column::from_values(vec![
21761 Scalar::Int64(15),
21762 Scalar::Int64(25),
21763 Scalar::Int64(35),
21764 Scalar::Int64(-15),
21765 ])
21766 .expect("col");
21767 let r = col.round(-1).expect("round");
21768 assert_eq!(r.dtype(), DType::Int64);
21769 assert_eq!(
21770 r.values(),
21771 &[
21772 Scalar::Int64(20),
21773 Scalar::Int64(20),
21774 Scalar::Int64(40),
21775 Scalar::Int64(-20)
21776 ]
21777 );
21778 }
21779
21780 #[test]
21781 fn round_bool_is_noop() {
21782 let col =
21783 Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("col");
21784 let r = col.round(-2).expect("round");
21785 assert_eq!(r.dtype(), DType::Bool);
21786 assert_eq!(r.values(), col.values());
21787 }
21788
21789 #[test]
21790 fn round_negative_decimals_rounds_left() {
21791 let col = Column::from_values(vec![Scalar::Float64(1234.0)]).expect("col");
21792 let r = col.round(-2).expect("round");
21793 assert_eq!(r.values()[0], Scalar::Float64(1200.0));
21794 }
21795
21796 #[test]
21797 fn round_uses_pandas_half_even_ties() {
21798 let col = Column::from_values(vec![
21799 Scalar::Float64(1.5),
21800 Scalar::Float64(2.5),
21801 Scalar::Float64(-1.5),
21802 Scalar::Float64(3.5),
21803 ])
21804 .expect("col");
21805 let r = col.round(0).expect("round");
21806 assert_eq!(
21807 r.values(),
21808 &[
21809 Scalar::Float64(2.0),
21810 Scalar::Float64(2.0),
21811 Scalar::Float64(-2.0),
21812 Scalar::Float64(4.0)
21813 ]
21814 );
21815 }
21816
21817 #[test]
21818 fn round_negative_decimals_uses_half_even_ties() {
21819 let col = Column::from_values(vec![
21820 Scalar::Float64(15.0),
21821 Scalar::Float64(25.0),
21822 Scalar::Float64(35.0),
21823 Scalar::Float64(-15.0),
21824 ])
21825 .expect("col");
21826 let r = col.round(-1).expect("round");
21827 assert_eq!(
21828 r.values(),
21829 &[
21830 Scalar::Float64(20.0),
21831 Scalar::Float64(20.0),
21832 Scalar::Float64(40.0),
21833 Scalar::Float64(-20.0)
21834 ]
21835 );
21836 }
21837
21838 #[test]
21839 fn floor_ceil_trunc_match_scalar_oracle_61try() {
21840 fn next(seed: &mut u64) -> u64 {
21843 *seed = seed
21844 .wrapping_mul(3202034522624059733)
21845 .wrapping_add(4354685564936845319);
21846 *seed
21847 }
21848
21849 fn floor_oracle(v: f64) -> f64 {
21850 v.floor()
21851 }
21852
21853 fn ceil_oracle(v: f64) -> f64 {
21854 v.ceil()
21855 }
21856
21857 fn trunc_oracle(v: f64) -> f64 {
21858 v.trunc()
21859 }
21860
21861 let mut seed = 0x61d1_ff10_0ce1_cafe_u64;
21862 for case in 0..240 {
21863 let len = (next(&mut seed) % 59 + 1) as usize;
21864 let mut values = Vec::with_capacity(len);
21865 for _ in 0..len {
21866 let selector = next(&mut seed) % 37;
21867 let whole = (next(&mut seed) % 500_001) as i64 - 250_000;
21868 let frac = (next(&mut seed) % 100_000) as f64 / 100_000.0;
21869 let sign = if next(&mut seed) & 1 == 0 { 1.0 } else { -1.0 };
21870 let value = sign * (whole as f64 / 13.0 + frac);
21871 values.push(match selector {
21872 0 => Scalar::Null(NullKind::NaN),
21873 1 => Scalar::Float64(f64::NAN),
21874 _ => Scalar::Float64(value),
21875 });
21876 }
21877
21878 let input = Column::from_values(values.clone()).expect("column");
21879 type UnaryFloatOutput = (&'static str, Column, fn(f64) -> f64);
21880 let outputs: [UnaryFloatOutput; 3] = [
21881 ("floor", input.floor().expect("floor"), floor_oracle),
21882 ("ceil", input.ceil().expect("ceil"), ceil_oracle),
21883 ("trunc", input.trunc().expect("trunc"), trunc_oracle),
21884 ];
21885
21886 for (op, output, oracle) in outputs {
21887 assert_eq!(output.dtype(), DType::Float64, "{op} dtype drift");
21888 assert_eq!(output.values().len(), values.len(), "{op} length drift");
21889 for (pos, (before, after)) in values.iter().zip(output.values()).enumerate() {
21890 if before.is_missing() {
21891 assert!(
21892 after.is_missing(),
21893 "{op} case={case} pos={pos}: missing became {after:?}"
21894 );
21895 continue;
21896 }
21897
21898 let expected = match before {
21899 Scalar::Float64(v) => oracle(*v),
21900 other => panic!("{op} unexpected non-float value: {other:?}"),
21901 };
21902 match after {
21903 Scalar::Float64(got) => assert_eq!(
21904 *got, expected,
21905 "{op} case={case} pos={pos}: got {got}, expected {expected}"
21906 ),
21907 other => panic!(
21908 "{op} case={case} pos={pos}: expected Float64, got {other:?}"
21909 ),
21910 }
21911 }
21912 }
21913 }
21914 }
21915
21916 #[test]
21917 fn isin_returns_bool_column() {
21918 let col = Column::from_values(vec![
21919 Scalar::Int64(1),
21920 Scalar::Int64(2),
21921 Scalar::Int64(3),
21922 Scalar::Null(NullKind::NaN),
21923 ])
21924 .expect("col");
21925 let needles = vec![Scalar::Int64(1), Scalar::Int64(3)];
21926 let r = col.isin(&needles).expect("isin");
21927 assert_eq!(r.dtype(), DType::Bool);
21928 assert_eq!(r.values()[0], Scalar::Bool(true));
21929 assert_eq!(r.values()[1], Scalar::Bool(false));
21930 assert_eq!(r.values()[2], Scalar::Bool(true));
21931 assert_eq!(r.values()[3], Scalar::Bool(false));
21932 }
21933
21934 #[test]
21935 fn isin_empty_needles_yields_all_false() {
21936 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21937 let r = col.isin(&[]).expect("isin");
21938 assert_eq!(r.values()[0], Scalar::Bool(false));
21939 assert_eq!(r.values()[1], Scalar::Bool(false));
21940 }
21941 }
21942
21943 mod sort_diff_duplicated_between {
21944 use fp_types::NullKind;
21945
21946 use super::*;
21947
21948 #[test]
21949 fn sort_values_ascending_puts_nulls_last() {
21950 let col = Column::from_values(vec![
21951 Scalar::Int64(3),
21952 Scalar::Null(NullKind::NaN),
21953 Scalar::Int64(1),
21954 Scalar::Int64(2),
21955 ])
21956 .expect("col");
21957 let s = col.sort_values(true).expect("sort");
21958 assert_eq!(s.values()[0], Scalar::Int64(1));
21959 assert_eq!(s.values()[1], Scalar::Int64(2));
21960 assert_eq!(s.values()[2], Scalar::Int64(3));
21961 assert!(s.values()[3].is_missing());
21962 }
21963
21964 #[test]
21965 fn sort_values_descending_keeps_nulls_last() {
21966 let col = Column::from_values(vec![
21967 Scalar::Int64(1),
21968 Scalar::Null(NullKind::NaN),
21969 Scalar::Int64(3),
21970 Scalar::Int64(2),
21971 ])
21972 .expect("col");
21973 let s = col.sort_values(false).expect("sort");
21974 assert_eq!(s.values()[0], Scalar::Int64(3));
21975 assert_eq!(s.values()[1], Scalar::Int64(2));
21976 assert_eq!(s.values()[2], Scalar::Int64(1));
21977 assert!(s.values()[3].is_missing());
21978 }
21979
21980 #[test]
21981 fn argsort_matches_take_sort_values() {
21982 let col =
21983 Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(1), Scalar::Int64(2)])
21984 .expect("col");
21985 let positions = col.argsort();
21986 assert_eq!(positions, vec![1, 2, 0]);
21987 let via_take = col.take(&positions).expect("take");
21988 let via_sort = col.sort_values(true).expect("sort");
21989 assert_eq!(via_take.values(), via_sort.values());
21990 }
21991
21992 fn scalar_sort_reference(values: &[Scalar], ascending: bool) -> Vec<Scalar> {
21995 let mut indexed: Vec<(usize, &Scalar)> = values.iter().enumerate().collect();
21996 indexed.sort_by(|a, b| crate::compare_scalars_na_last(a.1, b.1, ascending));
21997 indexed.into_iter().map(|(_, v)| v.clone()).collect()
21998 }
21999
22000 #[test]
22001 fn radix_sort_matches_scalar_reference_i64_and_f64() {
22002 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
22006 let mut next = || {
22007 state = state
22008 .wrapping_mul(6364136223846793005)
22009 .wrapping_add(1442695040888963407);
22010 state
22011 };
22012 for trial in 0..200 {
22013 let n = (next() % 400) as usize + 1;
22014 let i64_vals: Vec<Scalar> = (0..n)
22015 .map(|_| {
22016 let r = next();
22018 let v = if r % 7 == 0 {
22019 r as i64 } else {
22021 (r % 11) as i64 - 5
22022 };
22023 Scalar::Int64(v)
22024 })
22025 .collect();
22026 let f64_vals: Vec<Scalar> = i64_vals
22027 .iter()
22028 .map(|s| match s {
22029 Scalar::Int64(v) => {
22030 let f = (*v as f64) / 4.0;
22032 Scalar::Float64(if f == 0.0 { 0.0 } else { f })
22033 }
22034 _ => unreachable!(),
22035 })
22036 .collect();
22037 for (vals, label) in [(&i64_vals, "i64"), (&f64_vals, "f64")] {
22038 let col = Column::from_values(vals.clone()).expect("col");
22039 assert!(
22041 col.validity.all(),
22042 "{label} trial {trial}: unexpected missing"
22043 );
22044 for ascending in [true, false] {
22045 let got = col.sort_values(ascending).expect("sort").values().to_vec();
22046 let want = scalar_sort_reference(vals, ascending);
22047 assert_eq!(
22048 got, want,
22049 "{label} trial {trial} asc={ascending} sort mismatch"
22050 );
22051 }
22052 let perm = col.argsort();
22054 let via_perm: Vec<Scalar> = perm.iter().map(|&i| vals[i].clone()).collect();
22055 assert_eq!(
22056 via_perm,
22057 scalar_sort_reference(vals, true),
22058 "{label} trial {trial} argsort mismatch"
22059 );
22060 }
22061 }
22062 }
22063
22064 #[test]
22065 fn contiguous_utf8_argsort_matches_scalar_reference() {
22066 let raw = ["bee", "alpha", "bee", "alphabet", "", "zulu"];
22067 let scalars: Vec<Scalar> = raw
22068 .iter()
22069 .map(|value| Scalar::Utf8((*value).to_owned()))
22070 .collect();
22071 let scalar_col = Column::from_values(scalars.clone()).expect("scalar col");
22072 let mut bytes = Vec::new();
22073 let mut offsets = Vec::with_capacity(raw.len() + 1);
22074 offsets.push(0);
22075 for value in raw {
22076 bytes.extend_from_slice(value.as_bytes());
22077 offsets.push(bytes.len());
22078 }
22079 let contiguous_col = Column::from_utf8_contiguous(bytes, offsets);
22080
22081 assert_eq!(contiguous_col.argsort_with(true), vec![4, 1, 3, 0, 2, 5]);
22082 assert_eq!(contiguous_col.argsort_with(false), vec![5, 0, 2, 3, 1, 4]);
22083 for ascending in [true, false] {
22084 let got = contiguous_col
22085 .sort_values(ascending)
22086 .expect("contiguous sort")
22087 .values()
22088 .to_vec();
22089 let want = scalar_col
22090 .sort_values(ascending)
22091 .expect("scalar sort")
22092 .values()
22093 .to_vec();
22094 assert_eq!(got, want, "ascending={ascending}");
22095 }
22096 }
22097
22098 #[test]
22099 fn parallel_msd_radix_matches_serial_reference_qdrp7() {
22100 let n = 40_000usize;
22104 let strings: Vec<String> = (0..n)
22105 .map(|i| {
22106 let mixed = (i as u64)
22107 .wrapping_mul(0x9E37_79B9_7F4A_7C15)
22108 .rotate_left(17)
22109 ^ (i as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);
22110 format!("key_{mixed:016x}_{:04}", i % 97)
22111 })
22112 .collect();
22113 let spans: Vec<&[u8]> = strings.iter().map(|s| s.as_bytes()).collect();
22114 for ascending in [true, false] {
22115 let got = crate::utf8_msd_argsort_bytes(&spans, ascending);
22116 let mut want: Vec<usize> = (0..n).collect();
22117 want.sort_by(|&a, &b| {
22118 let ord = spans[a].cmp(spans[b]);
22119 if ascending { ord } else { ord.reverse() }
22120 });
22121 assert_eq!(
22122 got, want,
22123 "parallel radix != stable byte sort (asc={ascending})"
22124 );
22125 }
22126 }
22127
22128 #[test]
22129 fn contiguous_utf8_strict_witness_matches_byte_order_483i5() {
22130 fn contiguous(values: &[&str]) -> Column {
22131 let mut bytes = Vec::new();
22132 let mut offsets = Vec::with_capacity(values.len() + 1);
22133 offsets.push(0);
22134 for value in values {
22135 bytes.extend_from_slice(value.as_bytes());
22136 offsets.push(bytes.len());
22137 }
22138 Column::from_utf8_contiguous(bytes, offsets)
22139 }
22140
22141 assert!(
22142 contiguous(&["a", "b", "c"])
22143 .as_strictly_increasing_utf8_contiguous()
22144 .is_some()
22145 );
22146 assert!(
22147 contiguous(&[])
22148 .as_strictly_increasing_utf8_contiguous()
22149 .is_some()
22150 );
22151 assert!(
22152 contiguous(&["only"])
22153 .as_strictly_increasing_utf8_contiguous()
22154 .is_some()
22155 );
22156 assert!(
22157 contiguous(&["a", "a"])
22158 .as_strictly_increasing_utf8_contiguous()
22159 .is_none()
22160 );
22161 assert!(
22162 contiguous(&["b", "a"])
22163 .as_strictly_increasing_utf8_contiguous()
22164 .is_none()
22165 );
22166
22167 let scalar_backed = Column::from_values(vec![
22168 Scalar::Utf8("a".to_owned()),
22169 Scalar::Utf8("b".to_owned()),
22170 ])
22171 .expect("scalar-backed utf8");
22172 assert!(
22173 scalar_backed
22174 .as_strictly_increasing_utf8_contiguous()
22175 .is_none()
22176 );
22177 }
22178
22179 #[test]
22180 fn contiguous_utf8_lower_hex_sequence_certificate_jbyuc111111() {
22181 fn contiguous(values: &[&str]) -> Column {
22182 let mut bytes = Vec::new();
22183 let mut offsets = Vec::with_capacity(values.len() + 1);
22184 offsets.push(0);
22185 for value in values {
22186 bytes.extend_from_slice(value.as_bytes());
22187 offsets.push(bytes.len());
22188 }
22189 Column::from_utf8_contiguous(bytes, offsets)
22190 }
22191
22192 let certified = contiguous(&["id_0000000a", "id_0000000b", "id_0000000c"]);
22193 let (_, _, certificate) = certified
22194 .as_lower_hex_sequence_utf8_contiguous()
22195 .expect("lower-hex sequence certificate");
22196 assert_eq!(certificate.prefix_len(), 3);
22197 assert_eq!(certificate.hex_width(), 8);
22198 assert_eq!(certificate.width(), 11);
22199 assert_eq!(certificate.start(), 10);
22200 assert_eq!(certificate.value_at(2), Some(12));
22201
22202 assert!(
22203 contiguous(&["id_0000000a", "id_0000000c"])
22204 .as_lower_hex_sequence_utf8_contiguous()
22205 .is_none(),
22206 "gapped sequences are not certified"
22207 );
22208 assert!(
22209 contiguous(&["id_0000000a", "id_0000000B"])
22210 .as_lower_hex_sequence_utf8_contiguous()
22211 .is_none(),
22212 "uppercase hex is not certified by the lowercase witness"
22213 );
22214 assert!(
22215 contiguous(&["0000000a", "0000000b"])
22216 .as_lower_hex_sequence_utf8_contiguous()
22217 .is_none(),
22218 "a prefix is required so arbitrary all-hex strings fall back"
22219 );
22220 }
22221
22222 #[test]
22223 fn lower_hex_sequence_constructor_matches_contiguous_utf8_3wo1d() {
22224 let seeded =
22225 Column::from_lower_hex_sequence_utf8(b"id_", 0x0a, 3, 8).expect("seeded column");
22226 let manual = {
22227 let values = ["id_0000000a", "id_0000000b", "id_0000000c"];
22228 let mut bytes = Vec::new();
22229 let mut offsets = Vec::with_capacity(values.len() + 1);
22230 offsets.push(0);
22231 for value in values {
22232 bytes.extend_from_slice(value.as_bytes());
22233 offsets.push(bytes.len());
22234 }
22235 Column::from_utf8_contiguous(bytes, offsets)
22236 };
22237
22238 assert_eq!(seeded.values(), manual.values());
22239 let (_, _, certificate) = seeded
22240 .as_lower_hex_sequence_utf8_contiguous()
22241 .expect("seeded certificate");
22242 assert_eq!(certificate.prefix_len(), 3);
22243 assert_eq!(certificate.hex_width(), 8);
22244 assert_eq!(certificate.width(), 11);
22245 assert_eq!(certificate.start(), 10);
22246 assert_eq!(certificate.value_at(2), Some(12));
22247
22248 let empty =
22249 Column::from_lower_hex_sequence_utf8(b"id_", 0x0a, 0, 8).expect("empty column");
22250 assert!(empty.values().is_empty());
22251 assert!(empty.as_lower_hex_sequence_utf8_contiguous().is_none());
22252 let (empty_prefix, empty_certificate, empty_len) = empty
22253 .as_lower_hex_sequence_utf8()
22254 .expect("empty direct witness");
22255 assert_eq!(empty_prefix, b"id_");
22256 assert_eq!(empty_certificate.start(), 10);
22257 assert_eq!(empty_len, 0);
22258
22259 assert!(Column::from_lower_hex_sequence_utf8(b"id_", 0x0e, 3, 1).is_none());
22260 assert!(Column::from_lower_hex_sequence_utf8(b"", 0x0a, 3, 8).is_none());
22261 }
22262
22263 #[test]
22264 fn lower_hex_sequence_witness_stays_lazy_uza0447() {
22265 let column =
22266 Column::from_lower_hex_sequence_utf8(b"id_", 0x0a, 3, 8).expect("seeded column");
22267 assert!(matches!(
22268 &column.values,
22269 ScalarValues::LazyLowerHexSequenceUtf8 { .. }
22270 ));
22271 let ScalarValues::LazyLowerHexSequenceUtf8 { buffers, .. } = &column.values else {
22272 return;
22273 };
22274 assert!(buffers.get().is_none());
22275
22276 let (prefix, certificate, len) =
22277 column.as_lower_hex_sequence_utf8().expect("direct witness");
22278 assert_eq!(prefix, b"id_");
22279 assert_eq!(certificate.prefix_len(), 3);
22280 assert_eq!(certificate.hex_width(), 8);
22281 assert_eq!(certificate.start(), 10);
22282 assert_eq!(len, 3);
22283 assert!(
22284 buffers.get().is_none(),
22285 "direct witness must not materialize bytes"
22286 );
22287
22288 let (_, _, contiguous_certificate) = column
22289 .as_lower_hex_sequence_utf8_contiguous()
22290 .expect("contiguous materialization");
22291 assert_eq!(contiguous_certificate, certificate);
22292 assert!(
22293 buffers.get().is_some(),
22294 "contiguous accessor materializes exact old byte layout"
22295 );
22296 }
22297
22298 #[test]
22299 fn lower_hex_sequence_constructor_preserves_carry_uza0446() {
22300 let seeded =
22301 Column::from_lower_hex_sequence_utf8(b"id_", 0x0e, 4, 2).expect("seeded column");
22302 let manual = {
22303 let values = ["id_0e", "id_0f", "id_10", "id_11"];
22304 let mut bytes = Vec::new();
22305 let mut offsets = Vec::with_capacity(values.len() + 1);
22306 offsets.push(0);
22307 for value in values {
22308 bytes.extend_from_slice(value.as_bytes());
22309 offsets.push(bytes.len());
22310 }
22311 Column::from_utf8_contiguous(bytes, offsets)
22312 };
22313
22314 assert_eq!(seeded.values(), manual.values());
22315 let (_, _, certificate) = seeded
22316 .as_lower_hex_sequence_utf8_contiguous()
22317 .expect("seeded certificate");
22318 assert_eq!(certificate.prefix_len(), 3);
22319 assert_eq!(certificate.hex_width(), 2);
22320 assert_eq!(certificate.width(), 5);
22321 assert_eq!(certificate.start(), 14);
22322 assert_eq!(certificate.value_at(3), Some(17));
22323 }
22324
22325 #[test]
22326 fn abs_typed_matches_scalar_reference() {
22327 let mut state: u64 = 0x2545_F491_4F6C_DD1D;
22331 let mut next = || {
22332 state = state
22333 .wrapping_mul(6364136223846793005)
22334 .wrapping_add(1442695040888963407);
22335 state
22336 };
22337 for trial in 0..150 {
22338 let n = (next() % 300) as usize + 1;
22339 let i64_vals: Vec<Scalar> = (0..n)
22340 .map(|_| {
22341 let r = next();
22342 if r % 50 == 0 {
22343 Scalar::Int64(i64::MIN)
22344 } else {
22345 Scalar::Int64((r % 2000) as i64 - 1000)
22346 }
22347 })
22348 .collect();
22349 let f64_vals: Vec<Scalar> = i64_vals
22350 .iter()
22351 .map(|s| match s {
22352 Scalar::Int64(v) => {
22353 let f = if *v == i64::MIN {
22354 -0.0
22355 } else {
22356 *v as f64 / 4.0
22357 };
22358 Scalar::Float64(f)
22359 }
22360 _ => unreachable!(),
22361 })
22362 .collect();
22363 for vals in [&i64_vals, &f64_vals] {
22364 let col = Column::from_values(vals.clone()).expect("col");
22365 let got = col.abs().expect("abs").values().to_vec();
22366 let want: Vec<Scalar> = vals
22367 .iter()
22368 .map(|v| match v {
22369 Scalar::Int64(x) => Scalar::Int64(x.wrapping_abs()),
22370 Scalar::Float64(x) => Scalar::Float64(x.abs()),
22371 other => other.clone(),
22372 })
22373 .collect();
22374 for (g, w) in got.iter().zip(&want) {
22376 match (g, w) {
22377 (Scalar::Float64(a), Scalar::Float64(b)) => {
22378 assert_eq!(a.to_bits(), b.to_bits(), "trial {trial} float abs")
22379 }
22380 _ => assert_eq!(g, w, "trial {trial} abs"),
22381 }
22382 }
22383 }
22384 }
22385 }
22386
22387 #[test]
22388 #[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
22389 fn abs_typed_timing_vs_scalar() {
22390 use std::time::Instant;
22391 let n = 5_000_000usize;
22392 let iters = 10;
22393 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
22394 let mut next = || {
22395 state = state
22396 .wrapping_mul(6364136223846793005)
22397 .wrapping_add(1442695040888963407);
22398 state
22399 };
22400 let data: Vec<f64> = (0..n)
22401 .map(|_| (next() % 2_000_000) as f64 - 1_000_000.0)
22402 .collect();
22403 let mk = || Column::from_f64_values(data.clone());
22404
22405 let t0 = Instant::now();
22406 let mut chk = 0usize;
22407 for _ in 0..iters {
22408 chk ^= mk().abs().unwrap().len();
22409 }
22410 let typed = t0.elapsed();
22411
22412 let t1 = Instant::now();
22413 let mut chk2 = 0usize;
22414 for _ in 0..iters {
22415 let col = mk();
22416 let out: Vec<Scalar> = col
22417 .values()
22418 .iter()
22419 .map(|v| match v {
22420 Scalar::Float64(x) => Scalar::Float64(x.abs()),
22421 other => other.clone(),
22422 })
22423 .collect();
22424 chk2 ^= Column::new(DType::Float64, out).unwrap().len();
22425 }
22426 let scalar = t1.elapsed();
22427 let t2 = Instant::now();
22428 let mut sink = 0usize;
22429 for _ in 0..iters {
22430 sink ^= mk().len();
22431 }
22432 let build = t2.elapsed();
22433 let typed_op = typed.saturating_sub(build).as_secs_f64();
22434 let scalar_op = scalar.saturating_sub(build).as_secs_f64();
22435 eprintln!(
22436 "abs 5M f64 x{iters}: typed={typed:?} scalar={scalar:?} build={build:?} \
22437 op-only ratio={:.2}x (full {:.2}x, chk {chk}/{chk2}/{sink})",
22438 scalar_op / typed_op,
22439 scalar.as_secs_f64() / typed.as_secs_f64()
22440 );
22441 }
22442
22443 #[test]
22444 fn factorize_direct_address_matches_reference() {
22445 let mut state: u64 = 0x51A4_3C29_7E10_BB67;
22450 let mut next = || {
22451 state = state
22452 .wrapping_mul(6364136223846793005)
22453 .wrapping_add(1442695040888963407);
22454 state
22455 };
22456 for trial in 0..150 {
22457 let n = (next() % 300) as usize + 1;
22458 let data: Vec<i64> = (0..n).map(|_| (next() % 13) as i64 - 6).collect();
22459
22460 for sort in [false, true] {
22461 let mut uniques: Vec<i64> = Vec::new();
22464 let mut codes: Vec<i64> = Vec::with_capacity(n);
22465 for &v in &data {
22466 match uniques.iter().position(|&u| u == v) {
22467 Some(p) => codes.push(p as i64),
22468 None => {
22469 codes.push(uniques.len() as i64);
22470 uniques.push(v);
22471 }
22472 }
22473 }
22474 if sort {
22475 let mut order: Vec<usize> = (0..uniques.len()).collect();
22476 order.sort_by(|&a, &b| uniques[a].cmp(&uniques[b]));
22477 let mut remap = vec![0i64; uniques.len()];
22478 let sorted: Vec<i64> = order
22479 .iter()
22480 .enumerate()
22481 .map(|(new_pos, &orig)| {
22482 remap[orig] = new_pos as i64;
22483 uniques[orig]
22484 })
22485 .collect();
22486 for c in &mut codes {
22487 *c = remap[*c as usize];
22488 }
22489 uniques = sorted;
22490 }
22491
22492 let col = Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
22493 .expect("col");
22494 let (code_col, uniq_col) =
22495 col.factorize_with_options(sort, true).expect("factorize");
22496 let got_codes: Vec<i64> = code_col
22497 .values()
22498 .iter()
22499 .filter_map(|v| match v {
22500 Scalar::Int64(c) => Some(*c),
22501 _ => None,
22502 })
22503 .collect();
22504 let got_uniques: Vec<i64> = uniq_col
22505 .values()
22506 .iter()
22507 .filter_map(|v| match v {
22508 Scalar::Int64(c) => Some(*c),
22509 _ => None,
22510 })
22511 .collect();
22512 assert_eq!(got_codes.len(), code_col.len(), "non-int code");
22513 assert_eq!(got_uniques.len(), uniq_col.len(), "non-int unique");
22514 assert_eq!(got_codes, codes, "trial {trial} sort={sort} codes");
22515 assert_eq!(got_uniques, uniques, "trial {trial} sort={sort} uniques");
22516 }
22517 }
22518 }
22519
22520 #[test]
22521 #[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
22522 fn factorize_direct_address_timing_vs_hashmap() {
22523 use std::{collections::HashMap, time::Instant};
22524 let n = 5_000_000usize;
22525 let iters = 10;
22526 for cardinality in [1_000u64, 2_000_000u64] {
22527 let mut state: u64 = 0x2468_ACE0_1357_9BDF ^ cardinality;
22528 let mut next = || {
22529 state = state
22530 .wrapping_mul(6364136223846793005)
22531 .wrapping_add(1442695040888963407);
22532 state
22533 };
22534 let data: Vec<i64> = (0..n).map(|_| (next() % cardinality) as i64).collect();
22535
22536 let col = Column::from_i64_values(data.clone());
22537 let t0 = Instant::now();
22538 let mut chk = 0i64;
22539 for _ in 0..iters {
22540 let (codes, _u) = col.factorize_with_options(false, true).expect("da");
22541 if let Scalar::Int64(c) = &codes.values()[n - 1] {
22542 chk ^= *c;
22543 }
22544 }
22545 let direct = t0.elapsed();
22546
22547 let scalar_col =
22549 Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
22550 .expect("col");
22551 let t1 = Instant::now();
22552 let mut chk2 = 0i64;
22553 for _ in 0..iters {
22554 let mut map: HashMap<i64, i64> = HashMap::new();
22555 let mut uniques = 0i64;
22556 let mut last = 0i64;
22557 for v in scalar_col.values() {
22558 if let Scalar::Int64(i) = v {
22559 let code = *map.entry(*i).or_insert_with(|| {
22560 let c = uniques;
22561 uniques += 1;
22562 c
22563 });
22564 last = code;
22565 }
22566 }
22567 chk2 ^= last;
22568 }
22569 let scalar = t1.elapsed();
22570 eprintln!(
22571 "factorize 5M i64 card={cardinality} x{iters}: direct={direct:?} hashmap={scalar:?} ratio={:.2}x (chk {chk}/{chk2})",
22572 scalar.as_secs_f64() / direct.as_secs_f64()
22573 );
22574 }
22575 }
22576
22577 #[test]
22578 fn duplicated_typed_matches_bruteforce_reference() {
22579 let mut state: u64 = 0xD1B5_4A32_D192_ED03;
22585 let mut next = || {
22586 state = state
22587 .wrapping_mul(6364136223846793005)
22588 .wrapping_add(1442695040888963407);
22589 state
22590 };
22591 let fbits = |f: f64| (if f == 0.0 { 0.0 } else { f }).to_bits();
22592 for trial in 0..150 {
22593 let n = (next() % 300) as usize + 1;
22594 let raw: Vec<i64> = (0..n).map(|_| (next() % 9) as i64 - 4).collect();
22596 let i64_vals: Vec<Scalar> = raw.iter().map(|&v| Scalar::Int64(v)).collect();
22597 let f64_vals: Vec<Scalar> = raw
22598 .iter()
22599 .map(|&v| Scalar::Float64(v as f64 / 2.0))
22600 .collect();
22601 let i64_keys: Vec<i64> = raw.clone();
22602 let f64_keys: Vec<u64> = raw.iter().map(|&v| fbits(v as f64 / 2.0)).collect();
22603
22604 for keep in ["first", "last", "false"] {
22605 let bf = |eq_keys: &dyn Fn(usize, usize) -> bool| -> Vec<bool> {
22607 (0..n)
22608 .map(|i| match keep {
22609 "first" => (0..i).any(|j| eq_keys(i, j)),
22610 "last" => (i + 1..n).any(|j| eq_keys(i, j)),
22611 _ => (0..n).any(|j| j != i && eq_keys(i, j)),
22612 })
22613 .collect()
22614 };
22615 let want_i = bf(&|a, b| i64_keys[a] == i64_keys[b]);
22616 let want_f = bf(&|a, b| f64_keys[a] == f64_keys[b]);
22617
22618 let col_i = Column::from_values(i64_vals.clone()).expect("i64 col");
22619 let got_i: Vec<bool> = col_i
22620 .duplicated_keep(keep)
22621 .expect("dup i64")
22622 .values()
22623 .iter()
22624 .map(|v| matches!(v, Scalar::Bool(true)))
22625 .collect();
22626 assert_eq!(got_i, want_i, "i64 trial {trial} keep={keep}");
22627
22628 let col_f = Column::from_values(f64_vals.clone()).expect("f64 col");
22629 let got_f: Vec<bool> = col_f
22630 .duplicated_keep(keep)
22631 .expect("dup f64")
22632 .values()
22633 .iter()
22634 .map(|v| matches!(v, Scalar::Bool(true)))
22635 .collect();
22636 assert_eq!(got_f, want_f, "f64 trial {trial} keep={keep}");
22637 }
22638 }
22639 }
22640
22641 #[test]
22642 #[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
22643 fn duplicated_typed_timing_vs_scalar() {
22644 use std::{collections::HashSet, time::Instant};
22645 let n = 5_000_000usize;
22646 let iters = 10;
22647 #[derive(Hash, PartialEq, Eq)]
22650 enum OldKey {
22651 Int64(i64),
22652 Null,
22653 }
22654 for cardinality in [1_000u64, 2_000_000u64] {
22655 let mut state: u64 = 0x0FED_CBA9_8765_4321 ^ cardinality;
22656 let mut next = || {
22657 state = state
22658 .wrapping_mul(6364136223846793005)
22659 .wrapping_add(1442695040888963407);
22660 state
22661 };
22662 let data: Vec<i64> = (0..n).map(|_| (next() % cardinality) as i64).collect();
22663
22664 let col = Column::from_i64_values(data.clone());
22665 let t0 = Instant::now();
22666 let mut chk = 0usize;
22667 for _ in 0..iters {
22668 let d = col.duplicated_keep("first").expect("typed");
22669 chk ^= d
22670 .values()
22671 .iter()
22672 .filter(|v| matches!(v, Scalar::Bool(true)))
22673 .count();
22674 }
22675 let typed = t0.elapsed();
22676
22677 let scalar_col =
22678 Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
22679 .expect("col");
22680 let t1 = Instant::now();
22681 let mut chk2 = 0usize;
22682 for _ in 0..iters {
22683 let mut seen: HashSet<OldKey> = HashSet::new();
22684 let mut count = 0usize;
22685 for v in scalar_col.values() {
22686 let key = if v.is_missing() {
22687 OldKey::Null
22688 } else if let Scalar::Int64(i) = v {
22689 OldKey::Int64(*i)
22690 } else {
22691 OldKey::Null
22692 };
22693 if !seen.insert(key) {
22694 count += 1;
22695 }
22696 }
22697 chk2 ^= count;
22698 }
22699 let scalar = t1.elapsed();
22700 eprintln!(
22701 "duplicated 5M i64 card={cardinality} x{iters}: typed={typed:?} old_keyenum_siphash={scalar:?} ratio={:.2}x (chk {chk}/{chk2})",
22702 scalar.as_secs_f64() / typed.as_secs_f64()
22703 );
22704 }
22705 }
22706
22707 #[test]
22708 #[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
22709 fn radix_sort_timing_vs_scalar() {
22710 use std::time::Instant;
22711 let n = 5_000_000usize;
22712 let mut state: u64 = 0x1234_5678_9ABC_DEF0;
22713 let mut next = || {
22714 state = state
22715 .wrapping_mul(6364136223846793005)
22716 .wrapping_add(1442695040888963407);
22717 state
22718 };
22719 let data: Vec<i64> = (0..n).map(|_| next() as i64).collect();
22720 let col = Column::from_i64_values(data.clone());
22721
22722 let iters = 10;
22723 let t0 = Instant::now();
22724 let mut checksum = 0i64;
22725 for _ in 0..iters {
22726 let sorted = col.sort_values(true).expect("radix");
22727 checksum ^= match &sorted.values()[0] {
22728 Scalar::Int64(v) => *v,
22729 _ => 0,
22730 };
22731 }
22732 let radix = t0.elapsed();
22733
22734 let scalar_col = Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
22736 .expect("scalar col");
22737 let t1 = Instant::now();
22738 let mut checksum2 = 0i64;
22739 for _ in 0..iters {
22740 let mut indexed: Vec<(usize, &Scalar)> =
22741 scalar_col.values().iter().enumerate().collect();
22742 indexed.sort_by(|a, b| crate::compare_scalars_na_last(a.1, b.1, true));
22743 if let Scalar::Int64(v) = indexed[0].1 {
22744 checksum2 ^= *v;
22745 }
22746 }
22747 let scalar = t1.elapsed();
22748 eprintln!(
22749 "sort_single 5M i64 x{iters}: radix={radix:?} scalar={scalar:?} ratio={:.2}x (chk {checksum}/{checksum2})",
22750 scalar.as_secs_f64() / radix.as_secs_f64()
22751 );
22752 }
22753
22754 #[test]
22755 fn diff_periods_one_subtracts_prev() {
22756 let col =
22757 Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(8), Scalar::Int64(10)])
22758 .expect("col");
22759 let d = col.diff(1).expect("diff");
22760 assert!(d.values()[0].is_missing());
22761 assert_eq!(d.values()[1], Scalar::Float64(3.0));
22762 assert_eq!(d.values()[2], Scalar::Float64(2.0));
22763 assert_eq!(d.dtype(), DType::Float64);
22764 }
22765
22766 #[test]
22767 fn diff_negative_period_looks_ahead() {
22768 let col =
22769 Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(8), Scalar::Int64(10)])
22770 .expect("col");
22771 let d = col.diff(-1).expect("diff");
22772 assert_eq!(d.values()[0], Scalar::Float64(-3.0));
22773 assert_eq!(d.values()[1], Scalar::Float64(-2.0));
22774 assert!(d.values()[2].is_missing());
22775 }
22776
22777 #[test]
22778 fn diff_timedelta64_returns_timedelta_e607u() {
22779 let one_hour = 3_600 * 1_000_000_000_i64;
22782 let col = Column::from_values(vec![
22783 Scalar::Timedelta64(one_hour),
22784 Scalar::Timedelta64(3 * one_hour),
22785 Scalar::Timedelta64(2 * one_hour),
22786 ])
22787 .expect("col");
22788 let d = col.diff(1).expect("diff");
22789 assert_eq!(d.dtype(), DType::Timedelta64);
22790 assert!(d.values()[0].is_missing()); assert_eq!(d.values()[1], Scalar::Timedelta64(2 * one_hour));
22792 assert_eq!(d.values()[2], Scalar::Timedelta64(-one_hour));
22793 }
22794
22795 #[test]
22796 fn diff_timedelta64_nat_propagates_e607u() {
22797 use fp_types::Timedelta;
22798 let one_hour = 3_600 * 1_000_000_000_i64;
22799 let col = Column::from_values(vec![
22800 Scalar::Timedelta64(one_hour),
22801 Scalar::Timedelta64(Timedelta::NAT),
22802 Scalar::Timedelta64(2 * one_hour),
22803 ])
22804 .expect("col");
22805 let d = col.diff(1).expect("diff");
22806 assert_eq!(d.dtype(), DType::Timedelta64);
22807 assert!(d.values()[0].is_missing());
22808 assert!(d.values()[1].is_missing()); assert!(d.values()[2].is_missing()); }
22811
22812 #[test]
22813 fn duplicated_keep_first() {
22814 let col = Column::from_values(vec![
22815 Scalar::Int64(1),
22816 Scalar::Int64(2),
22817 Scalar::Int64(1),
22818 Scalar::Int64(3),
22819 Scalar::Int64(2),
22820 ])
22821 .expect("col");
22822 let d = col.duplicated().expect("duplicated");
22823 assert_eq!(d.values()[0], Scalar::Bool(false));
22824 assert_eq!(d.values()[1], Scalar::Bool(false));
22825 assert_eq!(d.values()[2], Scalar::Bool(true));
22826 assert_eq!(d.values()[3], Scalar::Bool(false));
22827 assert_eq!(d.values()[4], Scalar::Bool(true));
22828 }
22829
22830 #[test]
22831 fn duplicated_treats_nulls_as_one_bucket() {
22832 let col = Column::from_values(vec![
22833 Scalar::Null(NullKind::NaN),
22834 Scalar::Null(NullKind::NaN),
22835 Scalar::Int64(1),
22836 ])
22837 .expect("col");
22838 let d = col.duplicated().expect("duplicated");
22839 assert_eq!(d.values()[0], Scalar::Bool(false));
22840 assert_eq!(d.values()[1], Scalar::Bool(true));
22841 assert_eq!(d.values()[2], Scalar::Bool(false));
22842 }
22843
22844 #[test]
22845 fn duplicated_keep_variants_match_pandas() {
22846 let col = Column::from_values(vec![
22847 Scalar::Int64(1),
22848 Scalar::Int64(2),
22849 Scalar::Int64(1),
22850 Scalar::Int64(1),
22851 Scalar::Int64(3),
22852 Scalar::Int64(2),
22853 Scalar::Null(NullKind::NaN),
22854 Scalar::Null(NullKind::NaN),
22855 ])
22856 .expect("col");
22857
22858 let last = col.duplicated_keep("last").expect("duplicated last");
22859 assert_eq!(
22860 last.values(),
22861 &[
22862 Scalar::Bool(true),
22863 Scalar::Bool(true),
22864 Scalar::Bool(true),
22865 Scalar::Bool(false),
22866 Scalar::Bool(false),
22867 Scalar::Bool(false),
22868 Scalar::Bool(true),
22869 Scalar::Bool(false),
22870 ]
22871 );
22872
22873 let none = col.duplicated_keep("false").expect("duplicated none");
22874 assert_eq!(
22875 none.values(),
22876 &[
22877 Scalar::Bool(true),
22878 Scalar::Bool(true),
22879 Scalar::Bool(true),
22880 Scalar::Bool(true),
22881 Scalar::Bool(false),
22882 Scalar::Bool(true),
22883 Scalar::Bool(true),
22884 Scalar::Bool(true),
22885 ]
22886 );
22887 }
22888
22889 #[test]
22890 fn between_inclusive_both() {
22891 let col = Column::from_values(vec![
22892 Scalar::Float64(0.5),
22893 Scalar::Float64(1.0),
22894 Scalar::Float64(5.0),
22895 Scalar::Float64(6.0),
22896 ])
22897 .expect("col");
22898 let b = col.between(1.0, 5.0, true).expect("between");
22899 assert_eq!(b.values()[0], Scalar::Bool(false));
22900 assert_eq!(b.values()[1], Scalar::Bool(true));
22901 assert_eq!(b.values()[2], Scalar::Bool(true));
22902 assert_eq!(b.values()[3], Scalar::Bool(false));
22903 }
22904
22905 #[test]
22906 fn between_exclusive() {
22907 let col = Column::from_values(vec![
22908 Scalar::Float64(1.0),
22909 Scalar::Float64(3.0),
22910 Scalar::Float64(5.0),
22911 ])
22912 .expect("col");
22913 let b = col.between(1.0, 5.0, false).expect("between");
22914 assert_eq!(b.values()[0], Scalar::Bool(false));
22915 assert_eq!(b.values()[1], Scalar::Bool(true));
22916 assert_eq!(b.values()[2], Scalar::Bool(false));
22917 }
22918
22919 #[test]
22920 fn between_left_and_right_inclusive_edges() {
22921 let col = Column::from_values(vec![
22922 Scalar::Float64(1.0),
22923 Scalar::Float64(3.0),
22924 Scalar::Float64(5.0),
22925 ])
22926 .expect("col");
22927
22928 let left = col
22929 .between_inclusive(1.0, 5.0, "left")
22930 .expect("between left");
22931 assert_eq!(
22932 left.values(),
22933 &[Scalar::Bool(true), Scalar::Bool(true), Scalar::Bool(false),]
22934 );
22935
22936 let right = col
22937 .between_inclusive(1.0, 5.0, "right")
22938 .expect("between right");
22939 assert_eq!(
22940 right.values(),
22941 &[Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(true),]
22942 );
22943 }
22944
22945 #[test]
22946 fn between_missing_maps_to_false() {
22947 let col = Column::from_values(vec![Scalar::Null(NullKind::NaN), Scalar::Float64(3.0)])
22948 .expect("col");
22949 let b = col.between(1.0, 5.0, true).expect("between");
22950 assert_eq!(b.values()[0], Scalar::Bool(false));
22951 assert_eq!(b.values()[1], Scalar::Bool(true));
22952 }
22953 }
22954
22955 mod factorize {
22956 use fp_types::NullKind;
22957
22958 use super::*;
22959
22960 #[test]
22961 fn factorize_preserves_first_seen_order() {
22962 let col = Column::from_values(vec![
22963 Scalar::Utf8("b".into()),
22964 Scalar::Utf8("a".into()),
22965 Scalar::Utf8("b".into()),
22966 Scalar::Utf8("c".into()),
22967 Scalar::Utf8("a".into()),
22968 ])
22969 .expect("col");
22970
22971 let (codes, uniques) = col.factorize().expect("factorize");
22972 assert_eq!(codes.dtype(), DType::Int64);
22973 assert_eq!(
22974 codes.values(),
22975 &[
22976 Scalar::Int64(0),
22977 Scalar::Int64(1),
22978 Scalar::Int64(0),
22979 Scalar::Int64(2),
22980 Scalar::Int64(1),
22981 ]
22982 );
22983 assert_eq!(
22984 uniques.values(),
22985 &[
22986 Scalar::Utf8("b".into()),
22987 Scalar::Utf8("a".into()),
22988 Scalar::Utf8("c".into()),
22989 ]
22990 );
22991 }
22992
22993 #[test]
22994 fn factorize_lazy_contiguous_utf8_default_witness_preserves_order() {
22995 let col = Column {
22996 dtype: DType::Utf8,
22997 values: ScalarValues::lazy_contiguous_utf8_arc(
22998 Arc::from(&b"baacaab"[..]),
22999 Arc::from([0_usize, 1, 3, 4, 6, 7]),
23000 ),
23001 validity: ValidityMask::all_valid(5),
23002 data: None,
23003 };
23004
23005 let (codes, uniques) = col.factorize().expect("factorize");
23006 assert_eq!(
23007 codes.values(),
23008 &[
23009 Scalar::Int64(0),
23010 Scalar::Int64(1),
23011 Scalar::Int64(2),
23012 Scalar::Int64(1),
23013 Scalar::Int64(0),
23014 ]
23015 );
23016 assert_eq!(
23017 uniques.values(),
23018 &[
23019 Scalar::Utf8("b".into()),
23020 Scalar::Utf8("aa".into()),
23021 Scalar::Utf8("c".into()),
23022 ]
23023 );
23024
23025 let (sorted_codes, sorted_uniques) =
23026 col.factorize_with_options(true, true).expect("factorize");
23027 assert_eq!(
23028 sorted_codes.values(),
23029 &[
23030 Scalar::Int64(1),
23031 Scalar::Int64(0),
23032 Scalar::Int64(2),
23033 Scalar::Int64(0),
23034 Scalar::Int64(1),
23035 ]
23036 );
23037 assert_eq!(
23038 sorted_uniques.values(),
23039 &[
23040 Scalar::Utf8("aa".into()),
23041 Scalar::Utf8("b".into()),
23042 Scalar::Utf8("c".into()),
23043 ]
23044 );
23045 }
23046
23047 #[test]
23048 fn factorize_missing_values_map_to_negative_one() {
23049 let col = Column::from_values(vec![
23050 Scalar::Float64(1.5),
23051 Scalar::Null(NullKind::NaN),
23052 Scalar::Float64(2.5),
23053 Scalar::Null(NullKind::Null),
23054 Scalar::Float64(1.5),
23055 ])
23056 .expect("col");
23057
23058 let (codes, uniques) = col.factorize().expect("factorize");
23059 assert_eq!(
23060 codes.values(),
23061 &[
23062 Scalar::Int64(0),
23063 Scalar::Int64(-1),
23064 Scalar::Int64(1),
23065 Scalar::Int64(-1),
23066 Scalar::Int64(0),
23067 ]
23068 );
23069 assert_eq!(uniques.dtype(), DType::Float64);
23070 assert_eq!(
23071 uniques.values(),
23072 &[Scalar::Float64(1.5), Scalar::Float64(2.5)]
23073 );
23074 }
23075
23076 #[test]
23077 fn factorize_empty_column_returns_empty_outputs() {
23078 let col = Column::new(DType::Int64, Vec::new()).expect("col");
23079 let (codes, uniques) = col.factorize().expect("factorize");
23080 assert!(codes.is_empty());
23081 assert!(uniques.is_empty());
23082 assert_eq!(codes.dtype(), DType::Int64);
23083 assert_eq!(uniques.dtype(), DType::Int64);
23084 }
23085
23086 #[test]
23087 fn factorize_with_sort_sorts_uniques_and_relabels_codes() {
23088 let col = Column::from_values(vec![
23089 Scalar::Utf8("b".into()),
23090 Scalar::Utf8("a".into()),
23091 Scalar::Utf8("b".into()),
23092 Scalar::Utf8("c".into()),
23093 Scalar::Utf8("a".into()),
23094 ])
23095 .expect("col");
23096
23097 let (codes, uniques) = col.factorize_with_options(true, true).expect("factorize");
23098 assert_eq!(
23099 codes.values(),
23100 &[
23101 Scalar::Int64(1),
23102 Scalar::Int64(0),
23103 Scalar::Int64(1),
23104 Scalar::Int64(2),
23105 Scalar::Int64(0),
23106 ]
23107 );
23108 assert_eq!(
23109 uniques.values(),
23110 &[
23111 Scalar::Utf8("a".into()),
23112 Scalar::Utf8("b".into()),
23113 Scalar::Utf8("c".into()),
23114 ]
23115 );
23116 }
23117
23118 #[test]
23119 fn factorize_with_use_na_sentinel_false_keeps_missing_in_uniques() {
23120 let col = Column::from_values(vec![
23121 Scalar::Float64(1.5),
23122 Scalar::Null(NullKind::NaN),
23123 Scalar::Float64(2.5),
23124 Scalar::Null(NullKind::Null),
23125 Scalar::Float64(1.5),
23126 ])
23127 .expect("col");
23128
23129 let (codes, uniques) = col.factorize_with_options(false, false).expect("factorize");
23130 assert_eq!(
23131 codes.values(),
23132 &[
23133 Scalar::Int64(0),
23134 Scalar::Int64(1),
23135 Scalar::Int64(2),
23136 Scalar::Int64(1),
23137 Scalar::Int64(0),
23138 ]
23139 );
23140 assert_eq!(uniques.dtype(), DType::Float64);
23141 assert_eq!(
23142 uniques.values(),
23143 &[
23144 Scalar::Float64(1.5),
23145 Scalar::Null(NullKind::NaN),
23146 Scalar::Float64(2.5),
23147 ]
23148 );
23149 }
23150
23151 #[test]
23152 fn factorize_with_sort_and_use_na_sentinel_false_sorts_missing_last() {
23153 let col = Column::from_values(vec![
23154 Scalar::Utf8("b".into()),
23155 Scalar::Null(NullKind::Null),
23156 Scalar::Utf8("a".into()),
23157 Scalar::Utf8("b".into()),
23158 Scalar::Null(NullKind::NaN),
23159 ])
23160 .expect("col");
23161
23162 let (codes, uniques) = col.factorize_with_options(true, false).expect("factorize");
23163 assert_eq!(
23164 codes.values(),
23165 &[
23166 Scalar::Int64(1),
23167 Scalar::Int64(2),
23168 Scalar::Int64(0),
23169 Scalar::Int64(1),
23170 Scalar::Int64(2),
23171 ]
23172 );
23173 assert_eq!(
23174 uniques.values(),
23175 &[
23176 Scalar::Utf8("a".into()),
23177 Scalar::Utf8("b".into()),
23178 Scalar::Null(NullKind::Null),
23179 ]
23180 );
23181 }
23182 }
23183
23184 mod aggregation_helpers {
23185 use fp_types::{NullKind, Timedelta};
23186
23187 use super::*;
23188
23189 fn assert_float_nan(value: Scalar) {
23190 assert!(
23191 matches!(value, Scalar::Float64(v) if v.is_nan()),
23192 "expected Float64(NaN), got {value:?}"
23193 );
23194 }
23195
23196 #[test]
23197 fn sum_skips_nulls() {
23198 let col = Column::from_values(vec![
23199 Scalar::Float64(1.0),
23200 Scalar::Null(NullKind::NaN),
23201 Scalar::Float64(2.0),
23202 Scalar::Float64(3.0),
23203 ])
23204 .expect("col");
23205 let sum = col.sum();
23206 assert!(matches!(sum, Scalar::Float64(_)), "expected Float64 result");
23207 if let Scalar::Float64(v) = sum {
23208 assert!((v - 6.0).abs() < 1e-9);
23209 }
23210 }
23211
23212 #[test]
23213 fn sum_empty_is_zero() {
23214 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23215 assert_eq!(col.sum(), Scalar::Float64(0.0));
23216 }
23217
23218 #[test]
23219 fn mean_matches_sum_over_count() {
23220 let col = Column::from_values(vec![
23221 Scalar::Float64(2.0),
23222 Scalar::Float64(4.0),
23223 Scalar::Float64(6.0),
23224 ])
23225 .expect("col");
23226 let mean = col.mean();
23227 assert!(
23228 matches!(mean, Scalar::Float64(_)),
23229 "expected Float64 result"
23230 );
23231 if let Scalar::Float64(v) = mean {
23232 assert!((v - 4.0).abs() < 1e-9);
23233 }
23234 }
23235
23236 #[test]
23237 fn mean_empty_is_null() {
23238 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23239 assert!(col.mean().is_missing());
23240 }
23241
23242 #[test]
23243 fn min_max_extrema_skip_nulls() {
23244 let col = Column::from_values(vec![
23245 Scalar::Int64(3),
23246 Scalar::Null(NullKind::NaN),
23247 Scalar::Int64(1),
23248 Scalar::Int64(5),
23249 Scalar::Int64(2),
23250 ])
23251 .expect("col");
23252 assert_eq!(col.min(), Scalar::Int64(1));
23253 assert_eq!(col.max(), Scalar::Int64(5));
23254 }
23255
23256 #[test]
23257 fn median_of_odd_count() {
23258 let col = Column::from_values(vec![
23259 Scalar::Float64(1.0),
23260 Scalar::Float64(5.0),
23261 Scalar::Float64(3.0),
23262 ])
23263 .expect("col");
23264 let median = col.median();
23265 assert!(
23266 matches!(median, Scalar::Float64(_)),
23267 "expected Float64 result"
23268 );
23269 if let Scalar::Float64(v) = median {
23270 assert!((v - 3.0).abs() < 1e-9);
23271 }
23272 }
23273
23274 #[test]
23275 fn prod_multiplies_non_nulls() {
23276 let col = Column::from_values(vec![
23277 Scalar::Float64(2.0),
23278 Scalar::Null(NullKind::NaN),
23279 Scalar::Float64(3.0),
23280 Scalar::Float64(4.0),
23281 ])
23282 .expect("col");
23283 let prod = col.prod();
23284 assert!(
23285 matches!(prod, Scalar::Float64(_)),
23286 "expected Float64 result"
23287 );
23288 if let Scalar::Float64(v) = prod {
23289 assert!((v - 24.0).abs() < 1e-9);
23290 }
23291 }
23292
23293 #[test]
23294 fn prod_empty_is_one() {
23295 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23296 assert_eq!(col.prod(), Scalar::Float64(1.0));
23297 }
23298
23299 #[test]
23300 fn product_alias_matches_prod() {
23301 let col = Column::from_values(vec![
23302 Scalar::Float64(2.0),
23303 Scalar::Null(NullKind::NaN),
23304 Scalar::Float64(3.0),
23305 ])
23306 .expect("col");
23307 assert_eq!(col.product(), col.prod());
23308 }
23309
23310 #[test]
23311 fn skipna_false_aggregate_variants_propagate_nan() {
23312 let col = Column::from_values(vec![
23313 Scalar::Float64(2.0),
23314 Scalar::Null(NullKind::NaN),
23315 Scalar::Float64(4.0),
23316 ])
23317 .expect("col");
23318
23319 assert_eq!(col.sum_skipna(true), col.sum());
23320 assert_float_nan(col.sum_skipna(false));
23321 assert_float_nan(col.mean_skipna(false));
23322 assert_float_nan(col.min_skipna(false));
23323 assert_float_nan(col.max_skipna(false));
23324 assert_float_nan(col.median_skipna(false));
23325 assert_float_nan(col.prod_skipna(false));
23326 assert_float_nan(col.var_skipna(1, false));
23327 assert_float_nan(col.std_skipna(1, false));
23328 assert_float_nan(col.sem_skipna(1, false));
23329 }
23330
23331 #[test]
23332 fn skipna_false_timedelta_aggregate_variants_propagate_nat() {
23333 let col = Column::from_values(vec![
23334 Scalar::Timedelta64(Timedelta::NANOS_PER_SEC),
23335 Scalar::Timedelta64(Timedelta::NAT),
23336 ])
23337 .expect("col");
23338
23339 assert_eq!(col.sum_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
23340 assert_eq!(col.mean_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
23341 assert_eq!(col.min_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
23342 assert_eq!(col.max_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
23343 }
23344
23345 #[test]
23346 fn quantile_median_of_sorted_values() {
23347 let col = Column::from_values(vec![
23348 Scalar::Float64(1.0),
23349 Scalar::Float64(2.0),
23350 Scalar::Float64(3.0),
23351 Scalar::Float64(4.0),
23352 Scalar::Float64(5.0),
23353 ])
23354 .expect("col");
23355 let quantile = col.quantile(0.5);
23356 assert!(
23357 matches!(quantile, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9),
23358 "expected Float64 median, got {quantile:?}"
23359 );
23360 }
23361
23362 #[test]
23363 fn quantile_empty_is_null() {
23364 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23365 assert!(col.quantile(0.5).is_missing());
23366 }
23367
23368 #[test]
23369 fn quantile_out_of_range_is_null() {
23370 let col = Column::from_values(vec![Scalar::Float64(1.0)]).expect("col");
23371 assert!(col.quantile(1.5).is_missing());
23372 assert!(col.quantile(-0.1).is_missing());
23373 }
23374
23375 #[test]
23376 fn mode_returns_tied_max_frequency() {
23377 let col = Column::from_values(vec![
23378 Scalar::Int64(1),
23379 Scalar::Int64(2),
23380 Scalar::Int64(2),
23381 Scalar::Int64(3),
23382 Scalar::Int64(3),
23383 ])
23384 .expect("col");
23385 let m = col.mode().expect("mode");
23386 assert_eq!(m.values(), &[Scalar::Int64(2), Scalar::Int64(3)]);
23387 }
23388
23389 #[test]
23390 fn mode_ignores_missing_values() {
23391 let col = Column::from_values(vec![
23392 Scalar::Int64(1),
23393 Scalar::Null(NullKind::NaN),
23394 Scalar::Int64(1),
23395 Scalar::Null(NullKind::NaN),
23396 ])
23397 .expect("col");
23398 let m = col.mode().expect("mode");
23399 assert_eq!(m.values(), &[Scalar::Int64(1)]);
23400 }
23401
23402 #[test]
23403 fn mode_empty_is_empty_same_dtype() {
23404 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23405 let m = col.mode().expect("mode");
23406 assert!(m.is_empty());
23407 }
23408
23409 #[test]
23410 fn memory_usage_fixed_width_for_numeric() {
23411 let col =
23412 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
23413 .expect("col");
23414 let usage = col.memory_usage(false);
23415 assert_eq!(usage, 25);
23417 }
23418
23419 #[test]
23420 fn memory_usage_deep_counts_utf8_bytes() {
23421 let col = Column::from_values(vec![
23422 Scalar::Utf8("hi".into()),
23423 Scalar::Utf8("world".into()),
23424 ])
23425 .expect("col");
23426 let shallow = col.memory_usage(false);
23427 let deep = col.memory_usage(true);
23428 assert!(deep > shallow);
23429 assert_eq!(deep - shallow, 7);
23431 }
23432
23433 #[test]
23434 fn interpolate_fills_interior_gaps() {
23435 let col = Column::from_values(vec![
23436 Scalar::Float64(1.0),
23437 Scalar::Null(NullKind::NaN),
23438 Scalar::Null(NullKind::NaN),
23439 Scalar::Float64(4.0),
23440 ])
23441 .expect("col");
23442 let r = col.interpolate_linear().expect("interpolate");
23443 assert_eq!(r.values()[0], Scalar::Float64(1.0));
23444 assert!(
23445 matches!(&r.values()[1], Scalar::Float64(v) if (*v - 2.0).abs() < 1e-9),
23446 "expected Float64, got {:?}",
23447 r.values()[1]
23448 );
23449 assert!(
23450 matches!(&r.values()[2], Scalar::Float64(v) if (*v - 3.0).abs() < 1e-9),
23451 "expected Float64, got {:?}",
23452 r.values()[2]
23453 );
23454 assert_eq!(r.values()[3], Scalar::Float64(4.0));
23455 }
23456
23457 #[test]
23458 fn interpolate_leading_null_stays_null_trailing_forward_fills() {
23459 let col = Column::from_values(vec![
23465 Scalar::Null(NullKind::NaN),
23466 Scalar::Float64(2.0),
23467 Scalar::Null(NullKind::NaN),
23468 Scalar::Float64(4.0),
23469 Scalar::Null(NullKind::NaN),
23470 ])
23471 .expect("col");
23472 let r = col.interpolate_linear().expect("interpolate");
23473 assert!(r.values()[0].is_missing());
23474 assert_eq!(r.values()[1], Scalar::Float64(2.0));
23475 assert!(
23476 matches!(&r.values()[2], Scalar::Float64(v) if (*v - 3.0).abs() < 1e-9),
23477 "expected Float64, got {:?}",
23478 r.values()[2]
23479 );
23480 assert_eq!(r.values()[3], Scalar::Float64(4.0));
23481 assert_eq!(r.values()[4], Scalar::Float64(4.0));
23483 }
23484
23485 #[test]
23486 fn interpolate_trailing_run_forward_fills_without_extrapolating() {
23487 let col = Column::from_values(vec![
23489 Scalar::Float64(2.0),
23490 Scalar::Float64(4.0),
23491 Scalar::Null(NullKind::NaN),
23492 Scalar::Null(NullKind::NaN),
23493 ])
23494 .expect("col");
23495 let r = col.interpolate_linear().expect("interpolate");
23496 assert_eq!(
23497 r.values(),
23498 &[
23499 Scalar::Float64(2.0),
23500 Scalar::Float64(4.0),
23501 Scalar::Float64(4.0),
23502 Scalar::Float64(4.0),
23503 ]
23504 );
23505 }
23506
23507 #[test]
23508 fn interpolate_empty_is_empty_float64() {
23509 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23510 let r = col.interpolate_linear().expect("interpolate");
23511 assert!(r.is_empty());
23512 assert_eq!(r.dtype(), DType::Float64);
23513 }
23514
23515 #[test]
23516 fn interpolate_alias_matches_default_linear_interpolation() {
23517 let col = Column::from_values(vec![
23518 Scalar::Float64(1.0),
23519 Scalar::Null(NullKind::NaN),
23520 Scalar::Float64(3.0),
23521 ])
23522 .expect("col");
23523
23524 assert_eq!(
23525 col.interpolate().expect("interpolate"),
23526 col.interpolate_linear().expect("interpolate_linear")
23527 );
23528 }
23529
23530 #[test]
23531 fn drop_duplicates_keeps_first_occurrence() {
23532 let col = Column::from_values(vec![
23533 Scalar::Int64(1),
23534 Scalar::Int64(2),
23535 Scalar::Int64(1),
23536 Scalar::Int64(3),
23537 Scalar::Int64(2),
23538 ])
23539 .expect("col");
23540 let d = col.drop_duplicates().expect("drop_duplicates");
23541 assert_eq!(
23542 d.values(),
23543 &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
23544 );
23545 }
23546
23547 #[test]
23548 fn drop_duplicates_treats_nulls_as_one_bucket() {
23549 let col = Column::from_values(vec![
23550 Scalar::Null(NullKind::NaN),
23551 Scalar::Int64(1),
23552 Scalar::Null(NullKind::NaN),
23553 ])
23554 .expect("col");
23555 let d = col.drop_duplicates().expect("drop_duplicates");
23556 assert_eq!(d.len(), 2);
23558 assert!(d.values()[0].is_missing());
23559 assert_eq!(d.values()[1], Scalar::Int64(1));
23560 }
23561
23562 #[test]
23563 fn drop_duplicates_keep_variants_match_pandas() {
23564 let col = Column::from_values(vec![
23565 Scalar::Int64(1),
23566 Scalar::Int64(2),
23567 Scalar::Int64(1),
23568 Scalar::Int64(1),
23569 Scalar::Int64(3),
23570 Scalar::Int64(2),
23571 Scalar::Null(NullKind::NaN),
23572 Scalar::Null(NullKind::NaN),
23573 ])
23574 .expect("col");
23575
23576 let last = col.drop_duplicates_keep("last").expect("drop last");
23577 assert_eq!(last.len(), 4);
23578 assert_eq!(last.values()[0], Scalar::Int64(1));
23579 assert_eq!(last.values()[1], Scalar::Int64(3));
23580 assert_eq!(last.values()[2], Scalar::Int64(2));
23581 assert!(last.values()[3].is_missing());
23582
23583 let none = col.drop_duplicates_keep("false").expect("drop none");
23584 assert_eq!(none.values(), &[Scalar::Int64(3)]);
23585 }
23586
23587 #[test]
23588 fn compare_returns_only_differences() {
23589 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
23590 .expect("a");
23591 let b =
23592 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(20), Scalar::Int64(3)])
23593 .expect("b");
23594 let (left, right) = a.compare(&b).expect("compare");
23595 assert_eq!(left.values(), &[Scalar::Int64(2)]);
23596 assert_eq!(right.values(), &[Scalar::Int64(20)]);
23597 }
23598
23599 #[test]
23600 fn compare_treats_matching_nulls_as_equal() {
23601 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
23602 .expect("a");
23603 let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
23604 .expect("b");
23605 let (left, right) = a.compare(&b).expect("compare");
23606 assert!(left.is_empty());
23607 assert!(right.is_empty());
23608 }
23609
23610 #[test]
23611 fn compare_length_mismatch_errors() {
23612 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("a");
23613 let b = Column::from_values(vec![Scalar::Int64(1)]).expect("b");
23614 let err = a.compare(&b).unwrap_err();
23615 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
23616 }
23617
23618 #[test]
23619 fn map_applies_unary_function() {
23620 let col =
23621 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
23622 .expect("col");
23623 let doubled = col
23624 .map(|v| match v {
23625 Scalar::Int64(i) => Scalar::Int64(i * 2),
23626 other => other.clone(),
23627 })
23628 .expect("map");
23629 assert_eq!(doubled.values()[0], Scalar::Int64(2));
23630 assert_eq!(doubled.values()[1], Scalar::Int64(4));
23631 assert_eq!(doubled.values()[2], Scalar::Int64(6));
23632 }
23633
23634 #[test]
23635 fn map_can_change_dtype() {
23636 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
23637 let as_str = col
23638 .map(|v| match v {
23639 Scalar::Int64(i) => Scalar::Utf8(i.to_string()),
23640 other => other.clone(),
23641 })
23642 .expect("map");
23643 assert_eq!(as_str.dtype(), DType::Utf8);
23644 assert_eq!(as_str.values()[0], Scalar::Utf8("1".into()));
23645 }
23646
23647 #[test]
23648 fn argmin_argmax_skip_missing() {
23649 let col = Column::from_values(vec![
23650 Scalar::Int64(3),
23651 Scalar::Null(NullKind::NaN),
23652 Scalar::Int64(1),
23653 Scalar::Int64(5),
23654 Scalar::Int64(2),
23655 ])
23656 .expect("col");
23657 assert_eq!(col.argmin(), Some(2));
23658 assert_eq!(col.argmax(), Some(3));
23659 assert_eq!(col.idxmin(), Some(2));
23660 assert_eq!(col.idxmax(), Some(3));
23661 }
23662
23663 #[test]
23664 fn argmin_argmax_all_missing_returns_none() {
23665 let col = Column::from_values(vec![
23666 Scalar::Null(NullKind::NaN),
23667 Scalar::Null(NullKind::Null),
23668 ])
23669 .expect("col");
23670 assert!(col.argmin().is_none());
23671 assert!(col.argmax().is_none());
23672 assert!(col.idxmin().is_none());
23673 assert!(col.idxmax().is_none());
23674 }
23675
23676 #[test]
23677 fn is_monotonic_increasing_detects_ascending() {
23678 let col = Column::from_values(vec![
23679 Scalar::Int64(1),
23680 Scalar::Int64(2),
23681 Scalar::Int64(2),
23682 Scalar::Int64(5),
23683 ])
23684 .expect("col");
23685 assert!(col.is_monotonic_increasing());
23686 assert!(!col.is_monotonic_decreasing());
23687 }
23688
23689 #[test]
23690 fn is_monotonic_decreasing_detects_descending() {
23691 let col =
23692 Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(3), Scalar::Int64(1)])
23693 .expect("col");
23694 assert!(col.is_monotonic_decreasing());
23695 assert!(!col.is_monotonic_increasing());
23696 }
23697
23698 #[test]
23699 fn is_monotonic_skips_missing_values() {
23700 let col = Column::from_values(vec![
23701 Scalar::Int64(1),
23702 Scalar::Null(NullKind::NaN),
23703 Scalar::Int64(3),
23704 Scalar::Int64(5),
23705 ])
23706 .expect("col");
23707 assert!(col.is_monotonic_increasing());
23708 }
23709
23710 #[test]
23711 fn is_monotonic_empty_is_true() {
23712 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23713 assert!(col.is_monotonic_increasing());
23714 assert!(col.is_monotonic_decreasing());
23715 }
23716
23717 #[test]
23718 fn combine_first_fills_missing_from_other() {
23719 let a = Column::from_values(vec![
23720 Scalar::Int64(1),
23721 Scalar::Null(NullKind::NaN),
23722 Scalar::Int64(3),
23723 ])
23724 .expect("a");
23725 let b = Column::from_values(vec![
23726 Scalar::Int64(10),
23727 Scalar::Int64(20),
23728 Scalar::Int64(30),
23729 ])
23730 .expect("b");
23731 let c = a.combine_first(&b).expect("combine_first");
23732 assert_eq!(c.values()[0], Scalar::Int64(1));
23733 assert_eq!(c.values()[1], Scalar::Int64(20));
23734 assert_eq!(c.values()[2], Scalar::Int64(3));
23735 }
23736
23737 #[test]
23738 fn combine_first_length_mismatch_errors() {
23739 let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
23740 let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
23741 let err = a.combine_first(&b).unwrap_err();
23742 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
23743 }
23744
23745 #[test]
23746 fn clip_lower_only() {
23747 let col = Column::from_values(vec![
23748 Scalar::Float64(-2.0),
23749 Scalar::Float64(0.0),
23750 Scalar::Float64(5.0),
23751 ])
23752 .expect("col");
23753 let c = col.clip_lower(0.0).expect("clip_lower");
23754 assert_eq!(c.values()[0], Scalar::Float64(0.0));
23755 assert_eq!(c.values()[1], Scalar::Float64(0.0));
23756 assert_eq!(c.values()[2], Scalar::Float64(5.0));
23757 }
23758
23759 #[test]
23760 fn clip_upper_only() {
23761 let col = Column::from_values(vec![
23762 Scalar::Float64(-2.0),
23763 Scalar::Float64(0.0),
23764 Scalar::Float64(5.0),
23765 ])
23766 .expect("col");
23767 let c = col.clip_upper(1.0).expect("clip_upper");
23768 assert_eq!(c.values()[0], Scalar::Float64(-2.0));
23769 assert_eq!(c.values()[1], Scalar::Float64(0.0));
23770 assert_eq!(c.values()[2], Scalar::Float64(1.0));
23771 }
23772
23773 #[test]
23774 fn describe_returns_pandas_order() {
23775 let col = Column::from_values(vec![
23776 Scalar::Float64(1.0),
23777 Scalar::Float64(2.0),
23778 Scalar::Float64(3.0),
23779 Scalar::Float64(4.0),
23780 Scalar::Float64(5.0),
23781 ])
23782 .expect("col");
23783 let stats = col.describe().expect("describe");
23784 let names: Vec<&str> = stats.iter().map(|(k, _)| *k).collect();
23785 assert_eq!(
23786 names,
23787 vec!["count", "mean", "std", "min", "25%", "50%", "75%", "max"]
23788 );
23789 assert_eq!(stats[0].1, Scalar::Int64(5));
23790 assert!(
23791 matches!(&stats[1].1, Scalar::Float64(v) if (*v - 3.0).abs() < 1e-9),
23792 "expected Float64, got {:?}",
23793 stats[1].1
23794 );
23795 assert_eq!(stats[3].1, Scalar::Float64(1.0));
23796 assert_eq!(stats[7].1, Scalar::Float64(5.0));
23797 }
23798
23799 #[test]
23800 fn describe_rejects_utf8_column() {
23801 let col = Column::from_values(vec![Scalar::Utf8("a".into())]).expect("col");
23802 assert!(col.describe().is_err());
23803 }
23804
23805 #[test]
23806 fn combine_uses_fill_for_missing() {
23807 let a = Column::from_values(vec![
23808 Scalar::Int64(1),
23809 Scalar::Null(NullKind::NaN),
23810 Scalar::Int64(3),
23811 ])
23812 .expect("a");
23813 let b = Column::from_values(vec![
23814 Scalar::Int64(10),
23815 Scalar::Int64(20),
23816 Scalar::Null(NullKind::NaN),
23817 ])
23818 .expect("b");
23819 let out = a
23820 .combine(
23821 &b,
23822 |l, r| {
23823 if let (Ok(lf), Ok(rf)) = (l.to_f64(), r.to_f64()) {
23824 Scalar::Float64(lf + rf)
23825 } else {
23826 Scalar::Null(NullKind::NaN)
23827 }
23828 },
23829 Some(Scalar::Int64(0)),
23830 )
23831 .expect("combine");
23832 assert_eq!(out.values()[0], Scalar::Float64(11.0));
23833 assert_eq!(out.values()[1], Scalar::Float64(20.0));
23834 assert_eq!(out.values()[2], Scalar::Float64(3.0));
23835 }
23836
23837 #[test]
23838 fn combine_length_mismatch_errors() {
23839 let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
23840 let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
23841 let err = a
23842 .combine(&b, |l, _| l.clone(), Some(Scalar::Int64(0)))
23843 .unwrap_err();
23844 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
23845 }
23846
23847 #[test]
23848 fn combine_fill_none_propagates_nulls_without_invoking_func() {
23849 let a = Column::from_values(vec![
23850 Scalar::Float64(1.0),
23851 Scalar::Null(NullKind::NaN),
23852 Scalar::Float64(3.0),
23853 ])
23854 .expect("a");
23855 let b = Column::from_values(vec![
23856 Scalar::Float64(10.0),
23857 Scalar::Float64(20.0),
23858 Scalar::Null(NullKind::NaN),
23859 ])
23860 .expect("b");
23861 let mut calls = 0usize;
23862 let out = a
23863 .combine(
23864 &b,
23865 |l, r| {
23866 calls += 1;
23867 Scalar::Float64(l.to_f64().unwrap() + r.to_f64().unwrap())
23868 },
23869 None,
23870 )
23871 .expect("combine");
23872 assert_eq!(calls, 1);
23874 assert_eq!(out.values()[0], Scalar::Float64(11.0));
23875 assert!(out.values()[1].is_missing());
23876 assert!(out.values()[2].is_missing());
23877 }
23878
23879 #[test]
23880 fn combine_fill_none_all_present_matches_elementwise_apply() {
23881 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("a");
23882 let b = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("b");
23883 let out = a
23884 .combine(
23885 &b,
23886 |l, r| Scalar::Int64(l.to_f64().unwrap() as i64 + r.to_f64().unwrap() as i64),
23887 None,
23888 )
23889 .expect("combine");
23890 assert_eq!(out.values()[0], Scalar::Int64(11));
23891 assert_eq!(out.values()[1], Scalar::Int64(22));
23892 }
23893
23894 #[test]
23895 fn apply_float_applies_numeric_fn() {
23896 let col = Column::from_values(vec![
23897 Scalar::Float64(1.0),
23898 Scalar::Null(NullKind::NaN),
23899 Scalar::Float64(4.0),
23900 ])
23901 .expect("col");
23902 let out = col.apply_float(|x| x.sqrt()).expect("apply_float");
23903 assert_eq!(out.values()[0], Scalar::Float64(1.0));
23904 assert!(out.values()[1].is_missing());
23905 assert_eq!(out.values()[2], Scalar::Float64(2.0));
23906 assert_eq!(out.dtype(), DType::Float64);
23907 }
23908
23909 #[test]
23910 fn apply_float_rejects_non_numeric() {
23911 let col = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("col");
23912 assert!(col.apply_float(|x| x + 1.0).is_err());
23913 }
23914
23915 #[test]
23916 fn hist_counts_equal_width_bins() {
23917 let col = Column::from_values(vec![
23918 Scalar::Float64(0.0),
23919 Scalar::Float64(1.0),
23920 Scalar::Float64(2.0),
23921 Scalar::Float64(3.0),
23922 Scalar::Float64(9.0),
23923 ])
23924 .expect("col");
23925 let counts = col.hist_counts(3);
23926 assert_eq!(counts.len(), 3);
23928 assert_eq!(counts[0], 3); assert_eq!(counts[1], 1); assert_eq!(counts[2], 1); }
23932
23933 #[test]
23934 fn hist_counts_zero_bins_is_empty() {
23935 let col = Column::from_values(vec![Scalar::Float64(1.0)]).expect("col");
23936 assert!(col.hist_counts(0).is_empty());
23937 }
23938
23939 #[test]
23940 fn hist_counts_constant_column_puts_all_in_first_bin() {
23941 let col = Column::from_values(vec![
23942 Scalar::Float64(5.0),
23943 Scalar::Float64(5.0),
23944 Scalar::Float64(5.0),
23945 ])
23946 .expect("col");
23947 let counts = col.hist_counts(3);
23948 assert_eq!(counts[0], 3);
23949 assert_eq!(counts[1], 0);
23950 assert_eq!(counts[2], 0);
23951 }
23952
23953 #[test]
23954 fn nunique_drops_nulls() {
23955 let col = Column::from_values(vec![
23956 Scalar::Int64(1),
23957 Scalar::Int64(2),
23958 Scalar::Int64(1),
23959 Scalar::Null(NullKind::NaN),
23960 ])
23961 .expect("col");
23962 assert_eq!(col.nunique(), Scalar::Int64(2));
23963 }
23964
23965 #[test]
23966 fn nunique_with_dropna_false_counts_missing_once() {
23967 let col = Column::from_values(vec![
23968 Scalar::Int64(1),
23969 Scalar::Int64(2),
23970 Scalar::Int64(1),
23971 Scalar::Null(NullKind::NaN),
23972 Scalar::Null(NullKind::Null),
23973 ])
23974 .expect("col");
23975 assert_eq!(col.nunique_with_dropna(false), Scalar::Int64(3));
23976 }
23977
23978 #[test]
23979 fn nunique_with_dropna_false_all_missing_is_one() {
23980 let col = Column::from_values(vec![
23981 Scalar::Null(NullKind::NaN),
23982 Scalar::Null(NullKind::Null),
23983 Scalar::Null(NullKind::NaN),
23984 ])
23985 .expect("col");
23986 assert_eq!(col.nunique(), Scalar::Int64(0));
23987 assert_eq!(col.nunique_with_dropna(false), Scalar::Int64(1));
23988 }
23989
23990 #[test]
23991 fn any_all_reductions() {
23992 let col = Column::from_values(vec![Scalar::Int64(0), Scalar::Int64(0)]).expect("col");
23993 assert_eq!(col.any(), Scalar::Bool(false));
23994 assert_eq!(col.all(), Scalar::Bool(false));
23995
23996 let mixed = Column::from_values(vec![Scalar::Int64(0), Scalar::Int64(1)]).expect("col");
23997 assert_eq!(mixed.any(), Scalar::Bool(true));
23998 assert_eq!(mixed.all(), Scalar::Bool(false));
23999
24000 let all_true =
24001 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
24002 assert_eq!(all_true.all(), Scalar::Bool(true));
24003 }
24004
24005 #[test]
24006 fn is_unique_true_when_no_repeats() {
24007 let col =
24008 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
24009 .expect("col");
24010 assert!(col.is_unique());
24011 assert!(!col.has_duplicates());
24012 }
24013
24014 #[test]
24015 fn has_duplicates_true_when_repeats_present() {
24016 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(1)]).expect("col");
24017 assert!(col.has_duplicates());
24018 assert!(!col.is_unique());
24019 }
24020
24021 #[test]
24022 fn is_unique_ignores_nulls() {
24023 let col = Column::from_values(vec![
24024 Scalar::Int64(1),
24025 Scalar::Null(NullKind::NaN),
24026 Scalar::Null(NullKind::NaN),
24027 ])
24028 .expect("col");
24029 assert!(col.is_unique());
24030 }
24031
24032 #[test]
24033 fn pct_change_periods_one() {
24034 let col = Column::from_values(vec![
24035 Scalar::Float64(10.0),
24036 Scalar::Float64(12.0),
24037 Scalar::Float64(9.0),
24038 ])
24039 .expect("col");
24040 let r = col.pct_change(1).expect("pct_change");
24041 assert!(r.values()[0].is_missing());
24042 assert!(
24043 matches!(&r.values()[1], Scalar::Float64(v) if (*v - 0.2).abs() < 1e-9),
24044 "expected Float64, got {:?}",
24045 r.values()[1]
24046 );
24047 assert!(
24048 matches!(&r.values()[2], Scalar::Float64(v) if (*v + 0.25).abs() < 1e-9),
24049 "expected Float64, got {:?}",
24050 r.values()[2]
24051 );
24052 }
24053
24054 #[test]
24055 fn pct_change_zero_prev_yields_null() {
24056 let col =
24057 Column::from_values(vec![Scalar::Float64(0.0), Scalar::Float64(5.0)]).expect("col");
24058 let r = col.pct_change(1).expect("pct_change");
24059 assert!(r.values()[1].is_missing());
24060 }
24061
24062 #[test]
24063 fn pct_change_timedelta64_matches_pandas_mcu90() {
24064 let one_hour = 3_600 * 1_000_000_000_i64;
24068 let col = Column::from_values(vec![
24069 Scalar::Timedelta64(one_hour),
24070 Scalar::Timedelta64(2 * one_hour),
24071 Scalar::Timedelta64(4 * one_hour),
24072 ])
24073 .expect("col");
24074 let r = col.pct_change(1).expect("pct_change");
24075 assert!(r.values()[0].is_missing());
24076 assert!(
24077 matches!(&r.values()[1], Scalar::Float64(v) if (*v - 1.0).abs() < 1e-10),
24078 "expected Float64(1.0), got {:?}",
24079 r.values()[1]
24080 );
24081 assert!(
24082 matches!(&r.values()[2], Scalar::Float64(v) if (*v - 1.0).abs() < 1e-10),
24083 "expected Float64(1.0), got {:?}",
24084 r.values()[2]
24085 );
24086 }
24087
24088 #[test]
24089 fn pct_change_timedelta64_nat_propagates_mcu90() {
24090 use fp_types::Timedelta;
24091 let one_hour = 3_600 * 1_000_000_000_i64;
24092 let col = Column::from_values(vec![
24093 Scalar::Timedelta64(one_hour),
24094 Scalar::Timedelta64(Timedelta::NAT),
24095 Scalar::Timedelta64(2 * one_hour),
24096 ])
24097 .expect("col");
24098 let r = col.pct_change(1).expect("pct_change");
24099 assert!(r.values()[0].is_missing());
24100 assert!(r.values()[1].is_missing()); assert!(r.values()[2].is_missing()); }
24103
24104 #[test]
24105 fn pct_change_with_fill_ffill_uses_filled_previous_value() {
24106 let col = Column::from_values(vec![
24107 Scalar::Float64(10.0),
24108 Scalar::Null(NullKind::NaN),
24109 Scalar::Float64(12.0),
24110 ])
24111 .expect("col");
24112 let r = col
24113 .pct_change_with_fill(1, Some("ffill"), None)
24114 .expect("pct_change_with_fill");
24115 assert!(r.values()[0].is_missing());
24116 assert!(
24117 matches!(&r.values()[1], Scalar::Float64(v) if v.abs() < 1e-9),
24118 "expected Float64, got {:?}",
24119 r.values()[1]
24120 );
24121 assert!(
24122 matches!(&r.values()[2], Scalar::Float64(v) if (*v - 0.2).abs() < 1e-9),
24123 "expected Float64, got {:?}",
24124 r.values()[2]
24125 );
24126 }
24127
24128 #[test]
24129 fn pct_change_with_fill_limit_caps_forward_fill_runs() {
24130 let col = Column::from_values(vec![
24131 Scalar::Float64(10.0),
24132 Scalar::Null(NullKind::NaN),
24133 Scalar::Null(NullKind::NaN),
24134 Scalar::Float64(20.0),
24135 ])
24136 .expect("col");
24137 let r = col
24138 .pct_change_with_fill(1, Some("ffill"), Some(1))
24139 .expect("pct_change_with_fill");
24140 assert!(r.values()[0].is_missing());
24141 assert!(
24142 matches!(&r.values()[1], Scalar::Float64(v) if v.abs() < 1e-9),
24143 "expected Float64, got {:?}",
24144 r.values()[1]
24145 );
24146 assert!(r.values()[2].is_missing());
24147 assert!(r.values()[3].is_missing());
24148 }
24149
24150 #[test]
24151 fn pct_change_with_fill_bfill_aliases_backward_fill() {
24152 let col = Column::from_values(vec![
24153 Scalar::Float64(10.0),
24154 Scalar::Null(NullKind::NaN),
24155 Scalar::Float64(20.0),
24156 ])
24157 .expect("col");
24158 let r = col
24159 .pct_change_with_fill(1, Some("backfill"), None)
24160 .expect("pct_change_with_fill");
24161 assert!(r.values()[0].is_missing());
24162 assert!(
24163 matches!(&r.values()[1], Scalar::Float64(v) if (*v - 1.0).abs() < 1e-9),
24164 "expected Float64, got {:?}",
24165 r.values()[1]
24166 );
24167 assert!(
24168 matches!(&r.values()[2], Scalar::Float64(v) if v.abs() < 1e-9),
24169 "expected Float64, got {:?}",
24170 r.values()[2]
24171 );
24172 }
24173
24174 #[test]
24175 fn pct_change_with_fill_rejects_invalid_method() {
24176 let col =
24177 Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("col");
24178 let err = col
24179 .pct_change_with_fill(1, Some("nearest"), None)
24180 .expect_err("invalid fill_method should error");
24181 assert!(matches!(
24182 err,
24183 crate::ColumnError::Type(fp_types::TypeError::NonNumericValue { .. })
24184 ));
24185 }
24186
24187 #[test]
24188 fn ffill_fills_trailing_missing_runs() {
24189 let col = Column::from_values(vec![
24190 Scalar::Null(NullKind::NaN),
24191 Scalar::Int64(1),
24192 Scalar::Null(NullKind::NaN),
24193 Scalar::Null(NullKind::NaN),
24194 Scalar::Int64(5),
24195 ])
24196 .expect("col");
24197 let r = col.ffill(None).expect("ffill");
24198 assert!(r.values()[0].is_missing());
24199 assert_eq!(r.values()[1], Scalar::Int64(1));
24200 assert_eq!(r.values()[2], Scalar::Int64(1));
24201 assert_eq!(r.values()[3], Scalar::Int64(1));
24202 assert_eq!(r.values()[4], Scalar::Int64(5));
24203 }
24204
24205 #[test]
24206 fn ffill_respects_limit_per_run() {
24207 let col = Column::from_values(vec![
24208 Scalar::Int64(1),
24209 Scalar::Null(NullKind::NaN),
24210 Scalar::Null(NullKind::NaN),
24211 Scalar::Null(NullKind::NaN),
24212 Scalar::Int64(9),
24213 ])
24214 .expect("col");
24215 let r = col.ffill(Some(2)).expect("ffill");
24216 assert_eq!(r.values()[0], Scalar::Int64(1));
24217 assert_eq!(r.values()[1], Scalar::Int64(1));
24218 assert_eq!(r.values()[2], Scalar::Int64(1));
24219 assert!(r.values()[3].is_missing());
24220 assert_eq!(r.values()[4], Scalar::Int64(9));
24221 assert_eq!(col.pad(Some(2)), col.ffill(Some(2)));
24222 }
24223
24224 #[test]
24225 fn bfill_fills_leading_missing_runs() {
24226 let col = Column::from_values(vec![
24227 Scalar::Null(NullKind::NaN),
24228 Scalar::Null(NullKind::NaN),
24229 Scalar::Int64(3),
24230 Scalar::Null(NullKind::NaN),
24231 ])
24232 .expect("col");
24233 let r = col.bfill(None).expect("bfill");
24234 assert_eq!(r.values()[0], Scalar::Int64(3));
24235 assert_eq!(r.values()[1], Scalar::Int64(3));
24236 assert_eq!(r.values()[2], Scalar::Int64(3));
24237 assert!(r.values()[3].is_missing());
24239 }
24240
24241 #[test]
24242 fn bfill_respects_limit_per_run() {
24243 let col = Column::from_values(vec![
24244 Scalar::Null(NullKind::NaN),
24245 Scalar::Null(NullKind::NaN),
24246 Scalar::Null(NullKind::NaN),
24247 Scalar::Int64(7),
24248 ])
24249 .expect("col");
24250 let r = col.bfill(Some(1)).expect("bfill");
24251 assert!(r.values()[0].is_missing());
24252 assert!(r.values()[1].is_missing());
24253 assert_eq!(r.values()[2], Scalar::Int64(7));
24254 assert_eq!(r.values()[3], Scalar::Int64(7));
24255 assert_eq!(col.backfill(Some(1)), col.bfill(Some(1)));
24256 }
24257
24258 #[test]
24259 fn ffill_empty_is_empty_same_dtype() {
24260 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
24261 let r = col.ffill(None).expect("ffill");
24262 assert!(r.is_empty());
24263 assert_eq!(r.dtype(), DType::Null);
24264 }
24265
24266 #[test]
24267 fn pandas_metadata_and_materialization_aliases_match_core_methods()
24268 -> Result<(), crate::ColumnError> {
24269 let col = Column::from_values(vec![
24270 Scalar::Int64(1),
24271 Scalar::Null(NullKind::NaN),
24272 Scalar::Int64(2),
24273 ])?;
24274
24275 assert_eq!(col.size(), col.len());
24276 assert_eq!(col.shape(), (col.len(),));
24277 assert_eq!(col.ndim(), 1);
24278 assert_eq!(col.empty(), col.is_empty());
24279 assert_eq!(col.to_list(), col.to_vec());
24280 assert_eq!(col.tolist(), col.to_vec());
24281 assert_eq!(col.to_numpy(), col.to_vec());
24282 assert_eq!(col.ravel(), col.to_numpy());
24283 assert_eq!(col.array(), col.to_vec());
24284 Ok(())
24285 }
24286
24287 #[test]
24288 fn isnull_notnull_flag_missing_positions() {
24289 let col = Column::from_values(vec![
24290 Scalar::Int64(1),
24291 Scalar::Null(NullKind::NaN),
24292 Scalar::Int64(2),
24293 ])
24294 .expect("col");
24295 let is_null = col.isnull().expect("isnull");
24296 let not_null = col.notnull().expect("notnull");
24297 assert_eq!(is_null.dtype(), DType::Bool);
24298 assert_eq!(
24299 is_null.values(),
24300 &[Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(false),]
24301 );
24302 assert_eq!(col.isna(), col.isnull());
24303 assert_eq!(
24304 not_null.values(),
24305 &[Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true),]
24306 );
24307 assert_eq!(col.notna(), col.notnull());
24308 }
24309
24310 #[test]
24311 fn null_predicates_match_scalar_oracle_zvykt() {
24312 fn next(seed: &mut u64) -> u64 {
24315 *seed = seed
24316 .wrapping_mul(6364136223846793005)
24317 .wrapping_add(1442695040888963407);
24318 *seed
24319 }
24320
24321 let mut seed = 0x5a17_1e55_0b5e_7a11_u64;
24322 for case in 0..260 {
24323 let len = (next(&mut seed) % 73 + 1) as usize;
24324 let mut values = Vec::with_capacity(len);
24325 for pos in 0..len {
24326 let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
24327 let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
24328 values.push(match next(&mut seed) % 10 {
24329 0 => Scalar::Null(NullKind::Null),
24330 1 => Scalar::Null(NullKind::NaN),
24331 2 => Scalar::Float64(f64::NAN),
24332 3 => Scalar::Float64(f64::INFINITY),
24333 4 => Scalar::Float64(f64::NEG_INFINITY),
24334 5 => Scalar::Float64(raw as f64 / 41.0 + frac),
24335 6 => Scalar::Int64(raw),
24336 7 => Scalar::Bool(raw & 1 == 0),
24337 8 => Scalar::Utf8(format!("v{case}_{pos}")),
24338 _ => Scalar::Timedelta64(raw),
24339 });
24340 }
24341
24342 let input = Column::from_values(values.clone()).expect("column");
24343 let is_null = input.isnull().expect("isnull");
24344 let is_na = input.isna().expect("isna");
24345 let not_null = input.notnull().expect("notnull");
24346 let not_na = input.notna().expect("notna");
24347
24348 assert_eq!(is_null.dtype(), DType::Bool);
24349 assert_eq!(is_na.values(), is_null.values());
24350 assert_eq!(not_na.values(), not_null.values());
24351 assert_eq!(is_null.values().len(), values.len());
24352 assert_eq!(not_null.values().len(), values.len());
24353
24354 for (pos, value) in values.iter().enumerate() {
24355 let missing = value.is_missing();
24356 assert_eq!(
24357 is_null.values()[pos],
24358 Scalar::Bool(missing),
24359 "case={case} pos={pos}: isnull mismatch for {value:?}"
24360 );
24361 assert_eq!(
24362 not_null.values()[pos],
24363 Scalar::Bool(!missing),
24364 "case={case} pos={pos}: notnull mismatch for {value:?}"
24365 );
24366 }
24367 }
24368 }
24369
24370 #[test]
24371 fn missing_reducers_match_scalar_oracle_8n9cp() {
24372 fn next(seed: &mut u64) -> u64 {
24375 *seed = seed
24376 .wrapping_mul(2862933555777941757)
24377 .wrapping_add(3037000493);
24378 *seed
24379 }
24380
24381 let empty = Column::new(DType::Float64, Vec::new()).expect("empty");
24382 assert!(!empty.has_any_missing());
24383 assert!(!empty.hasnans());
24384 assert!(empty.all_missing());
24385
24386 let mut seed = 0x8a11_a115_1d5d_0a7a_u64;
24387 for case in 0..260 {
24388 let len = (next(&mut seed) % 79 + 1) as usize;
24389 let mut values = Vec::with_capacity(len);
24390 for pos in 0..len {
24391 let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
24392 let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
24393 values.push(match next(&mut seed) % 10 {
24394 0 => Scalar::Null(NullKind::Null),
24395 1 => Scalar::Null(NullKind::NaN),
24396 2 => Scalar::Float64(f64::NAN),
24397 3 => Scalar::Float64(f64::INFINITY),
24398 4 => Scalar::Float64(f64::NEG_INFINITY),
24399 5 => Scalar::Float64(raw as f64 / 43.0 + frac),
24400 6 => Scalar::Int64(raw),
24401 7 => Scalar::Bool(raw & 1 == 0),
24402 8 => Scalar::Utf8(format!("m{case}_{pos}")),
24403 _ => Scalar::Timedelta64(raw),
24404 });
24405 }
24406
24407 let input = Column::from_values(values.clone()).expect("column");
24408 let any_missing = values.iter().any(Scalar::is_missing);
24409 let all_missing = values.iter().all(Scalar::is_missing);
24410
24411 assert_eq!(
24412 input.has_any_missing(),
24413 any_missing,
24414 "case={case}: has_any_missing mismatch for {values:?}"
24415 );
24416 assert_eq!(
24417 input.hasnans(),
24418 any_missing,
24419 "case={case}: hasnans mismatch for {values:?}"
24420 );
24421 assert_eq!(
24422 input.all_missing(),
24423 all_missing,
24424 "case={case}: all_missing mismatch for {values:?}"
24425 );
24426 }
24427 }
24428
24429 #[test]
24430 fn isnull_notnull_use_nullable_int64_validity_without_scalar_materialization_nakgb() {
24431 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2), (5, 1)]), 6);
24432 let col = Column::from_i64_values_with_validity((0_i64..6).collect(), validity);
24433
24434 let is_null = col.isnull().expect("isnull");
24435 let not_null = col.notnull().expect("notnull");
24436
24437 assert_eq!(
24438 is_null.values(),
24439 &[
24440 Scalar::Bool(false),
24441 Scalar::Bool(true),
24442 Scalar::Bool(true),
24443 Scalar::Bool(false),
24444 Scalar::Bool(false),
24445 Scalar::Bool(true),
24446 ]
24447 );
24448 assert_eq!(
24449 not_null.values(),
24450 &[
24451 Scalar::Bool(true),
24452 Scalar::Bool(false),
24453 Scalar::Bool(false),
24454 Scalar::Bool(true),
24455 Scalar::Bool(true),
24456 Scalar::Bool(false),
24457 ]
24458 );
24459 assert!(matches!(
24460 &col.values,
24461 ScalarValues::LazyNullableInt64 { .. }
24462 ));
24463 if let ScalarValues::LazyNullableInt64 { values, .. } = &col.values {
24464 assert!(values.get().is_none());
24465 }
24466 }
24467
24468 #[test]
24469 fn isnull_notnull_float64_raw_path_checks_nan_without_scalar_materialization_nakgb() {
24470 let col = Column {
24471 dtype: DType::Float64,
24472 values: ScalarValues::lazy_all_valid_float64(vec![1.0, f64::NAN, f64::INFINITY]),
24473 validity: ValidityMask::all_valid(3),
24474 data: None,
24475 };
24476
24477 let is_null = col.isnull().expect("isnull");
24478 let not_null = col.notnull().expect("notnull");
24479
24480 assert_eq!(
24481 is_null.values(),
24482 &[Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(false),]
24483 );
24484 assert_eq!(
24485 not_null.values(),
24486 &[Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true),]
24487 );
24488 assert!(matches!(
24489 &col.values,
24490 ScalarValues::LazyAllValidFloat64 { .. }
24491 ));
24492 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &col.values {
24493 assert!(values.get().is_none());
24494 }
24495 }
24496
24497 #[test]
24498 fn float64_predicate_masks_use_raw_validity_without_scalar_materialization_ti9f1() {
24499 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 1)]), 4);
24500 let col = Column::from_f64_values_with_validity(
24501 vec![1.0, 0.0, f64::NAN, f64::INFINITY],
24502 validity,
24503 );
24504
24505 assert_eq!(
24506 col.isfinite().expect("isfinite").values(),
24507 &[
24508 Scalar::Bool(true),
24509 Scalar::Bool(false),
24510 Scalar::Bool(false),
24511 Scalar::Bool(false),
24512 ]
24513 );
24514 assert_eq!(
24515 col.isinf().expect("isinf").values(),
24516 &[
24517 Scalar::Bool(false),
24518 Scalar::Bool(false),
24519 Scalar::Bool(false),
24520 Scalar::Bool(true),
24521 ]
24522 );
24523 assert_eq!(
24524 col.isnan().expect("isnan").values(),
24525 &[
24526 Scalar::Bool(false),
24527 Scalar::Bool(true),
24528 Scalar::Bool(true),
24529 Scalar::Bool(false),
24530 ]
24531 );
24532 assert!(matches!(
24533 &col.values,
24534 ScalarValues::LazyNullableFloat64 { .. }
24535 ));
24536 if let ScalarValues::LazyNullableFloat64 { values, .. } = &col.values {
24537 assert!(values.get().is_none());
24538 }
24539 }
24540
24541 #[test]
24542 fn finite_predicates_match_scalar_oracle_dknku() {
24543 fn next(seed: &mut u64) -> u64 {
24546 *seed = seed
24547 .wrapping_mul(1442695040888963407)
24548 .wrapping_add(6364136223846793005);
24549 *seed
24550 }
24551
24552 fn oracle(value: &Scalar) -> (bool, bool, bool) {
24553 let isfinite = match value {
24554 Scalar::Float64(v) => v.is_finite(),
24555 Scalar::Int64(_) => true,
24556 _ if value.is_missing() => false,
24557 _ => true,
24558 };
24559 let isinf = matches!(value, Scalar::Float64(v) if v.is_infinite());
24560 let isnan = match value {
24561 Scalar::Float64(v) => v.is_nan(),
24562 Scalar::Null(NullKind::NaN) => true,
24563 _ => false,
24564 };
24565 (isfinite, isinf, isnan)
24566 }
24567
24568 let mut seed = 0xd1ff_1e5d_f1a7_00c5_u64;
24569 for case in 0..240 {
24570 let len = (next(&mut seed) % 71 + 1) as usize;
24571 let mut values = Vec::with_capacity(len);
24572 for pos in 0..len {
24573 let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
24574 let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
24575 values.push(match next(&mut seed) % 9 {
24576 0 => Scalar::Null(NullKind::Null),
24577 1 => Scalar::Null(NullKind::NaN),
24578 2 => Scalar::Float64(f64::NAN),
24579 3 => Scalar::Float64(f64::INFINITY),
24580 4 => Scalar::Float64(f64::NEG_INFINITY),
24581 5 => Scalar::Int64(raw),
24582 6 => Scalar::Utf8(format!("s{case}_{pos}")),
24583 _ => Scalar::Float64(raw as f64 / 37.0 + frac),
24584 });
24585 }
24586
24587 let input = Column::from_values(values.clone()).expect("column");
24588 let finite = input.isfinite().expect("isfinite");
24589 let infinite = input.isinf().expect("isinf");
24590 let nan = input.isnan().expect("isnan");
24591
24592 assert_eq!(finite.dtype(), DType::Bool);
24593 assert_eq!(infinite.dtype(), DType::Bool);
24594 assert_eq!(nan.dtype(), DType::Bool);
24595 assert_eq!(finite.values().len(), values.len());
24596 assert_eq!(infinite.values().len(), values.len());
24597 assert_eq!(nan.values().len(), values.len());
24598
24599 for (pos, value) in values.iter().enumerate() {
24600 let (expected_finite, expected_inf, expected_nan) = oracle(value);
24601 assert_eq!(
24602 finite.values()[pos],
24603 Scalar::Bool(expected_finite),
24604 "case={case} pos={pos}: isfinite mismatch for {value:?}"
24605 );
24606 assert_eq!(
24607 infinite.values()[pos],
24608 Scalar::Bool(expected_inf),
24609 "case={case} pos={pos}: isinf mismatch for {value:?}"
24610 );
24611 assert_eq!(
24612 nan.values()[pos],
24613 Scalar::Bool(expected_nan),
24614 "case={case} pos={pos}: isnan mismatch for {value:?}"
24615 );
24616 }
24617 }
24618 }
24619
24620 #[test]
24621 fn logical_bool_ops_use_raw_buffers_without_scalar_materialization_el0g2() {
24622 let left = Column {
24623 dtype: DType::Bool,
24624 values: ScalarValues::lazy_all_valid_bool(vec![true, false, true, false]),
24625 validity: ValidityMask::all_valid(4),
24626 data: None,
24627 };
24628 let right = Column {
24629 dtype: DType::Bool,
24630 values: ScalarValues::lazy_all_valid_bool(vec![true, true, false, false]),
24631 validity: ValidityMask::all_valid(4),
24632 data: None,
24633 };
24634
24635 assert_eq!(
24636 left.logical_and(&right).expect("and").values(),
24637 &[
24638 Scalar::Bool(true),
24639 Scalar::Bool(false),
24640 Scalar::Bool(false),
24641 Scalar::Bool(false),
24642 ]
24643 );
24644 assert_eq!(
24645 left.logical_or(&right).expect("or").values(),
24646 &[
24647 Scalar::Bool(true),
24648 Scalar::Bool(true),
24649 Scalar::Bool(true),
24650 Scalar::Bool(false),
24651 ]
24652 );
24653 assert_eq!(
24654 left.logical_xor(&right).expect("xor").values(),
24655 &[
24656 Scalar::Bool(false),
24657 Scalar::Bool(true),
24658 Scalar::Bool(true),
24659 Scalar::Bool(false),
24660 ]
24661 );
24662 assert_eq!(
24663 left.logical_not().expect("not").values(),
24664 &[
24665 Scalar::Bool(false),
24666 Scalar::Bool(true),
24667 Scalar::Bool(false),
24668 Scalar::Bool(true),
24669 ]
24670 );
24671
24672 assert!(matches!(
24673 &left.values,
24674 ScalarValues::LazyAllValidBool { .. }
24675 ));
24676 assert!(matches!(
24677 &right.values,
24678 ScalarValues::LazyAllValidBool { .. }
24679 ));
24680 if let ScalarValues::LazyAllValidBool { values, .. } = &left.values {
24681 assert!(values.get().is_none());
24682 }
24683 if let ScalarValues::LazyAllValidBool { values, .. } = &right.values {
24684 assert!(values.get().is_none());
24685 }
24686 }
24687
24688 #[test]
24689 fn bitwise_bool_ops_use_raw_buffers_without_scalar_materialization_ffoy7() {
24690 let left = Column {
24691 dtype: DType::Bool,
24692 values: ScalarValues::lazy_all_valid_bool(vec![true, false, true, false]),
24693 validity: ValidityMask::all_valid(4),
24694 data: None,
24695 };
24696 let right = Column {
24697 dtype: DType::Bool,
24698 values: ScalarValues::lazy_all_valid_bool(vec![false, false, true, true]),
24699 validity: ValidityMask::all_valid(4),
24700 data: None,
24701 };
24702
24703 assert_eq!(
24704 left.bitwise_and(&right).expect("and").values(),
24705 &[
24706 Scalar::Bool(false),
24707 Scalar::Bool(false),
24708 Scalar::Bool(true),
24709 Scalar::Bool(false),
24710 ]
24711 );
24712 assert_eq!(
24713 left.bitwise_or(&right).expect("or").values(),
24714 &[
24715 Scalar::Bool(true),
24716 Scalar::Bool(false),
24717 Scalar::Bool(true),
24718 Scalar::Bool(true),
24719 ]
24720 );
24721 assert_eq!(
24722 left.bitwise_xor(&right).expect("xor").values(),
24723 &[
24724 Scalar::Bool(true),
24725 Scalar::Bool(false),
24726 Scalar::Bool(false),
24727 Scalar::Bool(true),
24728 ]
24729 );
24730 assert_eq!(
24731 left.bitwise_not().expect("not").values(),
24732 &[
24733 Scalar::Bool(false),
24734 Scalar::Bool(true),
24735 Scalar::Bool(false),
24736 Scalar::Bool(true),
24737 ]
24738 );
24739
24740 assert!(matches!(
24741 &left.values,
24742 ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
24743 ));
24744 assert!(matches!(
24745 &right.values,
24746 ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
24747 ));
24748 }
24749
24750 #[test]
24751 fn bool_comparison_ops_use_raw_buffers_without_scalar_materialization_v7rko() {
24752 let left = Column {
24753 dtype: DType::Bool,
24754 values: ScalarValues::lazy_all_valid_bool(vec![false, false, true, true]),
24755 validity: ValidityMask::all_valid(4),
24756 data: None,
24757 };
24758 let right = Column {
24759 dtype: DType::Bool,
24760 values: ScalarValues::lazy_all_valid_bool(vec![false, true, false, true]),
24761 validity: ValidityMask::all_valid(4),
24762 data: None,
24763 };
24764
24765 assert_eq!(
24766 left.eq(&right).expect("eq").values(),
24767 &[
24768 Scalar::Bool(true),
24769 Scalar::Bool(false),
24770 Scalar::Bool(false),
24771 Scalar::Bool(true),
24772 ]
24773 );
24774 assert_eq!(
24775 left.ne(&right).expect("ne").values(),
24776 &[
24777 Scalar::Bool(false),
24778 Scalar::Bool(true),
24779 Scalar::Bool(true),
24780 Scalar::Bool(false),
24781 ]
24782 );
24783 assert_eq!(
24784 left.gt(&right).expect("gt").values(),
24785 &[
24786 Scalar::Bool(false),
24787 Scalar::Bool(false),
24788 Scalar::Bool(true),
24789 Scalar::Bool(false),
24790 ]
24791 );
24792 assert_eq!(
24793 left.lt(&right).expect("lt").values(),
24794 &[
24795 Scalar::Bool(false),
24796 Scalar::Bool(true),
24797 Scalar::Bool(false),
24798 Scalar::Bool(false),
24799 ]
24800 );
24801 assert_eq!(
24802 left.ge(&right).expect("ge").values(),
24803 &[
24804 Scalar::Bool(true),
24805 Scalar::Bool(false),
24806 Scalar::Bool(true),
24807 Scalar::Bool(true),
24808 ]
24809 );
24810 assert_eq!(
24811 left.le(&right).expect("le").values(),
24812 &[
24813 Scalar::Bool(true),
24814 Scalar::Bool(true),
24815 Scalar::Bool(false),
24816 Scalar::Bool(true),
24817 ]
24818 );
24819
24820 assert!(matches!(
24821 &left.values,
24822 ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
24823 ));
24824 assert!(matches!(
24825 &right.values,
24826 ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
24827 ));
24828 }
24829
24830 #[test]
24831 fn var_std_sem_ddof_one() {
24832 let col = Column::from_values(vec![
24833 Scalar::Float64(2.0),
24834 Scalar::Float64(4.0),
24835 Scalar::Float64(4.0),
24836 Scalar::Float64(4.0),
24837 Scalar::Float64(5.0),
24838 Scalar::Float64(5.0),
24839 Scalar::Float64(7.0),
24840 Scalar::Float64(9.0),
24841 ])
24842 .expect("col");
24843 match col.var(1) {
24844 Scalar::Float64(v) => assert!((v - 4.571428571428571).abs() < 1e-9),
24845 other => unreachable!("expected Float64, got {other:?}"),
24846 }
24847 match col.std(1) {
24848 Scalar::Float64(v) => assert!((v - 2.138089935299395).abs() < 1e-9),
24849 other => unreachable!("expected Float64, got {other:?}"),
24850 }
24851 match col.sem(1) {
24852 Scalar::Float64(v) => assert!((v - 0.7559289460184544).abs() < 1e-9),
24853 other => unreachable!("expected Float64, got {other:?}"),
24854 }
24855 }
24856
24857 #[test]
24858 fn skew_symmetric_is_zero() {
24859 let col = Column::from_values(vec![
24860 Scalar::Float64(1.0),
24861 Scalar::Float64(2.0),
24862 Scalar::Float64(3.0),
24863 Scalar::Float64(4.0),
24864 Scalar::Float64(5.0),
24865 ])
24866 .expect("col");
24867 match col.skew() {
24868 Scalar::Float64(v) => assert!(v.abs() < 1e-9),
24869 other => unreachable!("expected Float64, got {other:?}"),
24870 }
24871 }
24872
24873 #[test]
24874 fn kurt_uniform_five_values_is_minus_one_point_two() {
24875 let col = Column::from_values(vec![
24876 Scalar::Float64(1.0),
24877 Scalar::Float64(2.0),
24878 Scalar::Float64(3.0),
24879 Scalar::Float64(4.0),
24880 Scalar::Float64(5.0),
24881 ])
24882 .expect("col");
24883 match col.kurt() {
24884 Scalar::Float64(v) => assert!((v + 1.2).abs() < 1e-9),
24885 other => unreachable!("expected Float64, got {other:?}"),
24886 }
24887 }
24888
24889 #[test]
24890 fn kurtosis_alias_matches_kurt() {
24891 let col = Column::from_values(vec![
24892 Scalar::Float64(1.0),
24893 Scalar::Float64(2.0),
24894 Scalar::Float64(3.0),
24895 Scalar::Float64(4.0),
24896 Scalar::Float64(5.0),
24897 ])
24898 .expect("col");
24899 assert_eq!(col.kurtosis(), col.kurt());
24900 }
24901
24902 #[test]
24903 fn ptp_returns_max_minus_min() {
24904 let col = Column::from_values(vec![
24905 Scalar::Float64(3.0),
24906 Scalar::Null(NullKind::NaN),
24907 Scalar::Float64(7.0),
24908 Scalar::Float64(1.0),
24909 ])
24910 .expect("col");
24911 assert_eq!(col.ptp(), Scalar::Float64(6.0));
24912 }
24913
24914 #[test]
24915 fn ptp_empty_is_null() {
24916 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
24917 assert!(col.ptp().is_missing());
24918 }
24919
24920 #[test]
24921 fn skew_too_few_values_returns_null() {
24922 let col =
24923 Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("col");
24924 assert!(col.skew().is_missing());
24925 }
24926
24927 #[test]
24928 fn rolling_window_sum_full_window() {
24929 let col = Column::from_values(vec![
24930 Scalar::Float64(1.0),
24931 Scalar::Float64(2.0),
24932 Scalar::Float64(3.0),
24933 Scalar::Float64(4.0),
24934 Scalar::Float64(5.0),
24935 ])
24936 .expect("col");
24937 let r = col.rolling_window_sum(3, 3).expect("rolling");
24939 assert!(r.values()[0].is_missing());
24940 assert!(r.values()[1].is_missing());
24941 assert_eq!(r.values()[2], Scalar::Float64(6.0));
24942 assert_eq!(r.values()[3], Scalar::Float64(9.0));
24943 assert_eq!(r.values()[4], Scalar::Float64(12.0));
24944 }
24945
24946 #[test]
24947 fn rolling_window_sum_min_periods_relaxed() {
24948 let col = Column::from_values(vec![
24949 Scalar::Float64(1.0),
24950 Scalar::Float64(2.0),
24951 Scalar::Float64(3.0),
24952 ])
24953 .expect("col");
24954 let r = col.rolling_window_sum(3, 1).expect("rolling");
24956 assert_eq!(r.values()[0], Scalar::Float64(1.0));
24957 assert_eq!(r.values()[1], Scalar::Float64(3.0));
24958 assert_eq!(r.values()[2], Scalar::Float64(6.0));
24959 }
24960
24961 #[test]
24962 fn rolling_window_sum_skips_missing() {
24963 let col = Column::from_values(vec![
24964 Scalar::Float64(1.0),
24965 Scalar::Null(NullKind::NaN),
24966 Scalar::Float64(3.0),
24967 Scalar::Float64(4.0),
24968 ])
24969 .expect("col");
24970 let r = col.rolling_window_sum(3, 2).expect("rolling");
24976 assert!(r.values()[0].is_missing());
24977 assert!(r.values()[1].is_missing());
24978 assert_eq!(r.values()[2], Scalar::Float64(4.0));
24979 assert_eq!(r.values()[3], Scalar::Float64(7.0));
24980 }
24981
24982 #[test]
24983 fn rolling_window_sum_window_zero_is_all_null() {
24984 let col =
24985 Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("col");
24986 let r = col.rolling_window_sum(0, 0).expect("rolling");
24987 assert!(r.values()[0].is_missing());
24988 assert!(r.values()[1].is_missing());
24989 assert_eq!(r.dtype(), DType::Float64);
24990 }
24991
24992 #[test]
24993 fn diff_valid_skips_missing_predecessors() {
24994 let col = Column::from_values(vec![
24995 Scalar::Null(NullKind::NaN),
24996 Scalar::Float64(1.0),
24997 Scalar::Null(NullKind::NaN),
24998 Scalar::Float64(4.0),
24999 Scalar::Float64(7.0),
25000 ])
25001 .expect("col");
25002 let r = col.diff_valid().expect("diff_valid");
25003 assert!(r.values()[0].is_missing()); assert!(r.values()[1].is_missing()); assert!(r.values()[2].is_missing()); assert_eq!(r.values()[3], Scalar::Float64(3.0)); assert_eq!(r.values()[4], Scalar::Float64(3.0)); }
25009
25010 #[test]
25011 fn diff_valid_empty_column() {
25012 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
25013 let r = col.diff_valid().expect("diff_valid");
25014 assert!(r.is_empty());
25015 assert_eq!(r.dtype(), DType::Float64);
25016 }
25017
25018 #[test]
25019 fn sample_without_replacement_deterministic_by_seed() {
25020 let col =
25021 Column::from_values((0..10).map(Scalar::Int64).collect::<Vec<_>>()).expect("col");
25022 let a = col.sample(3, 42).expect("sample");
25023 let b = col.sample(3, 42).expect("sample");
25024 assert_eq!(a.values(), b.values());
25026 assert_eq!(a.len(), 3);
25027 for v in a.values() {
25029 match v {
25030 Scalar::Int64(x) => assert!((0..10).contains(x)),
25031 other => unreachable!("unexpected value {other:?}"),
25032 }
25033 }
25034 }
25035
25036 #[test]
25037 fn sample_different_seeds_likely_differ() {
25038 let col =
25039 Column::from_values((0..100).map(Scalar::Int64).collect::<Vec<_>>()).expect("col");
25040 let a = col.sample(5, 1).expect("sample");
25041 let b = col.sample(5, 2).expect("sample");
25042 assert_ne!(a.values(), b.values());
25045 }
25046
25047 #[test]
25048 fn sample_n_at_or_above_len_returns_clone() {
25049 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25050 let r = col.sample(10, 42).expect("sample");
25051 assert_eq!(r.values(), col.values());
25052 }
25053
25054 #[test]
25055 fn first_valid_last_valid_skip_nulls() {
25056 let col = Column::from_values(vec![
25057 Scalar::Null(NullKind::NaN),
25058 Scalar::Null(NullKind::NaN),
25059 Scalar::Int64(5),
25060 Scalar::Int64(7),
25061 Scalar::Null(NullKind::NaN),
25062 ])
25063 .expect("col");
25064 assert_eq!(col.first_valid(), Some(2));
25065 assert_eq!(col.last_valid(), Some(3));
25066 assert_eq!(col.first_valid_index(), Some(2));
25067 assert_eq!(col.last_valid_index(), Some(3));
25068 }
25069
25070 #[test]
25071 fn nsmallest_keep_first_breaks_ties_by_earlier_position() {
25072 let col = Column::from_values(vec![
25073 Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(1), ])
25079 .expect("col");
25080 let r = col.nsmallest_keep(2, "first").expect("nsmallest_keep");
25081 assert_eq!(r.len(), 2);
25083 assert_eq!(r.values()[0], Scalar::Int64(1));
25084 assert_eq!(r.values()[1], Scalar::Int64(1));
25085 }
25086
25087 #[test]
25088 fn nsmallest_keep_last_breaks_ties_by_later_position() {
25089 let col = Column::from_values(vec![
25090 Scalar::Int64(1), Scalar::Int64(2),
25092 Scalar::Int64(1), Scalar::Int64(3),
25094 Scalar::Int64(1), ])
25096 .expect("col");
25097 let r = col.nsmallest_keep(2, "last").expect("nsmallest_keep");
25099 assert_eq!(r.len(), 2);
25100 assert_eq!(r.values()[0], Scalar::Int64(1));
25101 assert_eq!(r.values()[1], Scalar::Int64(1));
25102 }
25103
25104 #[test]
25105 fn nsmallest_keep_all_expands_beyond_n_on_ties() {
25106 let col = Column::from_values(vec![
25107 Scalar::Int64(1),
25108 Scalar::Int64(1),
25109 Scalar::Int64(1),
25110 Scalar::Int64(2),
25111 ])
25112 .expect("col");
25113 let r = col.nsmallest_keep(1, "all").expect("nsmallest_keep");
25115 assert_eq!(r.len(), 3);
25116 assert_eq!(r.values()[0], Scalar::Int64(1));
25117 assert_eq!(r.values()[1], Scalar::Int64(1));
25118 assert_eq!(r.values()[2], Scalar::Int64(1));
25119 }
25120
25121 #[test]
25122 fn nlargest_keep_mirror_symmetry() {
25123 let col = Column::from_values(vec![
25124 Scalar::Int64(1),
25125 Scalar::Int64(3),
25126 Scalar::Int64(3),
25127 Scalar::Int64(2),
25128 ])
25129 .expect("col");
25130 let r = col.nlargest_keep(1, "all").expect("nlargest_keep");
25131 assert_eq!(r.len(), 2);
25132 assert_eq!(r.values()[0], Scalar::Int64(3));
25133 assert_eq!(r.values()[1], Scalar::Int64(3));
25134 }
25135
25136 #[test]
25137 fn nkeep_invalid_keep_errors() {
25138 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25139 assert!(col.nsmallest_keep(1, "middle").is_err());
25140 assert!(col.nlargest_keep(1, "middle").is_err());
25141 }
25142
25143 #[test]
25144 fn nkeep_zero_is_empty_same_dtype() {
25145 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25146 let r = col.nsmallest_keep(0, "first").expect("nsmallest_keep");
25147 assert!(r.is_empty());
25148 assert_eq!(r.dtype(), DType::Int64);
25149 }
25150
25151 #[test]
25152 fn first_valid_last_valid_all_missing_is_none() {
25153 let col = Column::from_values(vec![
25154 Scalar::Null(NullKind::NaN),
25155 Scalar::Null(NullKind::Null),
25156 ])
25157 .expect("col");
25158 assert_eq!(col.first_valid(), None);
25159 assert_eq!(col.last_valid(), None);
25160 assert_eq!(col.first_valid_index(), None);
25161 assert_eq!(col.last_valid_index(), None);
25162 }
25163
25164 #[test]
25165 fn rolling_window_sum_empty_column() {
25166 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
25167 let r = col.rolling_window_sum(3, 1).expect("rolling");
25168 assert!(r.is_empty());
25169 assert_eq!(r.dtype(), DType::Float64);
25170 }
25171
25172 #[test]
25173 fn pct_change_negative_periods() {
25174 let col = Column::from_values(vec![Scalar::Float64(10.0), Scalar::Float64(15.0)])
25175 .expect("col");
25176 let r = col.pct_change(-1).expect("pct_change");
25177 assert!(
25179 matches!(&r.values()[0], Scalar::Float64(v) if (*v + 1.0 / 3.0).abs() < 1e-9),
25180 "expected Float64, got {:?}",
25181 r.values()[0]
25182 );
25183 assert!(r.values()[1].is_missing());
25184 }
25185
25186 #[test]
25187 fn count_excludes_nulls() {
25188 let col = Column::from_values(vec![
25189 Scalar::Int64(1),
25190 Scalar::Null(NullKind::NaN),
25191 Scalar::Int64(2),
25192 Scalar::Null(NullKind::Null),
25193 ])
25194 .expect("col");
25195 assert_eq!(col.count(), 2);
25196 }
25197
25198 #[test]
25199 fn count_and_nunique_match_scalar_oracle_05112() {
25200 fn next(seed: &mut u64) -> u64 {
25203 *seed = seed
25204 .wrapping_mul(6364136223846793005)
25205 .wrapping_add(1442695040888963407);
25206 *seed
25207 }
25208
25209 fn same_unique_bucket(left: &Scalar, right: &Scalar) -> bool {
25210 match (left, right) {
25211 (Scalar::Float64(left), Scalar::Float64(right)) => {
25212 let left = if *left == 0.0 { 0.0 } else { *left };
25213 let right = if *right == 0.0 { 0.0 } else { *right };
25214 left.to_bits() == right.to_bits()
25215 }
25216 _ => left == right,
25217 }
25218 }
25219
25220 fn expected_nunique(values: &[Scalar], dropna: bool) -> i64 {
25221 let mut seen = Vec::<Scalar>::new();
25222 let mut saw_missing = false;
25223 for value in values {
25224 if value.is_missing() {
25225 saw_missing = true;
25226 continue;
25227 }
25228 if !seen
25229 .iter()
25230 .any(|existing| same_unique_bucket(existing, value))
25231 {
25232 seen.push(value.clone());
25233 }
25234 }
25235 let missing_bucket = i64::from(!dropna && saw_missing);
25236 seen.len() as i64 + missing_bucket
25237 }
25238
25239 fn assert_reducers(case: usize, family: &str, values: Vec<Scalar>) {
25240 let input = Column::from_values(values.clone()).expect("column");
25241 let expected_count = values.iter().filter(|value| !value.is_missing()).count();
25242 assert_eq!(
25243 input.count(),
25244 expected_count,
25245 "case={case} family={family}: count mismatch for {values:?}"
25246 );
25247 assert_eq!(
25248 input.nunique(),
25249 Scalar::Int64(expected_nunique(&values, true)),
25250 "case={case} family={family}: nunique(dropna=true) mismatch for {values:?}"
25251 );
25252 assert_eq!(
25253 input.nunique_with_dropna(false),
25254 Scalar::Int64(expected_nunique(&values, false)),
25255 "case={case} family={family}: nunique(dropna=false) mismatch for {values:?}"
25256 );
25257 }
25258
25259 let all_missing = vec![
25260 Scalar::Null(NullKind::Null),
25261 Scalar::Null(NullKind::NaN),
25262 Scalar::Float64(f64::NAN),
25263 Scalar::Timedelta64(i64::MIN),
25264 ];
25265 assert_reducers(usize::MAX, "all_missing", all_missing);
25266
25267 let mut seed = 0x0511_2c0a_1e5c_a1a5_u64;
25268 for case in 0..180 {
25269 let len = (next(&mut seed) % 67 + 1) as usize;
25270
25271 let mut floats = Vec::with_capacity(len);
25272 floats.push(Scalar::Float64(0.0));
25273 for _ in 1..len {
25274 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
25275 let value = match next(&mut seed) % 9 {
25276 0 => f64::NAN,
25277 1 => f64::INFINITY,
25278 2 => f64::NEG_INFINITY,
25279 3 => -0.0,
25280 4 => 0.0,
25281 _ => raw as f64 / 17.0,
25282 };
25283 floats.push(Scalar::Float64(value));
25284 }
25285 assert_reducers(case, "float", floats);
25286
25287 let mut ints = Vec::with_capacity(len);
25288 ints.push(Scalar::Int64(case as i64 % 11 - 5));
25289 for _ in 1..len {
25290 let raw = (next(&mut seed) % 41) as i64 - 20;
25291 ints.push(match next(&mut seed) % 6 {
25292 0 => Scalar::Null(NullKind::Null),
25293 1 => Scalar::Null(NullKind::NaN),
25294 _ => Scalar::Int64(raw),
25295 });
25296 }
25297 assert_reducers(case, "int", ints);
25298
25299 let mut bools = Vec::with_capacity(len);
25300 bools.push(Scalar::Bool(case & 1 == 0));
25301 for _ in 1..len {
25302 bools.push(match next(&mut seed) % 5 {
25303 0 => Scalar::Null(NullKind::Null),
25304 1 => Scalar::Null(NullKind::NaN),
25305 raw => Scalar::Bool(raw & 1 == 0),
25306 });
25307 }
25308 assert_reducers(case, "bool", bools);
25309
25310 let mut utf8 = Vec::with_capacity(len);
25311 utf8.push(Scalar::Utf8(format!("s{}", case % 13)));
25312 for pos in 1..len {
25313 utf8.push(match next(&mut seed) % 7 {
25314 0 => Scalar::Null(NullKind::Null),
25315 1 => Scalar::Null(NullKind::NaN),
25316 raw => Scalar::Utf8(format!("s{}_{}", raw, pos % 5)),
25317 });
25318 }
25319 assert_reducers(case, "utf8", utf8);
25320
25321 let mut timedeltas = Vec::with_capacity(len);
25322 timedeltas.push(Scalar::Timedelta64(case as i64));
25323 for _ in 1..len {
25324 let raw = (next(&mut seed) % 97) as i64 - 48;
25325 timedeltas.push(match next(&mut seed) % 7 {
25326 0 => Scalar::Null(NullKind::Null),
25327 1 => Scalar::Timedelta64(i64::MIN),
25328 _ => Scalar::Timedelta64(raw),
25329 });
25330 }
25331 assert_reducers(case, "timedelta", timedeltas);
25332 }
25333 }
25334
25335 #[test]
25336 fn count_uses_nullable_int64_validity_without_scalar_materialization_aed6d() {
25337 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 3), (7, 1)]), 10);
25338 let col = Column::from_i64_values_with_validity((0_i64..10).collect(), validity);
25339
25340 assert_eq!(col.count(), 6);
25341 assert!(matches!(
25342 &col.values,
25343 ScalarValues::LazyNullableInt64 { .. }
25344 ));
25345 if let ScalarValues::LazyNullableInt64 { values, .. } = &col.values {
25346 assert!(values.get().is_none());
25347 }
25348 }
25349
25350 #[test]
25351 fn count_float64_raw_path_still_excludes_nan_aed6d() {
25352 let col = Column {
25353 dtype: DType::Float64,
25354 values: ScalarValues::lazy_all_valid_float64(vec![
25355 1.0,
25356 f64::NAN,
25357 f64::INFINITY,
25358 -0.0,
25359 ]),
25360 validity: ValidityMask::all_valid(4),
25361 data: None,
25362 };
25363
25364 assert_eq!(col.count(), 3);
25365 assert!(matches!(
25366 &col.values,
25367 ScalarValues::LazyAllValidFloat64 { .. }
25368 ));
25369 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &col.values {
25370 assert!(values.get().is_none());
25371 }
25372 }
25373 }
25374
25375 mod where_mask {
25376 use fp_types::NullKind;
25377
25378 use super::*;
25379
25380 #[test]
25381 fn where_cond_keeps_true_positions() {
25382 let col =
25383 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
25384 .expect("col");
25385 let cond = Column::from_values(vec![
25386 Scalar::Bool(true),
25387 Scalar::Bool(false),
25388 Scalar::Bool(true),
25389 ])
25390 .expect("cond");
25391 let fill = Scalar::Int64(-1);
25392 let out = col.where_cond(&cond, &fill).expect("where");
25393 assert_eq!(col.r#where(&cond, &fill).expect("where"), out);
25394 assert_eq!(out.values()[0], Scalar::Int64(1));
25395 assert_eq!(out.values()[1], Scalar::Int64(-1));
25396 assert_eq!(out.values()[2], Scalar::Int64(3));
25397 }
25398
25399 #[test]
25400 fn mask_inverts_where_cond() {
25401 let col =
25402 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
25403 .expect("col");
25404 let cond = Column::from_values(vec![
25405 Scalar::Bool(true),
25406 Scalar::Bool(false),
25407 Scalar::Bool(true),
25408 ])
25409 .expect("cond");
25410 let fill = Scalar::Int64(0);
25411 let out = col.mask(&cond, &fill).expect("mask");
25412 assert_eq!(out.values()[0], Scalar::Int64(0));
25413 assert_eq!(out.values()[1], Scalar::Int64(2));
25414 assert_eq!(out.values()[2], Scalar::Int64(0));
25415 }
25416
25417 #[test]
25418 fn where_missing_cond_propagates_null() {
25419 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25420 let cond = Column::from_values(vec![Scalar::Bool(true), Scalar::Null(NullKind::NaN)])
25421 .expect("cond");
25422 let fill = Scalar::Int64(-1);
25423 let out = col.where_cond(&cond, &fill).expect("where");
25424 assert_eq!(out.values()[0], Scalar::Int64(1));
25425 assert!(out.values()[1].is_missing());
25426 }
25427
25428 #[test]
25429 fn where_rejects_non_bool_cond() {
25430 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25431 let cond = Column::from_values(vec![Scalar::Int64(1)]).expect("cond");
25432 let err = col.where_cond(&cond, &Scalar::Int64(0)).unwrap_err();
25433 assert!(matches!(err, crate::ColumnError::InvalidMaskType { .. }));
25434 }
25435
25436 #[test]
25437 fn equals_elementwise_matches_semantic_eq() {
25438 let a = Column::from_values(vec![
25439 Scalar::Int64(1),
25440 Scalar::Int64(2),
25441 Scalar::Null(NullKind::NaN),
25442 ])
25443 .expect("a");
25444 let b = Column::from_values(vec![
25445 Scalar::Int64(1),
25446 Scalar::Int64(3),
25447 Scalar::Null(NullKind::NaN),
25448 ])
25449 .expect("b");
25450 let r = a.equals(&b).expect("equals");
25451 assert_eq!(r.dtype(), DType::Bool);
25452 assert_eq!(r.values()[0], Scalar::Bool(true));
25453 assert_eq!(r.values()[1], Scalar::Bool(false));
25454 assert_eq!(r.values()[2], Scalar::Bool(false));
25456 }
25457
25458 #[test]
25459 fn equals_length_mismatch_errors() {
25460 let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
25461 let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
25462 assert!(a.equals(&b).is_err());
25463 }
25464
25465 #[test]
25466 fn dot_ignores_missing() {
25467 let a = Column::from_values(vec![
25468 Scalar::Float64(1.0),
25469 Scalar::Null(NullKind::NaN),
25470 Scalar::Float64(3.0),
25471 ])
25472 .expect("a");
25473 let b = Column::from_values(vec![
25474 Scalar::Float64(2.0),
25475 Scalar::Float64(4.0),
25476 Scalar::Float64(5.0),
25477 ])
25478 .expect("b");
25479 let r = a.dot(&b).expect("dot");
25480 assert!((r - 17.0).abs() < 1e-9);
25482 }
25483
25484 #[test]
25485 fn dot_non_numeric_errors() {
25486 let a = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("a");
25487 let b = Column::from_values(vec![Scalar::Float64(1.0)]).expect("b");
25488 assert!(a.dot(&b).is_err());
25489 }
25490
25491 #[test]
25492 fn fillna_with_column_fills_missing_positions() {
25493 let a = Column::from_values(vec![
25494 Scalar::Int64(1),
25495 Scalar::Null(NullKind::NaN),
25496 Scalar::Int64(3),
25497 ])
25498 .expect("a");
25499 let b = Column::from_values(vec![
25500 Scalar::Int64(10),
25501 Scalar::Int64(20),
25502 Scalar::Int64(30),
25503 ])
25504 .expect("b");
25505 let r = a.fillna_with_column(&b).expect("fillna_with_column");
25506 assert_eq!(r.values()[0], Scalar::Int64(1));
25507 assert_eq!(r.values()[1], Scalar::Int64(20));
25508 assert_eq!(r.values()[2], Scalar::Int64(3));
25509 }
25510
25511 #[test]
25512 fn divmod_returns_quotient_and_remainder() {
25513 let a = Column::from_values(vec![
25514 Scalar::Float64(10.0),
25515 Scalar::Float64(7.0),
25516 Scalar::Float64(-5.0),
25517 ])
25518 .expect("a");
25519 let b = Column::from_values(vec![
25520 Scalar::Float64(3.0),
25521 Scalar::Float64(2.0),
25522 Scalar::Float64(3.0),
25523 ])
25524 .expect("b");
25525 let (q, r) = a.divmod(&b).expect("divmod");
25526 match (&q.values()[0], &r.values()[0]) {
25528 (Scalar::Float64(qv), Scalar::Float64(rv)) => {
25529 assert!((qv - 3.0).abs() < 1e-9);
25530 assert!((rv - 1.0).abs() < 1e-9);
25531 }
25532 other => unreachable!("unexpected {other:?}"),
25533 }
25534 match (&q.values()[1], &r.values()[1]) {
25536 (Scalar::Float64(qv), Scalar::Float64(rv)) => {
25537 assert!((qv - 3.0).abs() < 1e-9);
25538 assert!((rv - 1.0).abs() < 1e-9);
25539 }
25540 other => unreachable!("unexpected {other:?}"),
25541 }
25542 match (&q.values()[2], &r.values()[2]) {
25544 (Scalar::Float64(qv), Scalar::Float64(rv)) => {
25545 assert!((qv + 2.0).abs() < 1e-9);
25546 assert!((rv - 1.0).abs() < 1e-9);
25547 }
25548 other => unreachable!("unexpected {other:?}"),
25549 }
25550 }
25551
25552 #[test]
25553 fn divmod_zero_divisor_yields_null() {
25554 let a = Column::from_values(vec![Scalar::Float64(10.0)]).expect("a");
25555 let b = Column::from_values(vec![Scalar::Float64(0.0)]).expect("b");
25556 let (q, r) = a.divmod(&b).expect("divmod");
25557 assert!(q.values()[0].is_missing());
25558 assert!(r.values()[0].is_missing());
25559 }
25560
25561 #[test]
25562 fn divmod_infinite_operands_match_pandas_float_semantics() {
25563 let a = Column::from_values(vec![
25564 Scalar::Float64(f64::INFINITY),
25565 Scalar::Float64(f64::NEG_INFINITY),
25566 Scalar::Float64(5.0),
25567 Scalar::Float64(-5.0),
25568 Scalar::Float64(f64::INFINITY),
25569 ])
25570 .expect("a");
25571 let b = Column::from_values(vec![
25572 Scalar::Float64(2.0),
25573 Scalar::Float64(-2.0),
25574 Scalar::Float64(f64::INFINITY),
25575 Scalar::Float64(f64::INFINITY),
25576 Scalar::Float64(f64::INFINITY),
25577 ])
25578 .expect("b");
25579
25580 let (q, r) = a.divmod(&b).expect("divmod");
25581 assert!(matches!(q.values()[0], Scalar::Float64(v) if v.is_nan()));
25582 assert!(matches!(r.values()[0], Scalar::Float64(v) if v.is_nan()));
25583 assert!(matches!(q.values()[1], Scalar::Float64(v) if v.is_nan()));
25584 assert!(matches!(r.values()[1], Scalar::Float64(v) if v.is_nan()));
25585 assert_eq!(q.values()[2], Scalar::Float64(0.0));
25586 assert_eq!(r.values()[2], Scalar::Float64(5.0));
25587 assert_eq!(q.values()[3], Scalar::Float64(-1.0));
25588 assert_eq!(r.values()[3], Scalar::Float64(f64::INFINITY));
25589 assert!(matches!(q.values()[4], Scalar::Float64(v) if v.is_nan()));
25590 assert!(matches!(r.values()[4], Scalar::Float64(v) if v.is_nan()));
25591 }
25592
25593 #[test]
25594 fn where_cond_series_fills_from_other_column() {
25595 let col =
25596 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
25597 .expect("col");
25598 let cond = Column::from_values(vec![
25599 Scalar::Bool(true),
25600 Scalar::Bool(false),
25601 Scalar::Bool(true),
25602 ])
25603 .expect("cond");
25604 let other = Column::from_values(vec![
25605 Scalar::Int64(10),
25606 Scalar::Int64(20),
25607 Scalar::Int64(30),
25608 ])
25609 .expect("other");
25610 let out = col.where_cond_series(&cond, &other).expect("where_series");
25611 assert_eq!(out.values()[0], Scalar::Int64(1));
25612 assert_eq!(out.values()[1], Scalar::Int64(20));
25613 assert_eq!(out.values()[2], Scalar::Int64(3));
25614 }
25615
25616 #[test]
25617 fn mask_series_fills_from_other_column() {
25618 let col =
25619 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
25620 .expect("col");
25621 let cond = Column::from_values(vec![
25622 Scalar::Bool(true),
25623 Scalar::Bool(false),
25624 Scalar::Bool(true),
25625 ])
25626 .expect("cond");
25627 let other =
25628 Column::from_values(vec![Scalar::Int64(0), Scalar::Int64(0), Scalar::Int64(0)])
25629 .expect("other");
25630 let out = col.mask_series(&cond, &other).expect("mask_series");
25631 assert_eq!(out.values()[0], Scalar::Int64(0));
25632 assert_eq!(out.values()[1], Scalar::Int64(2));
25633 assert_eq!(out.values()[2], Scalar::Int64(0));
25634 }
25635
25636 #[test]
25637 fn where_cond_series_rejects_non_bool_cond() {
25638 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25639 let cond = Column::from_values(vec![Scalar::Int64(1)]).expect("cond");
25640 let other = Column::from_values(vec![Scalar::Int64(0)]).expect("other");
25641 let err = col.where_cond_series(&cond, &other).unwrap_err();
25642 assert!(matches!(err, crate::ColumnError::InvalidMaskType { .. }));
25643 }
25644
25645 #[test]
25646 fn replace_values_applies_first_match() {
25647 let col = Column::from_values(vec![
25648 Scalar::Int64(1),
25649 Scalar::Int64(2),
25650 Scalar::Int64(3),
25651 Scalar::Int64(2),
25652 ])
25653 .expect("col");
25654 let to_replace = vec![Scalar::Int64(2), Scalar::Int64(3)];
25655 let replacement = vec![Scalar::Int64(20), Scalar::Int64(30)];
25656 let out = col
25657 .replace_values(&to_replace, &replacement)
25658 .expect("replace");
25659 let alias = col
25660 .replace(&to_replace, &replacement)
25661 .expect("replace alias");
25662 assert_eq!(alias, out);
25663 assert_eq!(out.values()[0], Scalar::Int64(1));
25664 assert_eq!(out.values()[1], Scalar::Int64(20));
25665 assert_eq!(out.values()[2], Scalar::Int64(30));
25666 assert_eq!(out.values()[3], Scalar::Int64(20));
25667 }
25668
25669 #[test]
25670 fn replace_values_can_replace_nulls() {
25671 let col = Column::from_values(vec![
25672 Scalar::Int64(1),
25673 Scalar::Null(NullKind::NaN),
25674 Scalar::Int64(2),
25675 ])
25676 .expect("col");
25677 let to_replace = vec![Scalar::Null(NullKind::NaN)];
25678 let replacement = vec![Scalar::Int64(-1)];
25679 let out = col
25680 .replace_values(&to_replace, &replacement)
25681 .expect("replace");
25682 assert_eq!(out.values()[0], Scalar::Int64(1));
25683 assert_eq!(out.values()[1], Scalar::Int64(-1));
25684 assert_eq!(out.values()[2], Scalar::Int64(2));
25685 }
25686
25687 #[test]
25688 fn replace_values_length_mismatch_errors() {
25689 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25690 let err = col
25691 .replace_values(&[Scalar::Int64(1)], &[Scalar::Int64(2), Scalar::Int64(3)])
25692 .unwrap_err();
25693 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
25694 }
25695
25696 #[test]
25697 fn nonzero_returns_truthy_positions() {
25698 let col = Column::from_values(vec![
25699 Scalar::Int64(0),
25700 Scalar::Int64(5),
25701 Scalar::Null(NullKind::NaN),
25702 Scalar::Int64(-3),
25703 Scalar::Int64(0),
25704 ])
25705 .expect("col");
25706 assert_eq!(col.nonzero(), vec![1, 3]);
25707 }
25708
25709 #[test]
25710 fn nonzero_empty_column_is_empty() {
25711 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
25712 assert!(col.nonzero().is_empty());
25713 }
25714
25715 #[test]
25716 fn where_rejects_length_mismatch() {
25717 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25718 let cond = Column::from_values(vec![Scalar::Bool(true)]).expect("cond");
25719 let err = col.where_cond(&cond, &Scalar::Int64(0)).unwrap_err();
25720 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
25721 }
25722 }
25723
25724 mod nlargest_nsmallest {
25725 use fp_types::NullKind;
25726
25727 use super::*;
25728
25729 #[test]
25730 fn nlargest_returns_top_n_descending() {
25731 let col = Column::from_values(vec![
25732 Scalar::Int64(3),
25733 Scalar::Int64(1),
25734 Scalar::Int64(5),
25735 Scalar::Int64(2),
25736 Scalar::Int64(4),
25737 ])
25738 .expect("col");
25739 let top = col.nlargest(3).expect("nlargest");
25740 assert_eq!(top.len(), 3);
25741 assert_eq!(top.values()[0], Scalar::Int64(5));
25742 assert_eq!(top.values()[1], Scalar::Int64(4));
25743 assert_eq!(top.values()[2], Scalar::Int64(3));
25744 }
25745
25746 #[test]
25747 fn nsmallest_returns_bottom_n_ascending() {
25748 let col = Column::from_values(vec![
25749 Scalar::Int64(3),
25750 Scalar::Int64(1),
25751 Scalar::Int64(5),
25752 Scalar::Int64(2),
25753 Scalar::Int64(4),
25754 ])
25755 .expect("col");
25756 let bot = col.nsmallest(2).expect("nsmallest");
25757 assert_eq!(bot.len(), 2);
25758 assert_eq!(bot.values()[0], Scalar::Int64(1));
25759 assert_eq!(bot.values()[1], Scalar::Int64(2));
25760 }
25761
25762 #[test]
25763 fn nlargest_excludes_missing_when_n_fits() {
25764 let col = Column::from_values(vec![
25765 Scalar::Int64(5),
25766 Scalar::Null(NullKind::NaN),
25767 Scalar::Int64(3),
25768 Scalar::Int64(7),
25769 ])
25770 .expect("col");
25771 let top = col.nlargest(2).expect("nlargest");
25772 assert_eq!(top.len(), 2);
25773 assert_eq!(top.values()[0], Scalar::Int64(7));
25774 assert_eq!(top.values()[1], Scalar::Int64(5));
25775 }
25776
25777 #[test]
25778 fn nlargest_n_larger_than_length_clamps() {
25779 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25780 let top = col.nlargest(100).expect("nlargest");
25781 assert_eq!(top.len(), 2);
25782 }
25783
25784 #[test]
25785 fn nlargest_zero_is_empty_same_dtype() {
25786 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25787 let top = col.nlargest(0).expect("nlargest");
25788 assert!(top.is_empty());
25789 assert_eq!(top.dtype(), DType::Int64);
25790 }
25791 }
25792
25793 mod astype {
25794 use fp_types::NullKind;
25795
25796 use super::*;
25797
25798 #[test]
25799 fn astype_int_to_float_preserves_values() {
25800 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25801 let out = col.astype(DType::Float64).expect("astype");
25802 assert_eq!(out.dtype(), DType::Float64);
25803 assert_eq!(out.values()[0], Scalar::Float64(1.0));
25804 assert_eq!(out.values()[1], Scalar::Float64(2.0));
25805 }
25806
25807 #[test]
25808 fn astype_same_dtype_is_noop_clone() {
25809 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25810 let out = col.astype(DType::Int64).expect("astype");
25811 assert_eq!(out.values(), col.values());
25812 }
25813
25814 #[test]
25815 fn astype_bool_to_int() {
25816 let col =
25817 Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("col");
25818 let out = col.astype(DType::Int64).expect("astype");
25819 assert_eq!(out.dtype(), DType::Int64);
25820 assert_eq!(out.values()[0], Scalar::Int64(1));
25821 assert_eq!(out.values()[1], Scalar::Int64(0));
25822 }
25823
25824 #[test]
25825 fn astype_to_utf8_uses_pandas_string_spellings() {
25826 let bool_col = Column::new(DType::Bool, vec![Scalar::Bool(true), Scalar::Bool(false)])
25827 .expect("bool col");
25828 let int_col = Column::new(DType::Int64, vec![Scalar::Int64(-7)]).expect("int col");
25829 let float_col = Column::new(
25830 DType::Float64,
25831 vec![Scalar::Float64(1.0), Scalar::Null(NullKind::NaN)],
25832 )
25833 .expect("float col");
25834
25835 let bool_out = bool_col.astype(DType::Utf8).expect("astype bool");
25836 let int_out = int_col.astype(DType::Utf8).expect("astype int");
25837 let float_out = float_col.astype(DType::Utf8).expect("astype float");
25838
25839 assert_eq!(bool_out.dtype(), DType::Utf8);
25840 assert_eq!(
25841 bool_out.values(),
25842 &[
25843 Scalar::Utf8("True".to_owned()),
25844 Scalar::Utf8("False".to_owned()),
25845 ]
25846 );
25847 assert_eq!(int_out.values(), &[Scalar::Utf8("-7".to_owned())]);
25848 assert_eq!(
25849 float_out.values(),
25850 &[
25851 Scalar::Utf8("1.0".to_owned()),
25852 Scalar::Utf8("nan".to_owned()),
25853 ]
25854 );
25855 }
25856
25857 #[test]
25858 fn astype_propagates_missing() {
25859 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
25860 .expect("col");
25861 let out = col.astype(DType::Float64).expect("astype");
25862 assert_eq!(out.values()[0], Scalar::Float64(1.0));
25863 assert!(out.values()[1].is_missing());
25864 }
25865
25866 #[test]
25867 fn astype_finite_float_to_int_truncates_toward_zero() {
25868 let col = Column::from_values(vec![
25871 Scalar::Float64(1.5),
25872 Scalar::Float64(2.9),
25873 Scalar::Float64(-1.5),
25874 Scalar::Float64(-2.9),
25875 Scalar::Float64(0.4),
25876 ])
25877 .expect("col");
25878 let out = col.astype(DType::Int64).expect("truncating cast");
25879 assert_eq!(
25880 out.values(),
25881 &[
25882 Scalar::Int64(1),
25883 Scalar::Int64(2),
25884 Scalar::Int64(-1),
25885 Scalar::Int64(-2),
25886 Scalar::Int64(0),
25887 ]
25888 );
25889 let inf = Column::from_values(vec![Scalar::Float64(f64::INFINITY)]).expect("col");
25891 assert!(matches!(
25892 inf.astype(DType::Int64).unwrap_err(),
25893 crate::ColumnError::Type(_)
25894 ));
25895 }
25896
25897 #[test]
25898 fn new_int64_from_lossy_float_errors_unlike_astype() {
25899 let err = Column::new(DType::Int64, vec![Scalar::Float64(1.5)]).unwrap_err();
25903 assert!(matches!(
25904 err,
25905 crate::ColumnError::Type(fp_types::TypeError::LossyFloatToInt { .. })
25906 ));
25907 let ok = Column::new(DType::Int64, vec![Scalar::Float64(2.0)]).expect("integer float");
25909 assert_eq!(ok.values(), &[Scalar::Int64(2)]);
25910 }
25911 }
25912
25913 mod rank_searchsorted {
25914 use fp_types::NullKind;
25915
25916 use super::*;
25917
25918 #[test]
25919 fn rank_average_ties_get_midpoint() {
25920 let col = Column::from_values(vec![
25921 Scalar::Float64(10.0),
25922 Scalar::Float64(20.0),
25923 Scalar::Float64(20.0),
25924 Scalar::Float64(30.0),
25925 ])
25926 .expect("col");
25927 let r = col.rank("average", true).expect("rank");
25928 assert_eq!(r.values()[0], Scalar::Float64(1.0));
25929 assert_eq!(r.values()[1], Scalar::Float64(2.5));
25931 assert_eq!(r.values()[2], Scalar::Float64(2.5));
25932 assert_eq!(r.values()[3], Scalar::Float64(4.0));
25933 }
25934
25935 #[test]
25936 fn rank_min_assigns_lowest_tied_rank() {
25937 let col = Column::from_values(vec![
25938 Scalar::Int64(1),
25939 Scalar::Int64(2),
25940 Scalar::Int64(2),
25941 Scalar::Int64(3),
25942 ])
25943 .expect("col");
25944 let r = col.rank("min", true).expect("rank");
25945 assert_eq!(r.values()[1], Scalar::Float64(2.0));
25946 assert_eq!(r.values()[2], Scalar::Float64(2.0));
25947 assert_eq!(r.values()[3], Scalar::Float64(4.0));
25948 }
25949
25950 #[test]
25951 fn rank_max_assigns_highest_tied_rank() {
25952 let col = Column::from_values(vec![
25953 Scalar::Int64(1),
25954 Scalar::Int64(2),
25955 Scalar::Int64(2),
25956 Scalar::Int64(3),
25957 ])
25958 .expect("col");
25959 let r = col.rank("max", true).expect("rank");
25960 assert_eq!(r.values()[1], Scalar::Float64(3.0));
25961 assert_eq!(r.values()[2], Scalar::Float64(3.0));
25962 assert_eq!(r.values()[3], Scalar::Float64(4.0));
25963 }
25964
25965 #[test]
25966 fn rank_first_breaks_ties_by_appearance_order() {
25967 let col =
25968 Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(3), Scalar::Int64(3)])
25969 .expect("col");
25970 let r = col.rank("first", true).expect("rank");
25971 assert_eq!(r.values()[0], Scalar::Float64(3.0));
25973 assert_eq!(r.values()[1], Scalar::Float64(1.0));
25974 assert_eq!(r.values()[2], Scalar::Float64(2.0));
25975 }
25976
25977 #[test]
25978 fn rank_dense_has_no_gaps() {
25979 let col = Column::from_values(vec![
25980 Scalar::Int64(1),
25981 Scalar::Int64(2),
25982 Scalar::Int64(2),
25983 Scalar::Int64(3),
25984 ])
25985 .expect("col");
25986 let r = col.rank("dense", true).expect("rank");
25987 assert_eq!(r.values()[0], Scalar::Float64(1.0));
25988 assert_eq!(r.values()[1], Scalar::Float64(2.0));
25989 assert_eq!(r.values()[2], Scalar::Float64(2.0));
25990 assert_eq!(r.values()[3], Scalar::Float64(3.0));
25991 }
25992
25993 #[test]
25994 fn rank_null_inputs_stay_null() {
25995 let col = Column::from_values(vec![
25996 Scalar::Float64(1.0),
25997 Scalar::Null(NullKind::NaN),
25998 Scalar::Float64(2.0),
25999 ])
26000 .expect("col");
26001 let r = col.rank("average", true).expect("rank");
26002 assert_eq!(r.values()[0], Scalar::Float64(1.0));
26003 assert!(r.values()[1].is_missing());
26004 assert_eq!(r.values()[2], Scalar::Float64(2.0));
26005 }
26006
26007 #[test]
26008 fn rank_descending_reverses_assignment() {
26009 let col =
26010 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
26011 .expect("col");
26012 let r = col.rank("min", false).expect("rank");
26013 assert_eq!(r.values()[0], Scalar::Float64(3.0));
26014 assert_eq!(r.values()[1], Scalar::Float64(2.0));
26015 assert_eq!(r.values()[2], Scalar::Float64(1.0));
26016 }
26017
26018 #[test]
26019 fn rank_invalid_method_errors() {
26020 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
26021 let err = col.rank("bogus", true).unwrap_err();
26022 assert!(matches!(err, crate::ColumnError::Type(_)));
26023 }
26024
26025 #[test]
26026 fn searchsorted_left_finds_first_insertion() {
26027 let col = Column::from_values(vec![
26028 Scalar::Int64(1),
26029 Scalar::Int64(2),
26030 Scalar::Int64(2),
26031 Scalar::Int64(5),
26032 ])
26033 .expect("col");
26034 assert_eq!(col.searchsorted(&Scalar::Int64(2), "left").unwrap(), 1);
26035 assert_eq!(col.searchsorted(&Scalar::Int64(0), "left").unwrap(), 0);
26036 assert_eq!(col.searchsorted(&Scalar::Int64(6), "left").unwrap(), 4);
26037 }
26038
26039 #[test]
26040 fn searchsorted_right_finds_last_insertion() {
26041 let col = Column::from_values(vec![
26042 Scalar::Int64(1),
26043 Scalar::Int64(2),
26044 Scalar::Int64(2),
26045 Scalar::Int64(5),
26046 ])
26047 .expect("col");
26048 assert_eq!(col.searchsorted(&Scalar::Int64(2), "right").unwrap(), 3);
26049 }
26050
26051 #[test]
26052 fn searchsorted_rejects_invalid_side() {
26053 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
26054 let err = col.searchsorted(&Scalar::Int64(0), "middle").unwrap_err();
26055 assert!(matches!(err, crate::ColumnError::Type(_)));
26056 }
26057
26058 #[test]
26059 fn searchsorted_rejects_missing_needle() {
26060 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
26061 let err = col
26062 .searchsorted(&Scalar::Null(NullKind::NaN), "left")
26063 .unwrap_err();
26064 assert!(matches!(err, crate::ColumnError::Type(_)));
26065 }
26066
26067 #[test]
26068 fn searchsorted_treats_trailing_nulls_as_greater() {
26069 let col = Column::from_values(vec![
26070 Scalar::Int64(1),
26071 Scalar::Int64(2),
26072 Scalar::Null(NullKind::NaN),
26073 ])
26074 .expect("col");
26075 assert_eq!(col.searchsorted(&Scalar::Int64(3), "left").unwrap(), 2);
26077 }
26078
26079 #[test]
26080 fn searchsorted_values_left_returns_positions_column() {
26081 let col = Column::from_values(vec![
26082 Scalar::Int64(1),
26083 Scalar::Int64(2),
26084 Scalar::Int64(2),
26085 Scalar::Int64(5),
26086 ])
26087 .expect("col");
26088 let positions = col
26089 .searchsorted_values(
26090 &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(6)],
26091 "left",
26092 )
26093 .expect("searchsorted");
26094 assert_eq!(positions.dtype(), DType::Int64);
26095 assert_eq!(
26096 positions.values(),
26097 &[Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(4)]
26098 );
26099 }
26100
26101 #[test]
26102 fn searchsorted_values_right_returns_positions_column() {
26103 let col = Column::from_values(vec![
26104 Scalar::Int64(1),
26105 Scalar::Int64(2),
26106 Scalar::Int64(2),
26107 Scalar::Int64(5),
26108 ])
26109 .expect("col");
26110 let positions = col
26111 .searchsorted_values(
26112 &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(6)],
26113 "right",
26114 )
26115 .expect("searchsorted");
26116 assert_eq!(
26117 positions.values(),
26118 &[Scalar::Int64(0), Scalar::Int64(3), Scalar::Int64(4)]
26119 );
26120 }
26121
26122 #[test]
26123 fn searchsorted_values_rejects_invalid_side() {
26124 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
26125 let err = col
26126 .searchsorted_values(&[Scalar::Int64(0)], "middle")
26127 .unwrap_err();
26128 assert!(matches!(err, crate::ColumnError::Type(_)));
26129 }
26130
26131 #[test]
26132 fn searchsorted_values_rejects_missing_needles() {
26133 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
26134 let err = col
26135 .searchsorted_values(&[Scalar::Null(NullKind::NaN)], "left")
26136 .unwrap_err();
26137 assert!(matches!(err, crate::ColumnError::Type(_)));
26138 }
26139
26140 #[test]
26141 fn searchsorted_with_sorter_uses_argsort_permutation() {
26142 let col = Column::from_values(vec![
26143 Scalar::Int64(5),
26144 Scalar::Int64(1),
26145 Scalar::Int64(2),
26146 Scalar::Int64(2),
26147 ])
26148 .expect("col");
26149 let sorter = col.argsort();
26150 assert_eq!(
26151 col.searchsorted_with_sorter(&Scalar::Int64(2), "left", &sorter)
26152 .unwrap(),
26153 1
26154 );
26155 assert_eq!(
26156 col.searchsorted_with_sorter(&Scalar::Int64(2), "right", &sorter)
26157 .unwrap(),
26158 3
26159 );
26160 assert_eq!(
26161 col.searchsorted_with_sorter(&Scalar::Int64(6), "left", &sorter)
26162 .unwrap(),
26163 4
26164 );
26165 }
26166
26167 #[test]
26168 fn searchsorted_values_with_sorter_returns_positions_column() {
26169 let col = Column::from_values(vec![
26170 Scalar::Int64(5),
26171 Scalar::Int64(1),
26172 Scalar::Int64(2),
26173 Scalar::Int64(2),
26174 ])
26175 .expect("col");
26176 let sorter = col.argsort();
26177 let positions = col
26178 .searchsorted_values_with_sorter(
26179 &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(6)],
26180 "left",
26181 &sorter,
26182 )
26183 .expect("searchsorted");
26184 assert_eq!(
26185 positions.values(),
26186 &[Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(4)]
26187 );
26188 }
26189
26190 #[test]
26191 fn searchsorted_with_sorter_rejects_length_mismatch() {
26192 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
26193 let err = col
26194 .searchsorted_with_sorter(&Scalar::Int64(1), "left", &[0])
26195 .unwrap_err();
26196 assert!(matches!(
26197 err,
26198 crate::ColumnError::LengthMismatch { left: 2, right: 1 }
26199 ));
26200 }
26201
26202 #[test]
26203 fn searchsorted_with_sorter_rejects_duplicate_or_oob_indices() {
26204 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
26205 let duplicate = col
26206 .searchsorted_with_sorter(&Scalar::Int64(1), "left", &[0, 0])
26207 .unwrap_err();
26208 assert!(matches!(
26209 duplicate,
26210 crate::ColumnError::InvalidSorter { .. }
26211 ));
26212
26213 let out_of_bounds = col
26214 .searchsorted_with_sorter(&Scalar::Int64(1), "left", &[0, 2])
26215 .unwrap_err();
26216 assert!(matches!(
26217 out_of_bounds,
26218 crate::ColumnError::InvalidSorter { .. }
26219 ));
26220 }
26221 }
26222
26223 mod value_counts {
26224 use fp_types::NullKind;
26225
26226 use super::*;
26227
26228 #[test]
26229 fn value_counts_default_drops_missing_and_sorts_descending() {
26230 let col = Column::from_values(vec![
26231 Scalar::Int64(3),
26232 Scalar::Int64(1),
26233 Scalar::Null(NullKind::NaN),
26234 Scalar::Int64(3),
26235 Scalar::Int64(2),
26236 Scalar::Int64(1),
26237 Scalar::Int64(3),
26238 ])
26239 .expect("col");
26240
26241 let (values, counts) = col.value_counts().expect("value_counts");
26242 assert_eq!(
26243 values.values(),
26244 &[Scalar::Int64(3), Scalar::Int64(1), Scalar::Int64(2)]
26245 );
26246 assert_eq!(
26247 counts.values(),
26248 &[Scalar::Int64(3), Scalar::Int64(2), Scalar::Int64(1)]
26249 );
26250 }
26251
26252 #[test]
26253 fn value_counts_sort_false_preserves_first_seen_order() {
26254 let col = Column::from_values(vec![
26255 Scalar::Int64(2),
26256 Scalar::Int64(1),
26257 Scalar::Int64(2),
26258 Scalar::Int64(3),
26259 Scalar::Int64(1),
26260 ])
26261 .expect("col");
26262
26263 let (values, counts) = col
26264 .value_counts_with_options(false, false, false, true)
26265 .expect("value_counts");
26266 assert_eq!(
26267 values.values(),
26268 &[Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)]
26269 );
26270 assert_eq!(
26271 counts.values(),
26272 &[Scalar::Int64(2), Scalar::Int64(2), Scalar::Int64(1)]
26273 );
26274 }
26275
26276 #[test]
26277 fn value_counts_dropna_false_includes_missing_bucket() {
26278 let col = Column::from_values(vec![
26279 Scalar::Utf8("a".into()),
26280 Scalar::Null(NullKind::NaN),
26281 Scalar::Utf8("a".into()),
26282 Scalar::Null(NullKind::Null),
26283 ])
26284 .expect("col");
26285
26286 let (values, counts) = col
26287 .value_counts_with_options(false, true, false, false)
26288 .expect("value_counts");
26289 assert_eq!(values.values()[0], Scalar::Utf8("a".into()));
26290 assert!(values.values()[1].is_missing());
26291 assert_eq!(counts.values(), &[Scalar::Int64(2), Scalar::Int64(2)]);
26292 }
26293
26294 #[test]
26295 fn value_counts_normalize_uses_returned_total() {
26296 let col = Column::from_values(vec![
26297 Scalar::Float64(1.0),
26298 Scalar::Float64(2.0),
26299 Scalar::Float64(1.0),
26300 Scalar::Null(NullKind::NaN),
26301 ])
26302 .expect("col");
26303
26304 let (values, counts) = col
26305 .value_counts_with_options(true, true, false, true)
26306 .expect("value_counts");
26307 assert_eq!(
26308 values.values(),
26309 &[Scalar::Float64(1.0), Scalar::Float64(2.0)]
26310 );
26311 assert_eq!(counts.dtype(), DType::Float64);
26312 assert_eq!(
26313 counts.values(),
26314 &[Scalar::Float64(2.0 / 3.0), Scalar::Float64(1.0 / 3.0)]
26315 );
26316 }
26317
26318 #[test]
26319 fn python_mod_f64_handles_infinity_divisor() {
26320 use crate::python_mod_f64;
26321
26322 assert_eq!(python_mod_f64(5.0, f64::INFINITY), 5.0);
26323 assert_eq!(python_mod_f64(-5.0, f64::INFINITY), f64::INFINITY);
26324 assert_eq!(python_mod_f64(5.0, f64::NEG_INFINITY), f64::NEG_INFINITY);
26325 assert_eq!(python_mod_f64(-5.0, f64::NEG_INFINITY), -5.0);
26326 assert_eq!(python_mod_f64(0.0, f64::INFINITY), 0.0);
26327 assert!(python_mod_f64(0.0, f64::NEG_INFINITY).is_sign_negative());
26328 assert_eq!(python_mod_f64(-0.0, f64::INFINITY), 0.0);
26329 assert_eq!(python_mod_f64(-0.0, f64::NEG_INFINITY), -0.0);
26330 assert!(python_mod_f64(f64::NAN, f64::INFINITY).is_nan());
26331 assert!(python_mod_f64(f64::NAN, f64::NEG_INFINITY).is_nan());
26332 assert!(python_mod_f64(f64::INFINITY, f64::INFINITY).is_nan());
26333 assert!(python_mod_f64(f64::NEG_INFINITY, f64::NEG_INFINITY).is_nan());
26334 }
26335
26336 #[test]
26337 fn python_floor_div_f64_handles_infinite_operands() {
26338 use crate::python_floor_div_f64;
26339
26340 assert_eq!(python_floor_div_f64(5.0, f64::INFINITY), 0.0);
26341 assert_eq!(python_floor_div_f64(-5.0, f64::INFINITY), -1.0);
26342 assert_eq!(python_floor_div_f64(5.0, f64::NEG_INFINITY), -1.0);
26343 assert_eq!(python_floor_div_f64(-5.0, f64::NEG_INFINITY), 0.0);
26344 assert_eq!(python_floor_div_f64(0.0, f64::INFINITY), 0.0);
26345 assert!(python_floor_div_f64(-0.0, f64::INFINITY).is_sign_negative());
26346 assert!(python_floor_div_f64(0.0, f64::NEG_INFINITY).is_sign_negative());
26347 assert_eq!(python_floor_div_f64(-0.0, f64::NEG_INFINITY), 0.0);
26348 assert!(python_floor_div_f64(f64::INFINITY, 2.0).is_nan());
26349 assert!(python_floor_div_f64(f64::NEG_INFINITY, -2.0).is_nan());
26350 assert!(python_floor_div_f64(f64::INFINITY, f64::INFINITY).is_nan());
26351 }
26352
26353 #[test]
26354 fn histogram_counts_values_in_bins() {
26355 let col = Column::from_values(vec![
26356 Scalar::Float64(0.5),
26357 Scalar::Float64(1.5),
26358 Scalar::Float64(2.5),
26359 Scalar::Float64(1.2),
26360 Scalar::Float64(2.8),
26361 ])
26362 .unwrap();
26363 let edges = vec![0.0, 1.0, 2.0, 3.0];
26364 let counts = col.histogram(&edges).unwrap();
26365 assert_eq!(
26366 counts.values(),
26367 &[
26368 Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2), ]
26372 );
26373 }
26374
26375 #[test]
26376 fn histogram_auto_creates_bins() {
26377 let col = Column::from_values(vec![
26378 Scalar::Float64(1.0),
26379 Scalar::Float64(2.0),
26380 Scalar::Float64(3.0),
26381 Scalar::Float64(4.0),
26382 ])
26383 .unwrap();
26384 let (counts, edges) = col.histogram_auto(3).unwrap();
26385 assert_eq!(counts.len(), 3);
26386 assert_eq!(edges.len(), 4);
26387 assert!((edges[0] - 1.0).abs() < 1e-10);
26388 assert!((edges[3] - 4.0).abs() < 1e-10);
26389 }
26390
26391 #[test]
26392 fn histogram_auto_constant_values_extends_range() {
26393 let col = Column::from_values(vec![
26394 Scalar::Float64(5.0),
26395 Scalar::Float64(5.0),
26396 Scalar::Float64(5.0),
26397 ])
26398 .unwrap();
26399 let (counts, edges) = col.histogram_auto(2).unwrap();
26400 assert_eq!(counts.len(), 2);
26401 assert!(edges[0] < 5.0);
26402 assert!(edges[2] > 5.0);
26403 }
26404
26405 #[test]
26406 fn hanning_window_shape() {
26407 let win = Column::hanning(5).unwrap();
26408 assert_eq!(win.len(), 5);
26409 assert!((win.values()[0].to_f64().unwrap()).abs() < 1e-10);
26411 assert!((win.values()[4].to_f64().unwrap()).abs() < 1e-10);
26412 assert!((win.values()[2].to_f64().unwrap() - 1.0).abs() < 1e-10);
26414 }
26415
26416 #[test]
26417 fn hamming_window_shape() {
26418 let win = Column::hamming(5).unwrap();
26419 assert_eq!(win.len(), 5);
26420 let v0 = win.values()[0].to_f64().unwrap();
26422 assert!(v0 > 0.07 && v0 < 0.09);
26423 }
26424
26425 #[test]
26426 fn bartlett_window_triangular() {
26427 let win = Column::bartlett(5).unwrap();
26428 assert_eq!(win.len(), 5);
26429 assert!((win.values()[0].to_f64().unwrap()).abs() < 1e-10);
26431 assert!((win.values()[4].to_f64().unwrap()).abs() < 1e-10);
26432 assert!((win.values()[2].to_f64().unwrap() - 1.0).abs() < 1e-10);
26434 }
26435
26436 #[test]
26437 fn convolve_full_mode() {
26438 let a = Column::from_values(vec![
26439 Scalar::Float64(1.0),
26440 Scalar::Float64(2.0),
26441 Scalar::Float64(3.0),
26442 ])
26443 .unwrap();
26444 let v = Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(1.0)]).unwrap();
26445 let result = a.convolve(&v, "full").unwrap();
26446 assert_eq!(result.len(), 4);
26448 assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26449 assert!((result.values()[1].to_f64().unwrap() - 3.0).abs() < 1e-10);
26450 assert!((result.values()[2].to_f64().unwrap() - 5.0).abs() < 1e-10);
26451 assert!((result.values()[3].to_f64().unwrap() - 3.0).abs() < 1e-10);
26452 }
26453
26454 #[test]
26455 fn geomspace_creates_geometric_progression() {
26456 let col = Column::geomspace(1.0, 1000.0, 4).unwrap();
26457 assert_eq!(col.len(), 4);
26458 assert!((col.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26459 assert!((col.values()[1].to_f64().unwrap() - 10.0).abs() < 1e-10);
26460 assert!((col.values()[2].to_f64().unwrap() - 100.0).abs() < 1e-10);
26461 assert!((col.values()[3].to_f64().unwrap() - 1000.0).abs() < 1e-10);
26462 }
26463
26464 #[test]
26465 fn nan_to_num_replaces_special_values() {
26466 let col = Column::from_values(vec![
26467 Scalar::Float64(1.0),
26468 Scalar::Float64(f64::NAN),
26469 Scalar::Float64(f64::INFINITY),
26470 Scalar::Float64(f64::NEG_INFINITY),
26471 ])
26472 .unwrap();
26473 let result = col.nan_to_num().unwrap();
26474 assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26475 assert!((result.values()[1].to_f64().unwrap() - 0.0).abs() < 1e-10);
26476 assert_eq!(result.values()[2].to_f64().unwrap(), f64::MAX);
26477 assert_eq!(result.values()[3].to_f64().unwrap(), f64::MIN);
26478 }
26479
26480 #[test]
26481 fn nan_to_num_with_values_matches_replacement_oracle_am707() {
26482 fn next(seed: &mut u64) -> u64 {
26485 *seed = seed
26486 .wrapping_mul(3935559000370003845)
26487 .wrapping_add(2691343689449507681);
26488 *seed
26489 }
26490
26491 fn replacement(seed: &mut u64) -> f64 {
26492 let raw = (next(seed) % 200_001) as i64 - 100_000;
26493 raw as f64 / 23.0
26494 }
26495
26496 fn expected_value(value: &Scalar, nan: f64, posinf: f64, neginf: f64) -> f64 {
26497 match value {
26498 Scalar::Float64(v) if v.is_nan() => nan,
26499 Scalar::Float64(v) if *v == f64::INFINITY => posinf,
26500 Scalar::Float64(v) if *v == f64::NEG_INFINITY => neginf,
26501 Scalar::Float64(v) => *v,
26502 Scalar::Null(_) => nan,
26503 other => panic!("unexpected value in oracle: {other:?}"),
26504 }
26505 }
26506
26507 let mut seed = 0xa070_7a7e_0f11_ca1e_u64;
26508 for case in 0..260 {
26509 let nan = replacement(&mut seed);
26510 let posinf = replacement(&mut seed);
26511 let neginf = replacement(&mut seed);
26512 let len = (next(&mut seed) % 67 + 1) as usize;
26513 let mut values = Vec::with_capacity(len);
26514
26515 for _ in 0..len {
26516 let selector = next(&mut seed) % 13;
26517 let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
26518 let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
26519 values.push(match selector {
26520 0 => Scalar::Null(NullKind::NaN),
26521 1 => Scalar::Float64(f64::NAN),
26522 2 => Scalar::Float64(f64::INFINITY),
26523 3 => Scalar::Float64(f64::NEG_INFINITY),
26524 _ => Scalar::Float64(raw as f64 / 31.0 + frac),
26525 });
26526 }
26527
26528 let input = Column::from_values(values.clone()).expect("column");
26529 let result = input
26530 .nan_to_num_with_values(nan, posinf, neginf)
26531 .expect("nan_to_num_with_values");
26532 assert_eq!(result.dtype(), DType::Float64);
26533 assert_eq!(result.values().len(), values.len());
26534
26535 for (pos, (before, after)) in values.iter().zip(result.values()).enumerate() {
26536 let expected = expected_value(before, nan, posinf, neginf);
26537 match after {
26538 Scalar::Float64(got) => assert_eq!(
26539 *got, expected,
26540 "case={case} pos={pos}: got {got}, expected {expected}"
26541 ),
26542 other => panic!("case={case} pos={pos}: expected Float64, got {other:?}"),
26543 }
26544 }
26545 }
26546 }
26547
26548 #[test]
26549 fn rint_rounds_to_nearest_even() {
26550 let col = Column::from_values(vec![
26551 Scalar::Float64(0.5),
26552 Scalar::Float64(1.5),
26553 Scalar::Float64(2.5),
26554 Scalar::Float64(3.5),
26555 ])
26556 .unwrap();
26557 let result = col.rint().unwrap();
26558 assert!((result.values()[0].to_f64().unwrap() - 0.0).abs() < 1e-10);
26560 assert!((result.values()[1].to_f64().unwrap() - 2.0).abs() < 1e-10);
26561 assert!((result.values()[2].to_f64().unwrap() - 2.0).abs() < 1e-10);
26562 assert!((result.values()[3].to_f64().unwrap() - 4.0).abs() < 1e-10);
26563 }
26564
26565 #[test]
26566 fn ldexp_multiplies_by_power_of_two() {
26567 let col = Column::from_values(vec![
26568 Scalar::Float64(1.0),
26569 Scalar::Float64(2.0),
26570 Scalar::Float64(0.5),
26571 ])
26572 .unwrap();
26573 let result = col.ldexp(3).unwrap(); assert!((result.values()[0].to_f64().unwrap() - 8.0).abs() < 1e-10);
26575 assert!((result.values()[1].to_f64().unwrap() - 16.0).abs() < 1e-10);
26576 assert!((result.values()[2].to_f64().unwrap() - 4.0).abs() < 1e-10);
26577 }
26578
26579 #[test]
26580 fn modf_splits_integer_and_fraction() {
26581 let col = Column::from_values(vec![
26582 Scalar::Float64(3.5),
26583 Scalar::Float64(-2.25),
26584 Scalar::Float64(1.0),
26585 ])
26586 .unwrap();
26587 let (frac, int) = col.modf().unwrap();
26588 assert!((frac.values()[0].to_f64().unwrap() - 0.5).abs() < 1e-10);
26589 assert!((int.values()[0].to_f64().unwrap() - 3.0).abs() < 1e-10);
26590 assert!((frac.values()[1].to_f64().unwrap() - (-0.25)).abs() < 1e-10);
26591 assert!((int.values()[1].to_f64().unwrap() - (-2.0)).abs() < 1e-10);
26592 assert!((frac.values()[2].to_f64().unwrap() - 0.0).abs() < 1e-10);
26593 assert!((int.values()[2].to_f64().unwrap() - 1.0).abs() < 1e-10);
26594 }
26595
26596 #[test]
26597 fn spacing_returns_ulp() {
26598 let col = Column::from_values(vec![
26599 Scalar::Float64(1.0),
26600 Scalar::Float64(-1.0),
26601 Scalar::Float64(0.0),
26602 ])
26603 .unwrap();
26604 let result = col.spacing().unwrap();
26605 let s1 = result.values()[0].to_f64().unwrap();
26607 assert!(s1 > 0.0 && s1 < 1e-15);
26608 let s_neg1 = result.values()[1].to_f64().unwrap();
26610 assert!((s1 - s_neg1).abs() < 1e-20);
26611 assert_eq!(result.values()[2].to_f64().unwrap(), f64::from_bits(1));
26613 }
26614
26615 #[test]
26616 fn frexp_decomposes_floats() {
26617 let col = Column::from_values(vec![
26618 Scalar::Float64(4.0),
26619 Scalar::Float64(0.5),
26620 Scalar::Float64(-8.0),
26621 Scalar::Float64(0.0),
26622 ])
26623 .unwrap();
26624 let (mant, exp) = col.frexp().unwrap();
26625 assert!((mant.values()[0].to_f64().unwrap() - 0.5).abs() < 1e-10);
26627 assert_eq!(exp.values()[0].to_i64().unwrap(), 3);
26628 assert!((mant.values()[1].to_f64().unwrap() - 0.5).abs() < 1e-10);
26630 assert_eq!(exp.values()[1].to_i64().unwrap(), 0);
26631 assert!((mant.values()[2].to_f64().unwrap() - (-0.5)).abs() < 1e-10);
26633 assert_eq!(exp.values()[2].to_i64().unwrap(), 4);
26634 assert!((mant.values()[3].to_f64().unwrap() - 0.0).abs() < 1e-10);
26636 assert_eq!(exp.values()[3].to_i64().unwrap(), 0);
26637 }
26638
26639 #[test]
26640 fn nextafter_returns_adjacent_floats() {
26641 let col = Column::from_values(vec![
26642 Scalar::Float64(0.0),
26643 Scalar::Float64(1.0),
26644 Scalar::Float64(1.0),
26645 ])
26646 .unwrap();
26647 let toward = Column::from_values(vec![
26648 Scalar::Float64(1.0),
26649 Scalar::Float64(2.0),
26650 Scalar::Float64(0.0),
26651 ])
26652 .unwrap();
26653 let result = col.nextafter(&toward).unwrap();
26654 assert_eq!(result.values()[0].to_f64().unwrap(), f64::from_bits(1));
26656 let r1 = result.values()[1].to_f64().unwrap();
26658 assert!(r1 > 1.0 && r1 < 1.0 + 1e-15);
26659 let r2 = result.values()[2].to_f64().unwrap();
26661 assert!(r2 < 1.0 && r2 > 1.0 - 1e-15);
26662 }
26663
26664 #[test]
26665 fn isneginf_isposinf_detect_infinities() {
26666 let col = Column::from_values(vec![
26667 Scalar::Float64(f64::NEG_INFINITY),
26668 Scalar::Float64(f64::INFINITY),
26669 Scalar::Float64(1.0),
26670 Scalar::Float64(f64::NAN),
26671 ])
26672 .unwrap();
26673 let neginf = col.isneginf().unwrap();
26674 let posinf = col.isposinf().unwrap();
26675 assert_eq!(neginf.values()[0], Scalar::Bool(true));
26676 assert_eq!(neginf.values()[1], Scalar::Bool(false));
26677 assert_eq!(neginf.values()[2], Scalar::Bool(false));
26678 assert_eq!(neginf.values()[3], Scalar::Bool(false));
26679 assert_eq!(posinf.values()[0], Scalar::Bool(false));
26680 assert_eq!(posinf.values()[1], Scalar::Bool(true));
26681 assert_eq!(posinf.values()[2], Scalar::Bool(false));
26682 assert_eq!(posinf.values()[3], Scalar::Bool(false));
26683 }
26684
26685 #[test]
26686 fn exp2_computes_power_of_two() {
26687 let col = Column::from_values(vec![
26688 Scalar::Float64(0.0),
26689 Scalar::Float64(1.0),
26690 Scalar::Float64(3.0),
26691 Scalar::Float64(-1.0),
26692 ])
26693 .unwrap();
26694 let result = col.exp2().unwrap();
26695 assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26696 assert!((result.values()[1].to_f64().unwrap() - 2.0).abs() < 1e-10);
26697 assert!((result.values()[2].to_f64().unwrap() - 8.0).abs() < 1e-10);
26698 assert!((result.values()[3].to_f64().unwrap() - 0.5).abs() < 1e-10);
26699 }
26700
26701 #[test]
26702 fn sinc_computes_sinc_function() {
26703 let col = Column::from_values(vec![
26704 Scalar::Float64(0.0),
26705 Scalar::Float64(1.0),
26706 Scalar::Float64(0.5),
26707 ])
26708 .unwrap();
26709 let result = col.sinc().unwrap();
26710 assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26712 assert!(result.values()[1].to_f64().unwrap().abs() < 1e-10);
26714 let expected = 2.0 / std::f64::consts::PI;
26716 assert!((result.values()[2].to_f64().unwrap() - expected).abs() < 1e-10);
26717 }
26718
26719 #[test]
26720 fn logaddexp_computes_stable_log_sum() {
26721 let x = Column::from_values(vec![
26722 Scalar::Float64(0.0),
26723 Scalar::Float64(1.0),
26724 Scalar::Float64(-1000.0),
26725 ])
26726 .unwrap();
26727 let y = Column::from_values(vec![
26728 Scalar::Float64(0.0),
26729 Scalar::Float64(2.0),
26730 Scalar::Float64(-1000.0),
26731 ])
26732 .unwrap();
26733 let result = x.logaddexp(&y).unwrap();
26734 assert!((result.values()[0].to_f64().unwrap() - std::f64::consts::LN_2).abs() < 1e-10);
26736 let expected1 = (1.0_f64.exp() + 2.0_f64.exp()).ln();
26738 assert!((result.values()[1].to_f64().unwrap() - expected1).abs() < 1e-10);
26739 let expected2 = -1000.0 + std::f64::consts::LN_2;
26741 assert!((result.values()[2].to_f64().unwrap() - expected2).abs() < 1e-8);
26742 }
26743
26744 #[test]
26745 fn logaddexp2_computes_stable_log2_sum() {
26746 let x = Column::from_values(vec![Scalar::Float64(0.0), Scalar::Float64(1.0)]).unwrap();
26747 let y = Column::from_values(vec![Scalar::Float64(0.0), Scalar::Float64(1.0)]).unwrap();
26748 let result = x.logaddexp2(&y).unwrap();
26749 assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26751 assert!((result.values()[1].to_f64().unwrap() - 2.0).abs() < 1e-10);
26753 }
26754
26755 #[test]
26756 fn roll_shifts_elements_circularly() {
26757 let col = Column::from_values(vec![
26758 Scalar::Int64(1),
26759 Scalar::Int64(2),
26760 Scalar::Int64(3),
26761 Scalar::Int64(4),
26762 Scalar::Int64(5),
26763 ])
26764 .unwrap();
26765 let r1 = col.roll(2).unwrap();
26767 assert_eq!(r1.values()[0].to_i64().unwrap(), 4);
26768 assert_eq!(r1.values()[1].to_i64().unwrap(), 5);
26769 assert_eq!(r1.values()[2].to_i64().unwrap(), 1);
26770 let r2 = col.roll(-2).unwrap();
26772 assert_eq!(r2.values()[0].to_i64().unwrap(), 3);
26773 assert_eq!(r2.values()[1].to_i64().unwrap(), 4);
26774 assert_eq!(r2.values()[2].to_i64().unwrap(), 5);
26775 let r3 = col.roll(0).unwrap();
26777 assert_eq!(r3.values()[0].to_i64().unwrap(), 1);
26778 let r4 = col.roll(5).unwrap();
26779 assert_eq!(r4.values()[0].to_i64().unwrap(), 1);
26780 }
26781
26782 #[test]
26783 fn trim_zeros_removes_leading_trailing() {
26784 let col = Column::from_values(vec![
26785 Scalar::Int64(0),
26786 Scalar::Int64(0),
26787 Scalar::Int64(1),
26788 Scalar::Int64(2),
26789 Scalar::Int64(0),
26790 ])
26791 .unwrap();
26792 let r1 = col.trim_zeros("fb").unwrap();
26794 assert_eq!(r1.len(), 2);
26795 assert_eq!(r1.values()[0].to_i64().unwrap(), 1);
26796 assert_eq!(r1.values()[1].to_i64().unwrap(), 2);
26797 let r2 = col.trim_zeros("f").unwrap();
26799 assert_eq!(r2.len(), 3);
26800 assert_eq!(r2.values()[0].to_i64().unwrap(), 1);
26801 let r3 = col.trim_zeros("b").unwrap();
26803 assert_eq!(r3.len(), 4);
26804 assert_eq!(r3.values()[3].to_i64().unwrap(), 2);
26805 }
26806
26807 #[test]
26808 fn around_rounds_to_decimals() {
26809 let col = Column::from_values(vec![
26810 Scalar::Float64(1.234),
26811 Scalar::Float64(5.678),
26812 Scalar::Float64(3.5),
26813 ])
26814 .unwrap();
26815 let r1 = col.around(2).unwrap();
26817 assert!((r1.values()[0].to_f64().unwrap() - 1.23).abs() < 1e-10);
26818 assert!((r1.values()[1].to_f64().unwrap() - 5.68).abs() < 1e-10);
26819 assert!((r1.values()[2].to_f64().unwrap() - 3.5).abs() < 1e-10);
26820 let r2 = col.around(0).unwrap();
26822 assert!((r2.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26823 assert!((r2.values()[1].to_f64().unwrap() - 6.0).abs() < 1e-10);
26824 let col2 = Column::from_values(vec![
26826 Scalar::Float64(15.0),
26827 Scalar::Float64(24.0),
26828 Scalar::Float64(35.0),
26829 ])
26830 .unwrap();
26831 let r3 = col2.around(-1).unwrap();
26832 assert!((r3.values()[0].to_f64().unwrap() - 20.0).abs() < 1e-10);
26833 assert!((r3.values()[1].to_f64().unwrap() - 20.0).abs() < 1e-10);
26834 assert!((r3.values()[2].to_f64().unwrap() - 40.0).abs() < 1e-10);
26835 }
26836
26837 #[test]
26838 fn around_uses_numpy_half_even_ties() {
26839 let col = Column::from_values(vec![
26843 Scalar::Float64(0.5),
26844 Scalar::Float64(1.5),
26845 Scalar::Float64(2.5),
26846 Scalar::Float64(3.5),
26847 Scalar::Float64(-2.5),
26848 ])
26849 .unwrap();
26850 let r = col.around(0).unwrap();
26851 let got: Vec<f64> = r.values().iter().map(|v| v.to_f64().unwrap()).collect();
26852 assert_eq!(got, vec![0.0, 2.0, 2.0, 4.0, -2.0]);
26853
26854 let tens = Column::from_values(vec![
26856 Scalar::Float64(15.0),
26857 Scalar::Float64(25.0),
26858 Scalar::Float64(35.0),
26859 ])
26860 .unwrap();
26861 let rt = tens.around(-1).unwrap();
26862 let gott: Vec<f64> = rt.values().iter().map(|v| v.to_f64().unwrap()).collect();
26863 assert_eq!(gott, vec![20.0, 20.0, 40.0]);
26864
26865 assert_eq!(
26867 col.around(0).unwrap().values(),
26868 col.round(0).unwrap().values()
26869 );
26870 }
26871
26872 #[test]
26873 fn unwrap_removes_phase_discontinuities() {
26874 use std::f64::consts::PI;
26875 let col = Column::from_values(vec![
26876 Scalar::Float64(0.0),
26877 Scalar::Float64(PI * 0.9),
26878 Scalar::Float64(-PI * 0.9), Scalar::Float64(0.0),
26880 ])
26881 .unwrap();
26882 let result = col.unwrap(None).unwrap();
26883 assert!((result.values()[0].to_f64().unwrap() - 0.0).abs() < 1e-10);
26885 assert!((result.values()[1].to_f64().unwrap() - PI * 0.9).abs() < 1e-10);
26887 let v2 = result.values()[2].to_f64().unwrap();
26889 let v1 = result.values()[1].to_f64().unwrap();
26890 assert!((v2 - v1).abs() < PI); }
26892 }
26893
26894 #[test]
26897 fn column_has_nulls_detects_missing_values() {
26898 let col_with_null = Column::from_values(vec![
26899 Scalar::Int64(1),
26900 Scalar::Null(NullKind::Null),
26901 Scalar::Int64(3),
26902 ])
26903 .unwrap();
26904 assert!(col_with_null.has_nulls());
26905
26906 let col_no_null =
26907 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
26908 .unwrap();
26909 assert!(!col_no_null.has_nulls());
26910 }
26911
26912 #[test]
26913 fn column_promote_to_nullable_upgrades_dtype() {
26914 let col = Column::new(
26915 DType::Int64,
26916 vec![
26917 Scalar::Int64(1),
26918 Scalar::Null(NullKind::Null),
26919 Scalar::Int64(3),
26920 ],
26921 )
26922 .unwrap();
26923 assert_eq!(col.dtype(), DType::Int64);
26924 assert!(col.has_nulls());
26925
26926 let promoted = col.promote_to_nullable();
26927 assert_eq!(promoted.dtype(), DType::Int64Nullable);
26928 assert_eq!(promoted.len(), 3);
26929 }
26930
26931 #[test]
26932 fn column_promote_to_nullable_noop_without_nulls() {
26933 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
26934 .unwrap();
26935 let promoted = col.promote_to_nullable();
26936 assert_eq!(promoted.dtype(), DType::Int64);
26938 }
26939
26940 #[test]
26941 fn column_with_dtype_changes_metadata() {
26942 let col = Column::new(DType::Int64, vec![Scalar::Int64(42)]).unwrap();
26943 let changed = col.with_dtype(DType::Int64Nullable);
26944 assert_eq!(changed.dtype(), DType::Int64Nullable);
26945 assert_eq!(changed.values()[0], Scalar::Int64(42));
26946 }
26947
26948 #[test]
26949 fn nullable_int64_from_scalars_preserves_storage() {
26950 use super::ColumnData;
26951 let values = vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)];
26952 let data = ColumnData::from_scalars(&values, DType::Int64Nullable);
26953 assert!(matches!(&data, ColumnData::Int64(_)));
26954 if let ColumnData::Int64(arr) = data {
26955 assert_eq!(arr.as_ref(), [1, 2, 3]);
26956 }
26957 }
26958
26959 #[test]
26960 fn scalar_int64_cache_arc_provenance_is_shared() {
26961 let col = Column::new(
26962 DType::Int64,
26963 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
26964 )
26965 .unwrap();
26966 assert!(matches!(&col.data, Some(ColumnData::Int64(_))));
26967 let Some(ColumnData::Int64(cached)) = &col.data else {
26968 return;
26969 };
26970 let source = col.as_i64_arc().expect("all-valid Int64 source");
26971 assert!(Arc::ptr_eq(cached, &source));
26972
26973 let cloned = col.clone();
26974 assert!(matches!(
26975 &cloned.values,
26976 ScalarValues::LazyAllValidInt64 { .. }
26977 ));
26978 let ScalarValues::LazyAllValidInt64 { data, .. } = &cloned.values else {
26979 return;
26980 };
26981 assert!(Arc::ptr_eq(cached, data));
26982 }
26983
26984 #[test]
26985 fn int64_dense_cycle_witness_is_exact_and_cached_uza0466() {
26986 let col = Column::new(
26987 DType::Int64,
26988 vec![
26989 Scalar::Int64(5),
26990 Scalar::Int64(6),
26991 Scalar::Int64(7),
26992 Scalar::Int64(5),
26993 Scalar::Int64(6),
26994 Scalar::Int64(7),
26995 Scalar::Int64(5),
26996 ],
26997 )
26998 .unwrap();
26999 let witness = col
27000 .int64_dense_cycle_witness()
27001 .expect("dense cycle should certify");
27002 assert_eq!(witness.start, 5);
27003 assert_eq!(witness.period, 3);
27004 assert_eq!(witness.len, 7);
27005 assert_eq!(witness.offset_count_for_key(5), Some((0, 3)));
27006 assert_eq!(witness.offset_count_for_key(6), Some((1, 2)));
27007 assert_eq!(witness.offset_count_for_key(7), Some((2, 2)));
27008 assert_eq!(witness.offset_count_for_key(8), None);
27009
27010 let again = col
27011 .int64_dense_cycle_witness()
27012 .expect("cached dense cycle should be reusable");
27013 assert_eq!(again, witness);
27014 }
27015
27016 #[test]
27017 fn bool_affine_selection_witness_is_exact_and_cached_uza0478() {
27018 let scalar_built = Column::new(
27019 DType::Bool,
27020 vec![
27021 Scalar::Bool(true),
27022 Scalar::Bool(false),
27023 Scalar::Bool(true),
27024 Scalar::Bool(false),
27025 Scalar::Bool(true),
27026 ],
27027 )
27028 .unwrap();
27029 assert!(matches!(
27030 &scalar_built.values,
27031 ScalarValues::LazyAllValidBool { .. }
27032 ));
27033 assert_eq!(
27034 scalar_built.bool_affine_selection_witness(),
27035 Some(BoolAffineSelectionWitness {
27036 start: 0,
27037 step: 2,
27038 len: 3,
27039 })
27040 );
27041 assert_eq!(
27042 scalar_built.bool_affine_selection_witness(),
27043 Some(BoolAffineSelectionWitness {
27044 start: 0,
27045 step: 2,
27046 len: 3,
27047 })
27048 );
27049
27050 let typed_built = Column::from_bool_values(vec![false, true, false, true, false]);
27051 assert_eq!(
27052 typed_built.bool_affine_selection_witness(),
27053 Some(BoolAffineSelectionWitness {
27054 start: 1,
27055 step: 2,
27056 len: 2,
27057 })
27058 );
27059
27060 let non_affine = Column::from_bool_values(vec![true, false, false, true, true]);
27061 assert_eq!(non_affine.bool_affine_selection_witness(), None);
27062
27063 let nullable = Column::from_values(vec![
27064 Scalar::Bool(true),
27065 Scalar::Null(NullKind::Null),
27066 Scalar::Bool(true),
27067 ])
27068 .unwrap();
27069 assert_eq!(nullable.bool_affine_selection_witness(), None);
27070 }
27071
27072 #[test]
27073 fn int64_dense_cycle_witness_rejects_gaps_and_nulls_uza0466() {
27074 let gapped = Column::new(
27075 DType::Int64,
27076 vec![
27077 Scalar::Int64(5),
27078 Scalar::Int64(6),
27079 Scalar::Int64(8),
27080 Scalar::Int64(5),
27081 ],
27082 )
27083 .unwrap();
27084 assert_eq!(gapped.int64_dense_cycle_witness(), None);
27085
27086 let nullable = Column::new(
27087 DType::Int64,
27088 vec![
27089 Scalar::Int64(5),
27090 Scalar::Null(NullKind::Null),
27091 Scalar::Int64(7),
27092 ],
27093 )
27094 .unwrap();
27095 assert_eq!(nullable.int64_dense_cycle_witness(), None);
27096 }
27097
27098 #[test]
27099 fn typed_all_valid_constructors_keep_single_typed_backing() {
27100 let ints = Column::from_i64_values(vec![1, 2, 3]);
27101 assert_eq!(ints.dtype(), DType::Int64);
27102 assert!(ints.validity.all());
27103 assert!(ints.data.is_none());
27104 assert_eq!(ints.as_i64_slice(), Some([1, 2, 3].as_slice()));
27105 assert_eq!(
27106 ints.values(),
27107 &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
27108 );
27109
27110 let floats = Column::from_f64_values(vec![1.5, -0.0, f64::INFINITY]);
27111 assert_eq!(floats.dtype(), DType::Float64);
27112 assert!(floats.validity.all());
27113 assert!(floats.data.is_none());
27114 assert_eq!(
27115 floats.as_f64_slice().map(|values| {
27116 values
27117 .iter()
27118 .map(|value| value.to_bits())
27119 .collect::<Vec<_>>()
27120 }),
27121 Some(vec![
27122 1.5f64.to_bits(),
27123 (-0.0f64).to_bits(),
27124 f64::INFINITY.to_bits()
27125 ])
27126 );
27127 assert_eq!(
27128 floats.values(),
27129 &[
27130 Scalar::Float64(1.5),
27131 Scalar::Float64(-0.0),
27132 Scalar::Float64(f64::INFINITY)
27133 ]
27134 );
27135 }
27136
27137 #[test]
27138 fn from_values_float64_fast_path_preserves_surface() {
27139 let nan = f64::from_bits(0x7ff8_0000_0000_1234);
27140 let column = Column::from_values(vec![
27141 Scalar::Float64(1.5),
27142 Scalar::Float64(-0.0),
27143 Scalar::Float64(f64::INFINITY),
27144 Scalar::Float64(nan),
27145 ])
27146 .expect("homogeneous float64 column");
27147
27148 assert_eq!(column.dtype(), DType::Float64);
27149 assert!(column.data.is_none());
27150 assert!(column.validity.get(0));
27151 assert!(column.validity.get(1));
27152 assert!(column.validity.get(2));
27153 assert!(!column.validity.get(3));
27154 let bits = column
27155 .values()
27156 .iter()
27157 .map(|value| match value {
27158 Scalar::Float64(value) => Some(value.to_bits()),
27159 _ => None,
27160 })
27161 .collect::<Vec<_>>();
27162 assert_eq!(
27163 bits,
27164 vec![
27165 Some(1.5f64.to_bits()),
27166 Some((-0.0f64).to_bits()),
27167 Some(f64::INFINITY.to_bits()),
27168 Some(nan.to_bits()),
27169 ]
27170 );
27171
27172 let mixed = Column::from_values(vec![
27173 Scalar::Float64(1.0),
27174 Scalar::Null(NullKind::NaN),
27175 Scalar::Float64(3.0),
27176 ])
27177 .expect("mixed float/null fallback");
27178 assert_eq!(mixed.dtype(), DType::Float64);
27179 assert_eq!(
27180 mixed.values(),
27181 &[
27182 Scalar::Float64(1.0),
27183 Scalar::Null(NullKind::NaN),
27184 Scalar::Float64(3.0),
27185 ]
27186 );
27187
27188 let empty = Column::from_values(Vec::new()).expect("empty fallback");
27189 assert_eq!(empty.dtype(), DType::Null);
27190 assert!(empty.values().is_empty());
27191 }
27192
27193 #[test]
27194 fn repeated_slice_int64_column_matches_eager_materialization() {
27195 let lazy = Column::from_i64_repeated_slices(
27196 vec![10, 11, 12, 20, 21],
27197 vec![(0, 3), (3, 2), (0, 3)],
27198 );
27199 let eager = Column::from_i64_values(vec![10, 11, 12, 20, 21, 10, 11, 12]);
27200
27201 assert_eq!(lazy.dtype(), DType::Int64);
27202 assert!(lazy.validity.all());
27203 assert_eq!(lazy.len(), eager.len());
27204 assert_eq!(lazy.as_i64_slice(), eager.as_i64_slice());
27205 assert_eq!(lazy.values(), eager.values());
27206 assert_eq!(lazy, eager);
27207 }
27208
27209 #[test]
27210 fn nullable_repeated_slices_store_sparse_invalid_ranges() {
27211 let segments: Arc<[(usize, usize)]> = Arc::from(vec![(0, 2), (usize::MAX, 3), (2, 1)]);
27212 let column =
27213 Column::from_f64_nullable_repeated_slices_shared(vec![1.0, 2.0, 3.0], segments, 6);
27214
27215 assert_eq!(column.dtype(), DType::Float64);
27216 assert!(column.validity.words.is_empty());
27217 assert_eq!(
27218 column.validity.invalid_ranges.as_deref(),
27219 Some(&[(2, 3)][..])
27220 );
27221 assert_eq!(
27222 column.values(),
27223 &[
27224 Scalar::Float64(1.0),
27225 Scalar::Float64(2.0),
27226 Scalar::Null(NullKind::NaN),
27227 Scalar::Null(NullKind::NaN),
27228 Scalar::Null(NullKind::NaN),
27229 Scalar::Float64(3.0),
27230 ]
27231 );
27232 }
27233
27234 #[test]
27235 fn nullable_repeated_slices_accept_precomputed_sparse_validity() {
27236 let segments: Arc<[(usize, usize)]> =
27237 Arc::from(vec![(0, 1), (usize::MAX, 1), (usize::MAX, 1), (1, 1)]);
27238 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2)]), 4);
27239 let column = Column::from_f64_nullable_repeated_slices_shared_with_sparse_validity(
27240 vec![4.0, -2.0],
27241 segments,
27242 validity,
27243 4,
27244 );
27245
27246 assert_eq!(
27247 column.values(),
27248 &[
27249 Scalar::Float64(4.0),
27250 Scalar::Null(NullKind::NaN),
27251 Scalar::Null(NullKind::NaN),
27252 Scalar::Float64(-2.0),
27253 ]
27254 );
27255 assert_eq!(
27256 column.validity.invalid_ranges.as_deref(),
27257 Some(&[(1, 2)][..])
27258 );
27259 }
27260
27261 #[test]
27262 fn nullable_repeat_values_store_sparse_invalid_ranges() {
27263 let run_valid: Arc<[bool]> = Arc::from(vec![true, false, true]);
27264 let run_lens: Arc<[usize]> = Arc::from(vec![2, 3, 1]);
27265 let column = Column::from_f64_nullable_repeat_values_run_lengths(
27266 vec![7.0, 0.0, -9.0],
27267 run_valid,
27268 run_lens,
27269 6,
27270 );
27271
27272 assert_eq!(column.dtype(), DType::Float64);
27273 assert!(column.validity.words.is_empty());
27274 assert_eq!(
27275 column.validity.invalid_ranges.as_deref(),
27276 Some(&[(2, 3)][..])
27277 );
27278 assert_eq!(
27279 column.values(),
27280 &[
27281 Scalar::Float64(7.0),
27282 Scalar::Float64(7.0),
27283 Scalar::Null(NullKind::NaN),
27284 Scalar::Null(NullKind::NaN),
27285 Scalar::Null(NullKind::NaN),
27286 Scalar::Float64(-9.0),
27287 ]
27288 );
27289 }
27290
27291 #[test]
27292 fn nullable_repeat_values_accept_precomputed_sparse_validity() {
27293 let run_valid: Arc<[bool]> = Arc::from(vec![true, false, true]);
27294 let run_lens: Arc<[usize]> = Arc::from(vec![1, 2, 1]);
27295 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2)]), 4);
27296 let column = Column::from_f64_nullable_repeat_values_run_lengths_with_sparse_validity(
27297 vec![8.0, 0.0, -4.0],
27298 run_valid,
27299 run_lens,
27300 validity,
27301 4,
27302 );
27303
27304 assert_eq!(
27305 column.values(),
27306 &[
27307 Scalar::Float64(8.0),
27308 Scalar::Null(NullKind::NaN),
27309 Scalar::Null(NullKind::NaN),
27310 Scalar::Float64(-4.0),
27311 ]
27312 );
27313 assert_eq!(
27314 column.validity.invalid_ranges.as_deref(),
27315 Some(&[(1, 2)][..])
27316 );
27317 }
27318
27319 #[test]
27320 fn nullable_repeated_positions_i64_as_f64_matches_tape_materialization_uza0461() {
27321 let source: Arc<[i64]> = Arc::from(vec![10, 20, 30, 40]);
27322 let positions: Arc<[usize]> = Arc::from(vec![2, 0, 3]);
27323 let segments: Arc<[(usize, usize)]> = Arc::from(vec![(0, 2), (usize::MAX, 1), (2, 1)]);
27324 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(2, 1)]), 4);
27325 let column = Column::from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
27326 source, positions, segments, validity, 4,
27327 );
27328
27329 assert_eq!(column.dtype(), DType::Float64);
27330 assert_eq!(
27331 column.values(),
27332 &[
27333 Scalar::Float64(30.0),
27334 Scalar::Float64(10.0),
27335 Scalar::Null(NullKind::NaN),
27336 Scalar::Float64(40.0),
27337 ]
27338 );
27339 assert_eq!(
27340 column.validity.invalid_ranges.as_deref(),
27341 Some(&[(2, 1)][..])
27342 );
27343 }
27344
27345 #[test]
27346 fn nullable_repeat_positions_i64_as_f64_matches_run_values_uza0461() {
27347 let source: Arc<[i64]> = Arc::from(vec![7, -3, 11]);
27348 let run_positions: Arc<[usize]> = Arc::from(vec![0, 0, 2]);
27349 let run_valid: Arc<[bool]> = Arc::from(vec![true, false, true]);
27350 let run_lens: Arc<[usize]> = Arc::from(vec![2, 3, 1]);
27351 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(2, 3)]), 6);
27352 let column = Column::from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
27353 source,
27354 run_positions,
27355 run_valid,
27356 run_lens,
27357 validity,
27358 6,
27359 );
27360
27361 assert_eq!(column.dtype(), DType::Float64);
27362 assert_eq!(
27363 column.values(),
27364 &[
27365 Scalar::Float64(7.0),
27366 Scalar::Float64(7.0),
27367 Scalar::Null(NullKind::NaN),
27368 Scalar::Null(NullKind::NaN),
27369 Scalar::Null(NullKind::NaN),
27370 Scalar::Float64(11.0),
27371 ]
27372 );
27373 assert_eq!(
27374 column.validity.invalid_ranges.as_deref(),
27375 Some(&[(2, 3)][..])
27376 );
27377 }
27378
27379 #[test]
27380 fn dense_cycle_probe_repeat_int64_preserves_probe_order_yq96z() {
27381 let probe = Column::from_i64_values(vec![0, 1, 2, 0, 1]);
27382 let build = Column::from_i64_values(vec![1, 2, 1, 2]);
27383 let probe_witness = probe
27384 .int64_dense_cycle_witness()
27385 .expect("probe dense cycle");
27386 let build_witness = build
27387 .int64_dense_cycle_witness()
27388 .expect("build dense cycle");
27389 let column = Column::from_i64_dense_cycle_probe_repeat(
27390 Arc::from(vec![10, 11, 12, 13, 14]),
27391 probe_witness,
27392 build_witness,
27393 8,
27394 );
27395
27396 assert_eq!(column.dtype(), DType::Int64);
27397 assert!(column.validity.all());
27398 assert_eq!(
27399 column.as_i64_slice(),
27400 Some([10, 11, 11, 12, 12, 13, 14, 14].as_slice())
27401 );
27402 assert_eq!(
27403 column.values(),
27404 &[
27405 Scalar::Int64(10),
27406 Scalar::Int64(11),
27407 Scalar::Int64(11),
27408 Scalar::Int64(12),
27409 Scalar::Int64(12),
27410 Scalar::Int64(13),
27411 Scalar::Int64(14),
27412 Scalar::Int64(14),
27413 ]
27414 );
27415 }
27416
27417 #[test]
27418 fn nullable_dense_cycle_probe_build_int64_preserves_build_ties_yq96z() {
27419 let probe = Column::from_i64_values(vec![0, 1, 2, 0, 1]);
27420 let build = Column::from_i64_values(vec![1, 2, 1, 2]);
27421 let probe_witness = probe
27422 .int64_dense_cycle_witness()
27423 .expect("probe dense cycle");
27424 let build_witness = build
27425 .int64_dense_cycle_witness()
27426 .expect("build dense cycle");
27427 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(0, 1), (5, 1)]), 8);
27428 let column = Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
27429 Arc::from(vec![100, 200, 101, 201]),
27430 probe_witness,
27431 build_witness,
27432 validity,
27433 8,
27434 );
27435
27436 assert_eq!(column.dtype(), DType::Int64);
27437 assert_eq!(
27438 column.validity.invalid_ranges.as_deref(),
27439 Some(&[(0, 1), (5, 1)][..])
27440 );
27441 assert_eq!(
27442 column.values(),
27443 &[
27444 Scalar::Null(NullKind::Null),
27445 Scalar::Int64(100),
27446 Scalar::Int64(101),
27447 Scalar::Int64(200),
27448 Scalar::Int64(201),
27449 Scalar::Null(NullKind::Null),
27450 Scalar::Int64(100),
27451 Scalar::Int64(101),
27452 ]
27453 );
27454 }
27455}