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 let out: Vec<Scalar> = self
14306 .values
14307 .iter()
14308 .map(|v| cast_scalar(v, target))
14309 .collect::<Result<Vec<_>, _>>()
14310 .map_err(ColumnError::Type)?;
14311 Self::new(target, out)
14312 }
14313
14314 pub fn nsmallest_keep(&self, n: usize, keep: &str) -> Result<Self, ColumnError> {
14324 nkeep_impl(self, n, keep, true)
14325 }
14326
14327 pub fn nlargest_keep(&self, n: usize, keep: &str) -> Result<Self, ColumnError> {
14333 nkeep_impl(self, n, keep, false)
14334 }
14335
14336 pub fn nlargest(&self, n: usize) -> Result<Self, ColumnError> {
14344 let sorted = self.sort_values(false)?;
14345 let take = n.min(sorted.values.len());
14346 let values: Vec<Scalar> = sorted.values[..take].to_vec();
14347 Self::new(self.dtype, values)
14348 }
14349
14350 pub fn nsmallest(&self, n: usize) -> Result<Self, ColumnError> {
14354 let sorted = self.sort_values(true)?;
14355 let take = n.min(sorted.values.len());
14356 let values: Vec<Scalar> = sorted.values[..take].to_vec();
14357 Self::new(self.dtype, values)
14358 }
14359
14360 pub fn mask(&self, cond: &Self, other: &Scalar) -> Result<Self, ColumnError> {
14365 if cond.dtype != DType::Bool {
14366 return Err(ColumnError::InvalidMaskType { dtype: cond.dtype });
14367 }
14368 if self.values.len() != cond.values.len() {
14369 return Err(ColumnError::LengthMismatch {
14370 left: self.values.len(),
14371 right: cond.values.len(),
14372 });
14373 }
14374 if !other.is_missing()
14377 && let Some(cb) = cond.as_bool_slice()
14378 {
14379 if let Some(s) = self.as_f64_slice()
14380 && let Ok(o) = other.to_f64()
14381 {
14382 let out: Vec<f64> = (0..s.len()).map(|i| if cb[i] { o } else { s[i] }).collect();
14383 return Ok(Self::from_f64_values(out));
14384 }
14385 if let Some(s) = self.as_i64_slice()
14386 && let Scalar::Int64(o) = other
14387 {
14388 let o = *o;
14389 let out: Vec<i64> = (0..s.len()).map(|i| if cb[i] { o } else { s[i] }).collect();
14390 return Ok(Self::from_i64_values(out));
14391 }
14392 }
14393 let out: Vec<Scalar> = self
14394 .values
14395 .iter()
14396 .zip(cond.values.iter())
14397 .map(|(v, c)| match c {
14398 Scalar::Bool(true) => other.clone(),
14399 Scalar::Bool(false) => v.clone(),
14400 _ => Scalar::Null(NullKind::NaN),
14401 })
14402 .collect();
14403 Self::new(self.dtype, out)
14404 }
14405
14406 fn as_all_valid_str_vec(&self) -> Option<Vec<&str>> {
14421 if self.dtype != DType::Utf8 || !self.validity.all() {
14422 return None;
14423 }
14424 if let Some((bytes, offsets)) = self.as_utf8_contiguous() {
14431 let mut strs = Vec::with_capacity(offsets.len() - 1);
14432 for w in offsets.windows(2) {
14433 strs.push(
14434 std::str::from_utf8(&bytes[w[0]..w[1]])
14435 .expect("contiguous utf8 buffer is valid by construction"),
14436 );
14437 }
14438 return Some(strs);
14439 }
14440 let mut strs = Vec::with_capacity(self.len());
14441 for v in self.values.iter() {
14442 match v {
14443 Scalar::Utf8(s) => strs.push(s.as_str()),
14444 _ => return None,
14445 }
14446 }
14447 Some(strs)
14448 }
14449
14450 fn typed_radix_perm(&self, ascending: bool) -> Option<Vec<usize>> {
14451 if let Some(data) = self.as_i64_slice() {
14452 let keys: Vec<u64> = if ascending {
14453 data.iter().map(|&v| i64_radix_key(v)).collect()
14454 } else {
14455 data.iter().map(|&v| !i64_radix_key(v)).collect()
14456 };
14457 return Some(radix_argsort_u64(&keys));
14458 }
14459 if let Some(data) = self.as_f64_slice() {
14460 let keys: Vec<u64> = if ascending {
14461 data.iter().map(|&v| f64_radix_key(v)).collect()
14462 } else {
14463 data.iter().map(|&v| !f64_radix_key(v)).collect()
14464 };
14465 return Some(radix_argsort_u64(&keys));
14466 }
14467 None
14468 }
14469
14470 #[must_use]
14480 pub fn typed_radix_keys(&self, ascending: bool) -> Option<Vec<u64>> {
14481 if let Some(data) = self.as_i64_slice() {
14482 return Some(if ascending {
14483 data.iter().map(|&v| i64_radix_key(v)).collect()
14484 } else {
14485 data.iter().map(|&v| !i64_radix_key(v)).collect()
14486 });
14487 }
14488 if let Some(data) = self.as_f64_slice() {
14489 if data.iter().any(|x| x.is_nan()) {
14490 return None;
14491 }
14492 return Some(if ascending {
14493 data.iter().map(|&v| f64_radix_key(v)).collect()
14494 } else {
14495 data.iter().map(|&v| !f64_radix_key(v)).collect()
14496 });
14497 }
14498 None
14499 }
14500
14501 pub fn sort_values(&self, ascending: bool) -> Result<Self, ColumnError> {
14502 if let Some(data) = self.as_i64_slice() {
14506 let perm = self
14507 .typed_radix_perm(ascending)
14508 .expect("i64 slice yields perm");
14509 let sorted: Vec<i64> = perm.iter().map(|&i| data[i]).collect();
14510 return Ok(Self::from_i64_values(sorted));
14511 }
14512 if let Some(data) = self.as_f64_slice() {
14513 let perm = self
14514 .typed_radix_perm(ascending)
14515 .expect("f64 slice yields perm");
14516 let sorted: Vec<f64> = perm.iter().map(|&i| data[i]).collect();
14517 return Ok(Self::from_f64_values(sorted));
14518 }
14519 if let Some(strs) = self.as_all_valid_str_vec() {
14524 let perm = utf8_msd_argsort(&strs, ascending);
14525 let sorted: Vec<Scalar> = perm.iter().map(|&i| self.values[i].clone()).collect();
14526 return Self::new(self.dtype, sorted);
14527 }
14528 let mut indexed: Vec<(usize, &Scalar)> = self.values.iter().enumerate().collect();
14529 indexed.sort_by(|a, b| compare_scalars_na_last(a.1, b.1, ascending));
14530 let sorted: Vec<Scalar> = indexed.into_iter().map(|(_, v)| v.clone()).collect();
14531 Self::new(self.dtype, sorted)
14532 }
14533
14534 #[must_use]
14540 pub fn argsort(&self) -> Vec<usize> {
14541 self.argsort_with(true)
14542 }
14543
14544 #[must_use]
14549 pub fn argsort_with(&self, ascending: bool) -> Vec<usize> {
14550 if let Some(perm) = self.typed_radix_perm(ascending) {
14551 return perm;
14552 }
14553 if self.validity.all()
14559 && let Some((bytes, offsets)) = self.as_utf8_contiguous()
14560 {
14561 let spans: Vec<&[u8]> = offsets.windows(2).map(|w| &bytes[w[0]..w[1]]).collect();
14562 return utf8_msd_argsort_bytes(&spans, ascending);
14563 }
14564 if let Some(strs) = self.as_all_valid_str_vec() {
14569 return utf8_msd_argsort(&strs, ascending);
14570 }
14571 let mut indexed: Vec<(usize, &Scalar)> = self.values.iter().enumerate().collect();
14572 indexed.sort_by(|a, b| compare_scalars_na_last(a.1, b.1, ascending));
14573 indexed.into_iter().map(|(i, _)| i).collect()
14574 }
14575
14576 pub fn argpartition(&self, kth: usize) -> Result<Vec<usize>, ColumnError> {
14582 if kth >= self.len() {
14583 return Err(ColumnError::InvalidLength {
14584 operation: "argpartition",
14585 expected: kth + 1,
14586 actual: self.len(),
14587 });
14588 }
14589 let mut indexed: Vec<(usize, &Scalar)> = self.values.iter().enumerate().collect();
14590 indexed.select_nth_unstable_by(kth, |a, b| compare_scalars_na_last(a.1, b.1, true));
14591 Ok(indexed.into_iter().map(|(i, _)| i).collect())
14592 }
14593
14594 pub fn partition(&self, kth: usize) -> Result<Self, ColumnError> {
14599 let indices = self.argpartition(kth)?;
14600 let out: Vec<Scalar> = indices.iter().map(|&i| self.values[i].clone()).collect();
14601 Self::new(self.dtype, out)
14602 }
14603
14604 pub fn diff(&self, periods: i64) -> Result<Self, ColumnError> {
14611 let len = self.values.len();
14612 let out_dtype = match self.dtype {
14620 DType::Timedelta64 => DType::Timedelta64,
14621 DType::Bool => DType::Bool,
14622 _ => DType::Float64,
14623 };
14624 if len == 0 || periods == 0 {
14625 let null = if out_dtype == DType::Timedelta64 {
14626 Scalar::Null(NullKind::NaT)
14627 } else {
14628 Scalar::Null(NullKind::NaN)
14629 };
14630 return Self::new(out_dtype, vec![null; len]);
14631 }
14632 let abs = periods.unsigned_abs() as usize;
14633 let mut out: Vec<Scalar> = Vec::with_capacity(len);
14634 let null_scalar = if out_dtype == DType::Timedelta64 {
14635 Scalar::Null(NullKind::NaT)
14636 } else {
14637 Scalar::Null(NullKind::NaN)
14638 };
14639 for i in 0..len {
14640 if (periods > 0 && i < abs) || (periods < 0 && i + abs >= len) {
14641 out.push(null_scalar.clone());
14642 continue;
14643 }
14644 let (cur, prev) = if periods > 0 {
14645 (&self.values[i], &self.values[i - abs])
14646 } else {
14647 (&self.values[i], &self.values[i + abs])
14648 };
14649 if cur.is_missing() || prev.is_missing() {
14650 out.push(null_scalar.clone());
14651 continue;
14652 }
14653 if let (Scalar::Timedelta64(cur_ns), Scalar::Timedelta64(prev_ns)) = (cur, prev) {
14654 if *cur_ns == Timedelta::NAT || *prev_ns == Timedelta::NAT {
14655 out.push(Scalar::Null(NullKind::NaT));
14656 } else {
14657 out.push(Scalar::Timedelta64(cur_ns.saturating_sub(*prev_ns)));
14658 }
14659 continue;
14660 }
14661 if let (Scalar::Bool(cur_b), Scalar::Bool(prev_b)) = (cur, prev) {
14662 out.push(Scalar::Bool(cur_b != prev_b));
14664 continue;
14665 }
14666 match (cur.to_f64(), prev.to_f64()) {
14667 (Ok(a), Ok(b)) => out.push(Scalar::Float64(a - b)),
14668 _ => out.push(Scalar::Null(NullKind::NaN)),
14669 }
14670 }
14671 Self::new(out_dtype, out)
14672 }
14673
14674 pub fn ediff1d(
14678 &self,
14679 to_begin: Option<Scalar>,
14680 to_end: Option<Scalar>,
14681 ) -> Result<Self, ColumnError> {
14682 let mut out = Vec::new();
14683 if let Some(v) = to_begin {
14684 out.push(v);
14685 }
14686 for i in 1..self.values.len() {
14687 let cur = &self.values[i];
14688 let prev = &self.values[i - 1];
14689 if cur.is_missing() || prev.is_missing() {
14690 out.push(Scalar::Float64(f64::NAN));
14691 continue;
14692 }
14693 let cf = cur.to_f64().map_err(ColumnError::Type)?;
14694 let pf = prev.to_f64().map_err(ColumnError::Type)?;
14695 out.push(Scalar::Float64(cf - pf));
14696 }
14697 if let Some(v) = to_end {
14698 out.push(v);
14699 }
14700 Self::new(DType::Float64, out)
14701 }
14702
14703 pub fn gradient(&self) -> Result<Self, ColumnError> {
14707 let n = self.values.len();
14708 if n == 0 {
14709 return Self::new(DType::Float64, Vec::new());
14710 }
14711 if n == 1 {
14712 return Self::new(DType::Float64, vec![Scalar::Float64(0.0)]);
14713 }
14714 let vals: Vec<f64> = self
14715 .values
14716 .iter()
14717 .map(|v| v.to_f64().unwrap_or(f64::NAN))
14718 .collect();
14719 let mut out = Vec::with_capacity(n);
14720 out.push(Scalar::Float64(vals[1] - vals[0]));
14721 for i in 1..n - 1 {
14722 out.push(Scalar::Float64((vals[i + 1] - vals[i - 1]) / 2.0));
14723 }
14724 out.push(Scalar::Float64(vals[n - 1] - vals[n - 2]));
14725 Self::new(DType::Float64, out)
14726 }
14727
14728 pub fn trapz(&self, dx: f64) -> Result<Scalar, ColumnError> {
14732 let n = self.values.len();
14733 if n < 2 {
14734 return Ok(Scalar::Float64(0.0));
14735 }
14736 let vals: Vec<f64> = self
14737 .values
14738 .iter()
14739 .map(|v| v.to_f64().unwrap_or(0.0))
14740 .collect();
14741 let mut sum = 0.0;
14742 for i in 1..n {
14743 sum += (vals[i - 1] + vals[i]) / 2.0 * dx;
14744 }
14745 Ok(Scalar::Float64(sum))
14746 }
14747
14748 pub fn duplicated(&self) -> Result<Self, ColumnError> {
14754 self.duplicated_keep("first")
14755 }
14756
14757 pub fn duplicated_keep(&self, keep: &str) -> Result<Self, ColumnError> {
14763 #[derive(Hash, PartialEq, Eq)]
14764 enum Key<'a> {
14765 Null,
14766 Bool(bool),
14767 Int64(i64),
14768 FloatBits(u64),
14769 Utf8(&'a str),
14770 Timedelta64(i64),
14771 Datetime64(i64),
14772 Period(i64),
14773 Interval(u64, u64, IntervalClosed),
14774 }
14775 fn key_of(v: &Scalar) -> Key<'_> {
14776 if v.is_missing() {
14777 return Key::Null;
14778 }
14779 match v {
14780 Scalar::Bool(b) => Key::Bool(*b),
14781 Scalar::Int64(i) => Key::Int64(*i),
14782 Scalar::Float64(f) => {
14783 let norm = if *f == 0.0 { 0.0 } else { *f };
14784 Key::FloatBits(norm.to_bits())
14785 }
14786 Scalar::Utf8(s) => Key::Utf8(s.as_str()),
14787 Scalar::Timedelta64(v) => Key::Timedelta64(*v),
14788 Scalar::Datetime64(v) => Key::Datetime64(*v),
14789 Scalar::Period(p) => Key::Period(p.ordinal),
14790 Scalar::Interval(v) => {
14791 let (left, right, closed) = interval_key(v);
14792 Key::Interval(left, right, closed)
14793 }
14794 Scalar::Null(_) => Key::Null,
14795 }
14796 }
14797
14798 let policy = match keep {
14799 "first" => DupPolicy::First,
14800 "last" => DupPolicy::Last,
14801 "false" | "False" | "none" => DupPolicy::None,
14802 other => {
14803 return Err(ColumnError::Type(TypeError::NonNumericValue {
14804 value: other.to_string(),
14805 dtype: self.dtype,
14806 }));
14807 }
14808 };
14809
14810 if let Some(data) = self.as_i64_slice() {
14816 if let Some((min, range)) = i64_direct_address_range(data) {
14819 return Ok(Self::from_bool_values(duplicated_flags_i64_direct(
14820 data, min, range, policy,
14821 )));
14822 }
14823 return Ok(Self::from_bool_values(duplicated_flags_typed(data, policy)));
14824 }
14825 if let Some(data) = self.as_f64_slice() {
14826 let keys: Vec<u64> = data
14827 .iter()
14828 .map(|&f| (if f == 0.0 { 0.0 } else { f }).to_bits())
14829 .collect();
14830 return Ok(Self::from_bool_values(duplicated_flags_typed(
14831 &keys, policy,
14832 )));
14833 }
14834
14835 let mut flags = vec![false; self.values.len()];
14836 match policy {
14837 DupPolicy::First => {
14838 let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
14839 for (idx, value) in self.values.iter().enumerate() {
14840 flags[idx] = !seen.insert(key_of(value));
14841 }
14842 }
14843 DupPolicy::Last => {
14844 let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
14845 for (idx, value) in self.values.iter().enumerate().rev() {
14846 flags[idx] = !seen.insert(key_of(value));
14847 }
14848 }
14849 DupPolicy::None => {
14850 let mut seen_once: FxHashSet<Key<'_>> = FxHashSet::default();
14851 let mut seen_multiple: FxHashSet<Key<'_>> = FxHashSet::default();
14852 for value in &self.values {
14853 let key = key_of(value);
14854 if !seen_once.insert(key_of(value)) {
14855 seen_multiple.insert(key);
14856 }
14857 }
14858 for (idx, value) in self.values.iter().enumerate() {
14859 flags[idx] = seen_multiple.contains(&key_of(value));
14860 }
14861 }
14862 }
14863
14864 let out: Vec<Scalar> = flags.into_iter().map(Scalar::Bool).collect();
14865 Self::new(DType::Bool, out)
14866 }
14867
14868 pub fn between(&self, lower: f64, upper: f64, inclusive: bool) -> Result<Self, ColumnError> {
14875 let policy = if inclusive { "both" } else { "neither" };
14876 self.between_inclusive(lower, upper, policy)
14877 }
14878
14879 pub fn between_inclusive(
14885 &self,
14886 lower: f64,
14887 upper: f64,
14888 inclusive: &str,
14889 ) -> Result<Self, ColumnError> {
14890 let (include_left, include_right) = match inclusive {
14891 "both" => (true, true),
14892 "left" => (true, false),
14893 "right" => (false, true),
14894 "neither" => (false, false),
14895 other => {
14896 return Err(ColumnError::Type(TypeError::NonNumericValue {
14897 value: other.to_string(),
14898 dtype: self.dtype,
14899 }));
14900 }
14901 };
14902
14903 let mut out = Vec::with_capacity(self.values.len());
14904 for v in &self.values {
14905 if v.is_missing() {
14906 out.push(Scalar::Bool(false));
14907 continue;
14908 }
14909 match v.to_f64() {
14910 Ok(x) => {
14911 let lower_ok = if include_left { x >= lower } else { x > lower };
14912 let upper_ok = if include_right { x <= upper } else { x < upper };
14913 out.push(Scalar::Bool(lower_ok && upper_ok));
14914 }
14915 Err(err) => return Err(ColumnError::Type(err)),
14916 }
14917 }
14918 Self::new(DType::Bool, out)
14919 }
14920
14921 pub fn factorize(&self) -> Result<(Self, Self), ColumnError> {
14926 self.factorize_with_options(false, true)
14927 }
14928
14929 pub fn factorize_with_options(
14936 &self,
14937 sort: bool,
14938 use_na_sentinel: bool,
14939 ) -> Result<(Self, Self), ColumnError> {
14940 if !sort
14941 && use_na_sentinel
14942 && let Some(cached) = self.utf8_default_factorize_columns()
14943 {
14944 return Ok(cached);
14945 }
14946
14947 #[derive(Hash, PartialEq, Eq, Clone, Copy)]
14955 enum LocalKey<'a> {
14956 Bool(bool),
14957 Int64(i64),
14958 FloatBits(u64),
14959 Utf8(&'a str),
14960 Timedelta64(i64),
14961 Datetime64(i64),
14962 Period(i64),
14963 Interval(u64, u64, IntervalClosed),
14964 }
14965 fn key_of(s: &Scalar) -> Option<LocalKey<'_>> {
14966 match s {
14967 Scalar::Null(_) => None,
14968 Scalar::Bool(b) => Some(LocalKey::Bool(*b)),
14969 Scalar::Int64(i) => Some(LocalKey::Int64(*i)),
14970 Scalar::Float64(f) => {
14971 if f.is_nan() {
14972 None
14973 } else {
14974 let normalized = if *f == 0.0 { 0.0 } else { *f };
14975 Some(LocalKey::FloatBits(normalized.to_bits()))
14976 }
14977 }
14978 Scalar::Utf8(s) => Some(LocalKey::Utf8(s.as_str())),
14979 Scalar::Timedelta64(t) => {
14980 if *t == Timedelta::NAT {
14981 None
14982 } else {
14983 Some(LocalKey::Timedelta64(*t))
14984 }
14985 }
14986 Scalar::Datetime64(t) => {
14987 if *t == Timestamp::NAT {
14988 None
14989 } else {
14990 Some(LocalKey::Datetime64(*t))
14991 }
14992 }
14993 Scalar::Period(p) => {
14994 if p.ordinal == i64::MIN {
14995 None
14996 } else {
14997 Some(LocalKey::Period(p.ordinal))
14998 }
14999 }
15000 Scalar::Interval(interval) => {
15001 let (left, right, closed) = interval_key(interval);
15002 Some(LocalKey::Interval(left, right, closed))
15003 }
15004 }
15005 }
15006
15007 let (mut codes, mut uniques): (Vec<Scalar>, Vec<Scalar>) = if let Some((data, min, range)) =
15008 self.as_i64_slice()
15009 .and_then(|d| i64_direct_address_range(d).map(|(m, r)| (d, m, r)))
15010 {
15011 let mut code_table = vec![-1i64; range];
15017 let mut uniques: Vec<Scalar> = Vec::new();
15018 let mut codes: Vec<Scalar> = Vec::with_capacity(data.len());
15019 for &v in data {
15020 let slot = (v as i128 - min as i128) as usize;
15021 let existing = code_table[slot];
15022 if existing < 0 {
15023 let code = uniques.len() as i64;
15024 code_table[slot] = code;
15025 uniques.push(Scalar::Int64(v));
15026 codes.push(Scalar::Int64(code));
15027 } else {
15028 codes.push(Scalar::Int64(existing));
15029 }
15030 }
15031 (codes, uniques)
15032 } else {
15033 let mut uniques: Vec<Scalar> = Vec::new();
15034 let mut idx_map: FxHashMap<LocalKey<'_>, i64> = FxHashMap::default();
15035 let mut missing_position: Option<i64> = None;
15036 let mut codes: Vec<Scalar> = Vec::with_capacity(self.values.len());
15037
15038 for value in &self.values {
15039 if value.is_missing() {
15040 if use_na_sentinel {
15041 codes.push(Scalar::Int64(-1));
15042 } else if let Some(p) = missing_position {
15043 codes.push(Scalar::Int64(p));
15044 } else {
15045 let code = uniques.len() as i64;
15046 missing_position = Some(code);
15047 uniques.push(value.clone());
15048 codes.push(Scalar::Int64(code));
15049 }
15050 continue;
15051 }
15052 let Some(key) = key_of(value) else {
15053 codes.push(Scalar::Int64(-1));
15056 continue;
15057 };
15058 match idx_map.get(&key) {
15059 Some(&p) => codes.push(Scalar::Int64(p)),
15060 None => {
15061 let code = uniques.len() as i64;
15062 idx_map.insert(key, code);
15063 uniques.push(value.clone());
15064 codes.push(Scalar::Int64(code));
15065 }
15066 }
15067 }
15068 drop(idx_map);
15069 (codes, uniques)
15070 };
15071
15072 if sort && !uniques.is_empty() {
15073 let mut ordering: Vec<usize> = (0..uniques.len()).collect();
15074 ordering.sort_by(|left, right| {
15075 compare_scalars_na_last(&uniques[*left], &uniques[*right], true)
15076 });
15077
15078 let mut remap = vec![0usize; uniques.len()];
15079 let sorted_uniques: Vec<Scalar> = ordering
15080 .into_iter()
15081 .enumerate()
15082 .map(|(sorted_position, original_position)| {
15083 remap[original_position] = sorted_position;
15084 uniques[original_position].clone()
15085 })
15086 .collect();
15087
15088 for code in &mut codes {
15089 if let Scalar::Int64(value) = code
15090 && *value >= 0
15091 {
15092 *value = remap[*value as usize] as i64;
15093 }
15094 }
15095
15096 uniques = sorted_uniques;
15097 }
15098
15099 let codes_col = Self::new(DType::Int64, codes)?;
15100 let uniques_col = Self::new(self.dtype, uniques)?;
15101 Ok((codes_col, uniques_col))
15102 }
15103
15104 pub fn abs(&self) -> Result<Self, ColumnError> {
15110 if let Some(data) = self.as_i64_slice() {
15116 return Ok(Self::from_i64_values(
15117 data.iter().map(|&x| x.wrapping_abs()).collect(),
15118 ));
15119 }
15120 if let Some(data) = self.as_f64_slice() {
15121 let witness = self.f64_finite_witness();
15132 let out: Vec<f64> = data.iter().map(|&x| x.abs()).collect();
15133 return Ok(Self::from_f64_all_valid_with_finite_opt(out, witness));
15134 }
15135
15136 let mut out = Vec::with_capacity(self.values.len());
15137 for v in &self.values {
15138 if v.is_missing() {
15139 out.push(v.clone());
15140 continue;
15141 }
15142 match v {
15143 Scalar::Bool(x) => out.push(Scalar::Bool(*x)),
15144 Scalar::Int64(x) => out.push(Scalar::Int64(x.wrapping_abs())),
15145 Scalar::Float64(x) => out.push(Scalar::Float64(x.abs())),
15146 Scalar::Timedelta64(x) if *x != Timedelta::NAT => {
15147 out.push(Scalar::Timedelta64(x.wrapping_abs()))
15148 }
15149 _ => {
15150 return Err(ColumnError::Type(TypeError::NonNumericValue {
15151 value: format!("{v:?}"),
15152 dtype: self.dtype,
15153 }));
15154 }
15155 }
15156 }
15157 Self::new(self.dtype, out)
15158 }
15159
15160 pub fn fabs(&self) -> Result<Self, ColumnError> {
15162 self.abs()
15163 }
15164
15165 pub fn absolute(&self) -> Result<Self, ColumnError> {
15167 self.abs()
15168 }
15169
15170 pub fn neg(&self) -> Result<Self, ColumnError> {
15172 if let Some(data) = self.as_i64_slice() {
15176 return Ok(Self::from_i64_values(
15177 data.iter().map(|&x| x.wrapping_neg()).collect(),
15178 ));
15179 }
15180 if let Some(data) = self.as_f64_slice() {
15181 let witness = self.f64_finite_witness();
15186 let out: Vec<f64> = data.iter().map(|&x| -x).collect();
15187 return Ok(Self::from_f64_all_valid_with_finite_opt(out, witness));
15188 }
15189 let mut out = Vec::with_capacity(self.values.len());
15190 for v in &self.values {
15191 if v.is_missing() {
15192 out.push(v.clone());
15193 continue;
15194 }
15195 match v {
15196 Scalar::Int64(x) => out.push(Scalar::Int64(x.wrapping_neg())),
15197 Scalar::Float64(x) => out.push(Scalar::Float64(-x)),
15198 Scalar::Timedelta64(x) if *x != Timedelta::NAT => {
15199 out.push(Scalar::Timedelta64(x.wrapping_neg()))
15200 }
15201 _ => {
15202 return Err(ColumnError::Type(TypeError::NonNumericValue {
15203 value: format!("{v:?}"),
15204 dtype: self.dtype,
15205 }));
15206 }
15207 }
15208 }
15209 Self::new(self.dtype, out)
15210 }
15211
15212 pub fn positive(&self) -> Result<Self, ColumnError> {
15214 for v in &self.values {
15215 if v.is_missing() {
15216 continue;
15217 }
15218 match v {
15219 Scalar::Int64(_) | Scalar::Float64(_) | Scalar::Timedelta64(_) => {}
15220 _ => {
15221 return Err(ColumnError::Type(TypeError::NonNumericValue {
15222 value: format!("{v:?}"),
15223 dtype: self.dtype,
15224 }));
15225 }
15226 }
15227 }
15228 Ok(self.clone())
15229 }
15230
15231 pub fn negative(&self) -> Result<Self, ColumnError> {
15233 self.neg()
15234 }
15235
15236 pub fn sqrt(&self) -> Result<Self, ColumnError> {
15238 if let Some(out) = self.typed_float_unary(f64::sqrt) {
15239 return Ok(out);
15240 }
15241 let mut out = Vec::with_capacity(self.values.len());
15242 for v in &self.values {
15243 if v.is_missing() {
15244 out.push(Scalar::Float64(f64::NAN));
15245 continue;
15246 }
15247 match v {
15248 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).sqrt())),
15249 Scalar::Float64(x) => out.push(Scalar::Float64(x.sqrt())),
15250 _ => {
15251 return Err(ColumnError::Type(TypeError::NonNumericValue {
15252 value: format!("{v:?}"),
15253 dtype: self.dtype,
15254 }));
15255 }
15256 }
15257 }
15258 Self::new(DType::Float64, out)
15259 }
15260
15261 pub fn exp(&self) -> Result<Self, ColumnError> {
15263 if let Some(out) = self.typed_float_unary(f64::exp) {
15264 return Ok(out);
15265 }
15266 let mut out = Vec::with_capacity(self.values.len());
15267 for v in &self.values {
15268 if v.is_missing() {
15269 out.push(Scalar::Float64(f64::NAN));
15270 continue;
15271 }
15272 match v {
15273 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).exp())),
15274 Scalar::Float64(x) => out.push(Scalar::Float64(x.exp())),
15275 _ => {
15276 return Err(ColumnError::Type(TypeError::NonNumericValue {
15277 value: format!("{v:?}"),
15278 dtype: self.dtype,
15279 }));
15280 }
15281 }
15282 }
15283 Self::new(DType::Float64, out)
15284 }
15285
15286 pub fn log(&self) -> Result<Self, ColumnError> {
15288 if let Some(out) = self.typed_float_unary(f64::ln) {
15289 return Ok(out);
15290 }
15291 let mut out = Vec::with_capacity(self.values.len());
15292 for v in &self.values {
15293 if v.is_missing() {
15294 out.push(Scalar::Float64(f64::NAN));
15295 continue;
15296 }
15297 match v {
15298 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).ln())),
15299 Scalar::Float64(x) => out.push(Scalar::Float64(x.ln())),
15300 _ => {
15301 return Err(ColumnError::Type(TypeError::NonNumericValue {
15302 value: format!("{v:?}"),
15303 dtype: self.dtype,
15304 }));
15305 }
15306 }
15307 }
15308 Self::new(DType::Float64, out)
15309 }
15310
15311 pub fn log10(&self) -> Result<Self, ColumnError> {
15313 if let Some(out) = self.typed_float_unary(f64::log10) {
15314 return Ok(out);
15315 }
15316 let mut out = Vec::with_capacity(self.values.len());
15317 for v in &self.values {
15318 if v.is_missing() {
15319 out.push(Scalar::Float64(f64::NAN));
15320 continue;
15321 }
15322 match v {
15323 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).log10())),
15324 Scalar::Float64(x) => out.push(Scalar::Float64(x.log10())),
15325 _ => {
15326 return Err(ColumnError::Type(TypeError::NonNumericValue {
15327 value: format!("{v:?}"),
15328 dtype: self.dtype,
15329 }));
15330 }
15331 }
15332 }
15333 Self::new(DType::Float64, out)
15334 }
15335
15336 pub fn log2(&self) -> Result<Self, ColumnError> {
15338 if let Some(out) = self.typed_float_unary(f64::log2) {
15339 return Ok(out);
15340 }
15341 let mut out = Vec::with_capacity(self.values.len());
15342 for v in &self.values {
15343 if v.is_missing() {
15344 out.push(Scalar::Float64(f64::NAN));
15345 continue;
15346 }
15347 match v {
15348 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).log2())),
15349 Scalar::Float64(x) => out.push(Scalar::Float64(x.log2())),
15350 _ => {
15351 return Err(ColumnError::Type(TypeError::NonNumericValue {
15352 value: format!("{v:?}"),
15353 dtype: self.dtype,
15354 }));
15355 }
15356 }
15357 }
15358 Self::new(DType::Float64, out)
15359 }
15360
15361 pub fn sin(&self) -> Result<Self, ColumnError> {
15363 if let Some(out) = self.typed_float_unary(f64::sin) {
15364 return Ok(out);
15365 }
15366 let mut out = Vec::with_capacity(self.values.len());
15367 for v in &self.values {
15368 if v.is_missing() {
15369 out.push(Scalar::Float64(f64::NAN));
15370 continue;
15371 }
15372 match v {
15373 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).sin())),
15374 Scalar::Float64(x) => out.push(Scalar::Float64(x.sin())),
15375 _ => {
15376 return Err(ColumnError::Type(TypeError::NonNumericValue {
15377 value: format!("{v:?}"),
15378 dtype: self.dtype,
15379 }));
15380 }
15381 }
15382 }
15383 Self::new(DType::Float64, out)
15384 }
15385
15386 pub fn cos(&self) -> Result<Self, ColumnError> {
15388 if let Some(out) = self.typed_float_unary(f64::cos) {
15389 return Ok(out);
15390 }
15391 let mut out = Vec::with_capacity(self.values.len());
15392 for v in &self.values {
15393 if v.is_missing() {
15394 out.push(Scalar::Float64(f64::NAN));
15395 continue;
15396 }
15397 match v {
15398 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).cos())),
15399 Scalar::Float64(x) => out.push(Scalar::Float64(x.cos())),
15400 _ => {
15401 return Err(ColumnError::Type(TypeError::NonNumericValue {
15402 value: format!("{v:?}"),
15403 dtype: self.dtype,
15404 }));
15405 }
15406 }
15407 }
15408 Self::new(DType::Float64, out)
15409 }
15410
15411 pub fn tan(&self) -> Result<Self, ColumnError> {
15413 if let Some(out) = self.typed_float_unary(f64::tan) {
15414 return Ok(out);
15415 }
15416 let mut out = Vec::with_capacity(self.values.len());
15417 for v in &self.values {
15418 if v.is_missing() {
15419 out.push(Scalar::Float64(f64::NAN));
15420 continue;
15421 }
15422 match v {
15423 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).tan())),
15424 Scalar::Float64(x) => out.push(Scalar::Float64(x.tan())),
15425 _ => {
15426 return Err(ColumnError::Type(TypeError::NonNumericValue {
15427 value: format!("{v:?}"),
15428 dtype: self.dtype,
15429 }));
15430 }
15431 }
15432 }
15433 Self::new(DType::Float64, out)
15434 }
15435
15436 pub fn asin(&self) -> Result<Self, ColumnError> {
15438 if let Some(out) = self.typed_float_unary(f64::asin) {
15439 return Ok(out);
15440 }
15441 let mut out = Vec::with_capacity(self.values.len());
15442 for v in &self.values {
15443 if v.is_missing() {
15444 out.push(Scalar::Float64(f64::NAN));
15445 continue;
15446 }
15447 match v {
15448 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).asin())),
15449 Scalar::Float64(x) => out.push(Scalar::Float64(x.asin())),
15450 _ => {
15451 return Err(ColumnError::Type(TypeError::NonNumericValue {
15452 value: format!("{v:?}"),
15453 dtype: self.dtype,
15454 }));
15455 }
15456 }
15457 }
15458 Self::new(DType::Float64, out)
15459 }
15460
15461 pub fn acos(&self) -> Result<Self, ColumnError> {
15463 if let Some(out) = self.typed_float_unary(f64::acos) {
15464 return Ok(out);
15465 }
15466 let mut out = Vec::with_capacity(self.values.len());
15467 for v in &self.values {
15468 if v.is_missing() {
15469 out.push(Scalar::Float64(f64::NAN));
15470 continue;
15471 }
15472 match v {
15473 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).acos())),
15474 Scalar::Float64(x) => out.push(Scalar::Float64(x.acos())),
15475 _ => {
15476 return Err(ColumnError::Type(TypeError::NonNumericValue {
15477 value: format!("{v:?}"),
15478 dtype: self.dtype,
15479 }));
15480 }
15481 }
15482 }
15483 Self::new(DType::Float64, out)
15484 }
15485
15486 pub fn atan(&self) -> Result<Self, ColumnError> {
15488 if let Some(out) = self.typed_float_unary(f64::atan) {
15489 return Ok(out);
15490 }
15491 let mut out = Vec::with_capacity(self.values.len());
15492 for v in &self.values {
15493 if v.is_missing() {
15494 out.push(Scalar::Float64(f64::NAN));
15495 continue;
15496 }
15497 match v {
15498 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).atan())),
15499 Scalar::Float64(x) => out.push(Scalar::Float64(x.atan())),
15500 _ => {
15501 return Err(ColumnError::Type(TypeError::NonNumericValue {
15502 value: format!("{v:?}"),
15503 dtype: self.dtype,
15504 }));
15505 }
15506 }
15507 }
15508 Self::new(DType::Float64, out)
15509 }
15510
15511 pub fn sinh(&self) -> Result<Self, ColumnError> {
15513 if let Some(out) = self.typed_float_unary(f64::sinh) {
15514 return Ok(out);
15515 }
15516 let mut out = Vec::with_capacity(self.values.len());
15517 for v in &self.values {
15518 if v.is_missing() {
15519 out.push(Scalar::Float64(f64::NAN));
15520 continue;
15521 }
15522 match v {
15523 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).sinh())),
15524 Scalar::Float64(x) => out.push(Scalar::Float64(x.sinh())),
15525 _ => {
15526 return Err(ColumnError::Type(TypeError::NonNumericValue {
15527 value: format!("{v:?}"),
15528 dtype: self.dtype,
15529 }));
15530 }
15531 }
15532 }
15533 Self::new(DType::Float64, out)
15534 }
15535
15536 pub fn cosh(&self) -> Result<Self, ColumnError> {
15538 if let Some(out) = self.typed_float_unary(f64::cosh) {
15539 return Ok(out);
15540 }
15541 let mut out = Vec::with_capacity(self.values.len());
15542 for v in &self.values {
15543 if v.is_missing() {
15544 out.push(Scalar::Float64(f64::NAN));
15545 continue;
15546 }
15547 match v {
15548 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).cosh())),
15549 Scalar::Float64(x) => out.push(Scalar::Float64(x.cosh())),
15550 _ => {
15551 return Err(ColumnError::Type(TypeError::NonNumericValue {
15552 value: format!("{v:?}"),
15553 dtype: self.dtype,
15554 }));
15555 }
15556 }
15557 }
15558 Self::new(DType::Float64, out)
15559 }
15560
15561 pub fn tanh(&self) -> Result<Self, ColumnError> {
15563 if let Some(out) = self.typed_float_unary(f64::tanh) {
15564 return Ok(out);
15565 }
15566 let mut out = Vec::with_capacity(self.values.len());
15567 for v in &self.values {
15568 if v.is_missing() {
15569 out.push(Scalar::Float64(f64::NAN));
15570 continue;
15571 }
15572 match v {
15573 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).tanh())),
15574 Scalar::Float64(x) => out.push(Scalar::Float64(x.tanh())),
15575 _ => {
15576 return Err(ColumnError::Type(TypeError::NonNumericValue {
15577 value: format!("{v:?}"),
15578 dtype: self.dtype,
15579 }));
15580 }
15581 }
15582 }
15583 Self::new(DType::Float64, out)
15584 }
15585
15586 pub fn asinh(&self) -> Result<Self, ColumnError> {
15588 if let Some(out) = self.typed_float_unary(f64::asinh) {
15589 return Ok(out);
15590 }
15591 let mut out = Vec::with_capacity(self.values.len());
15592 for v in &self.values {
15593 if v.is_missing() {
15594 out.push(Scalar::Float64(f64::NAN));
15595 continue;
15596 }
15597 match v {
15598 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).asinh())),
15599 Scalar::Float64(x) => out.push(Scalar::Float64(x.asinh())),
15600 _ => {
15601 return Err(ColumnError::Type(TypeError::NonNumericValue {
15602 value: format!("{v:?}"),
15603 dtype: self.dtype,
15604 }));
15605 }
15606 }
15607 }
15608 Self::new(DType::Float64, out)
15609 }
15610
15611 pub fn acosh(&self) -> Result<Self, ColumnError> {
15613 if let Some(out) = self.typed_float_unary(f64::acosh) {
15614 return Ok(out);
15615 }
15616 let mut out = Vec::with_capacity(self.values.len());
15617 for v in &self.values {
15618 if v.is_missing() {
15619 out.push(Scalar::Float64(f64::NAN));
15620 continue;
15621 }
15622 match v {
15623 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).acosh())),
15624 Scalar::Float64(x) => out.push(Scalar::Float64(x.acosh())),
15625 _ => {
15626 return Err(ColumnError::Type(TypeError::NonNumericValue {
15627 value: format!("{v:?}"),
15628 dtype: self.dtype,
15629 }));
15630 }
15631 }
15632 }
15633 Self::new(DType::Float64, out)
15634 }
15635
15636 pub fn atanh(&self) -> Result<Self, ColumnError> {
15638 if let Some(out) = self.typed_float_unary(f64::atanh) {
15639 return Ok(out);
15640 }
15641 let mut out = Vec::with_capacity(self.values.len());
15642 for v in &self.values {
15643 if v.is_missing() {
15644 out.push(Scalar::Float64(f64::NAN));
15645 continue;
15646 }
15647 match v {
15648 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).atanh())),
15649 Scalar::Float64(x) => out.push(Scalar::Float64(x.atanh())),
15650 _ => {
15651 return Err(ColumnError::Type(TypeError::NonNumericValue {
15652 value: format!("{v:?}"),
15653 dtype: self.dtype,
15654 }));
15655 }
15656 }
15657 }
15658 Self::new(DType::Float64, out)
15659 }
15660
15661 pub fn arcsin(&self) -> Result<Self, ColumnError> {
15665 self.asin()
15666 }
15667
15668 pub fn arccos(&self) -> Result<Self, ColumnError> {
15672 self.acos()
15673 }
15674
15675 pub fn arctan(&self) -> Result<Self, ColumnError> {
15679 self.atan()
15680 }
15681
15682 pub fn arctan2(&self, other: &Self) -> Result<Self, ColumnError> {
15686 self.atan2(other)
15687 }
15688
15689 pub fn arcsinh(&self) -> Result<Self, ColumnError> {
15693 self.asinh()
15694 }
15695
15696 pub fn arccosh(&self) -> Result<Self, ColumnError> {
15700 self.acosh()
15701 }
15702
15703 pub fn arctanh(&self) -> Result<Self, ColumnError> {
15707 self.atanh()
15708 }
15709
15710 fn typed_float_unary(&self, f: fn(f64) -> f64) -> Option<Self> {
15721 if let Some(data) = self.as_f64_slice() {
15722 return Some(Self::from_f64_values(data.iter().map(|&x| f(x)).collect()));
15723 }
15724 if let Some(data) = self.as_i64_slice() {
15725 return Some(Self::from_f64_values(
15726 data.iter().map(|&x| f(x as f64)).collect(),
15727 ));
15728 }
15729 None
15730 }
15731
15732 fn typed_float_unary_finite_preserving<F: Fn(f64) -> f64>(&self, f: F) -> Option<Self> {
15744 if let Some(data) = self.as_f64_slice() {
15745 let witness = self.f64_finite_witness();
15746 let out: Vec<f64> = data.iter().map(|&x| f(x)).collect();
15747 return Some(Self::from_f64_all_valid_with_finite_opt(out, witness));
15748 }
15749 if let Some(data) = self.as_i64_slice() {
15750 let out: Vec<f64> = data.iter().map(|&x| f(x as f64)).collect();
15751 return Some(Self::from_f64_all_valid_with_finite_opt(out, Some(true)));
15753 }
15754 None
15755 }
15756
15757 fn all_valid_as_f64(&self) -> Option<Vec<f64>> {
15761 if let Some(s) = self.as_f64_slice() {
15762 return Some(s.to_vec());
15763 }
15764 if let Some(s) = self.as_i64_slice() {
15765 return Some(s.iter().map(|&x| x as f64).collect());
15766 }
15767 None
15768 }
15769
15770 fn typed_float_binary(&self, other: &Self, f: fn(f64, f64) -> f64) -> Option<Self> {
15778 let a = self.all_valid_as_f64()?;
15779 let b = other.all_valid_as_f64()?;
15780 Some(Self::from_f64_values(
15781 a.iter().zip(b.iter()).map(|(&x, &y)| f(x, y)).collect(),
15782 ))
15783 }
15784
15785 pub fn floor(&self) -> Result<Self, ColumnError> {
15786 if let Some(out) = self.typed_float_unary_finite_preserving(f64::floor) {
15787 return Ok(out);
15788 }
15789 let mut out = Vec::with_capacity(self.values.len());
15790 for v in &self.values {
15791 if v.is_missing() {
15792 out.push(Scalar::Float64(f64::NAN));
15793 continue;
15794 }
15795 match v {
15796 Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
15797 Scalar::Float64(x) => out.push(Scalar::Float64(x.floor())),
15798 _ => {
15799 return Err(ColumnError::Type(TypeError::NonNumericValue {
15800 value: format!("{v:?}"),
15801 dtype: self.dtype,
15802 }));
15803 }
15804 }
15805 }
15806 Self::new(DType::Float64, out)
15807 }
15808
15809 pub fn ceil(&self) -> Result<Self, ColumnError> {
15811 if let Some(out) = self.typed_float_unary_finite_preserving(f64::ceil) {
15812 return Ok(out);
15813 }
15814 let mut out = Vec::with_capacity(self.values.len());
15815 for v in &self.values {
15816 if v.is_missing() {
15817 out.push(Scalar::Float64(f64::NAN));
15818 continue;
15819 }
15820 match v {
15821 Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
15822 Scalar::Float64(x) => out.push(Scalar::Float64(x.ceil())),
15823 _ => {
15824 return Err(ColumnError::Type(TypeError::NonNumericValue {
15825 value: format!("{v:?}"),
15826 dtype: self.dtype,
15827 }));
15828 }
15829 }
15830 }
15831 Self::new(DType::Float64, out)
15832 }
15833
15834 pub fn trunc(&self) -> Result<Self, ColumnError> {
15836 if let Some(out) = self.typed_float_unary_finite_preserving(f64::trunc) {
15837 return Ok(out);
15838 }
15839 let mut out = Vec::with_capacity(self.values.len());
15840 for v in &self.values {
15841 if v.is_missing() {
15842 out.push(Scalar::Float64(f64::NAN));
15843 continue;
15844 }
15845 match v {
15846 Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
15847 Scalar::Float64(x) => out.push(Scalar::Float64(x.trunc())),
15848 _ => {
15849 return Err(ColumnError::Type(TypeError::NonNumericValue {
15850 value: format!("{v:?}"),
15851 dtype: self.dtype,
15852 }));
15853 }
15854 }
15855 }
15856 Self::new(DType::Float64, out)
15857 }
15858
15859 pub fn nan_to_num(&self) -> Result<Self, ColumnError> {
15864 self.nan_to_num_with_values(0.0, f64::MAX, f64::MIN)
15865 }
15866
15867 pub fn nan_to_num_with_values(
15871 &self,
15872 nan: f64,
15873 posinf: f64,
15874 neginf: f64,
15875 ) -> Result<Self, ColumnError> {
15876 if let Some(data) = self.as_f64_slice() {
15882 return Ok(Self::from_f64_values(
15883 data.iter()
15884 .map(|&x| {
15885 if x == f64::INFINITY {
15886 posinf
15887 } else if x == f64::NEG_INFINITY {
15888 neginf
15889 } else {
15890 x
15891 }
15892 })
15893 .collect(),
15894 ));
15895 }
15896 if let Some(data) = self.as_i64_slice() {
15897 return Ok(Self::from_f64_values(
15898 data.iter().map(|&x| x as f64).collect(),
15899 ));
15900 }
15901 let mut out = Vec::with_capacity(self.values.len());
15902 for v in &self.values {
15903 let result = match v {
15904 Scalar::Float64(x) => {
15905 if x.is_nan() {
15906 nan
15907 } else if *x == f64::INFINITY {
15908 posinf
15909 } else if *x == f64::NEG_INFINITY {
15910 neginf
15911 } else {
15912 *x
15913 }
15914 }
15915 Scalar::Int64(x) => *x as f64,
15916 Scalar::Null(_) => nan,
15917 _ => {
15918 return Err(ColumnError::Type(TypeError::NonNumericValue {
15919 value: format!("{v:?}"),
15920 dtype: self.dtype,
15921 }));
15922 }
15923 };
15924 out.push(Scalar::Float64(result));
15925 }
15926 Self::new(DType::Float64, out)
15927 }
15928
15929 pub fn rint(&self) -> Result<Self, ColumnError> {
15934 if let Some(out) = self.typed_float_unary(f64::round_ties_even) {
15937 return Ok(out);
15938 }
15939 let mut out = Vec::with_capacity(self.values.len());
15940 for v in &self.values {
15941 if v.is_missing() {
15942 out.push(Scalar::Float64(f64::NAN));
15943 continue;
15944 }
15945 match v {
15946 Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64)),
15947 Scalar::Float64(x) => out.push(Scalar::Float64(x.round_ties_even())),
15948 _ => {
15949 return Err(ColumnError::Type(TypeError::NonNumericValue {
15950 value: format!("{v:?}"),
15951 dtype: self.dtype,
15952 }));
15953 }
15954 }
15955 }
15956 Self::new(DType::Float64, out)
15957 }
15958
15959 pub fn fix(&self) -> Result<Self, ColumnError> {
15963 self.trunc()
15964 }
15965
15966 pub fn trim_zeros(&self, trim: &str) -> Result<Self, ColumnError> {
15973 let values = &self.values;
15974 if values.is_empty() {
15975 return Self::new(self.dtype, vec![]);
15976 }
15977
15978 let is_zero = |s: &Scalar| -> bool {
15979 match s {
15980 Scalar::Int64(x) => *x == 0,
15981 Scalar::Float64(x) => *x == 0.0,
15982 Scalar::Bool(b) => !*b,
15983 _ => false,
15984 }
15985 };
15986
15987 let mut start = 0;
15988 let mut end = values.len();
15989
15990 if trim.contains('f') {
15991 while start < end && is_zero(&values[start]) {
15992 start += 1;
15993 }
15994 }
15995
15996 if trim.contains('b') {
15997 while end > start && is_zero(&values[end - 1]) {
15998 end -= 1;
15999 }
16000 }
16001
16002 Self::new(self.dtype, values[start..end].to_vec())
16003 }
16004
16005 pub fn around(&self, decimals: i32) -> Result<Self, ColumnError> {
16010 let factor = 10.0_f64.powi(decimals);
16011 let mut out = Vec::with_capacity(self.values.len());
16012 for v in &self.values {
16013 if v.is_missing() {
16014 out.push(Scalar::Float64(f64::NAN));
16015 continue;
16016 }
16017 match v {
16018 Scalar::Int64(x) => {
16019 if decimals >= 0 {
16020 out.push(Scalar::Int64(*x));
16021 } else {
16022 let rounded = ((*x as f64) * factor).round_ties_even() / factor;
16025 out.push(Scalar::Int64(rounded as i64));
16026 }
16027 }
16028 Scalar::Float64(x) => {
16029 let rounded = (*x * factor).round_ties_even() / factor;
16030 out.push(Scalar::Float64(rounded));
16031 }
16032 _ => {
16033 return Err(ColumnError::Type(TypeError::NonNumericValue {
16034 value: format!("{v:?}"),
16035 dtype: self.dtype,
16036 }));
16037 }
16038 }
16039 }
16040 if decimals >= 0 && self.dtype == DType::Int64 {
16041 Self::new(DType::Int64, out)
16042 } else {
16043 Self::new(DType::Float64, out)
16044 }
16045 }
16046
16047 pub fn unwrap(&self, discont: Option<f64>) -> Result<Self, ColumnError> {
16053 let threshold = discont.unwrap_or(std::f64::consts::PI);
16054 let two_pi = 2.0 * std::f64::consts::PI;
16055
16056 let mut out = Vec::with_capacity(self.values.len());
16057 let mut offset = 0.0;
16058
16059 for (i, v) in self.values.iter().enumerate() {
16060 if v.is_missing() {
16061 out.push(Scalar::Float64(f64::NAN));
16062 continue;
16063 }
16064 let x = match v {
16065 Scalar::Int64(x) => *x as f64,
16066 Scalar::Float64(x) => *x,
16067 _ => {
16068 return Err(ColumnError::Type(TypeError::NonNumericValue {
16069 value: format!("{v:?}"),
16070 dtype: self.dtype,
16071 }));
16072 }
16073 };
16074
16075 if i == 0 {
16076 out.push(Scalar::Float64(x));
16077 } else {
16078 let prev = match &out[out.len() - 1] {
16079 Scalar::Float64(p) if !p.is_nan() => *p,
16080 _ => {
16081 out.push(Scalar::Float64(x + offset));
16082 continue;
16083 }
16084 };
16085
16086 let diff = x + offset - prev;
16087 if diff > threshold {
16088 offset -= two_pi * ((diff + std::f64::consts::PI) / two_pi).floor();
16089 } else if diff < -threshold {
16090 offset += two_pi * ((-diff + std::f64::consts::PI) / two_pi).floor();
16091 }
16092 out.push(Scalar::Float64(x + offset));
16093 }
16094 }
16095
16096 Self::new(DType::Float64, out)
16097 }
16098
16099 pub fn expm1(&self) -> Result<Self, ColumnError> {
16101 if let Some(out) = self.typed_float_unary(f64::exp_m1) {
16102 return Ok(out);
16103 }
16104 let mut out = Vec::with_capacity(self.values.len());
16105 for v in &self.values {
16106 if v.is_missing() {
16107 out.push(Scalar::Float64(f64::NAN));
16108 continue;
16109 }
16110 match v {
16111 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).exp_m1())),
16112 Scalar::Float64(x) => out.push(Scalar::Float64(x.exp_m1())),
16113 _ => {
16114 return Err(ColumnError::Type(TypeError::NonNumericValue {
16115 value: format!("{v:?}"),
16116 dtype: self.dtype,
16117 }));
16118 }
16119 }
16120 }
16121 Self::new(DType::Float64, out)
16122 }
16123
16124 pub fn log1p(&self) -> Result<Self, ColumnError> {
16126 if let Some(out) = self.typed_float_unary(f64::ln_1p) {
16127 return Ok(out);
16128 }
16129 let mut out = Vec::with_capacity(self.values.len());
16130 for v in &self.values {
16131 if v.is_missing() {
16132 out.push(Scalar::Float64(f64::NAN));
16133 continue;
16134 }
16135 match v {
16136 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).ln_1p())),
16137 Scalar::Float64(x) => out.push(Scalar::Float64(x.ln_1p())),
16138 _ => {
16139 return Err(ColumnError::Type(TypeError::NonNumericValue {
16140 value: format!("{v:?}"),
16141 dtype: self.dtype,
16142 }));
16143 }
16144 }
16145 }
16146 Self::new(DType::Float64, out)
16147 }
16148
16149 pub fn cbrt(&self) -> Result<Self, ColumnError> {
16151 if let Some(out) = self.typed_float_unary(f64::cbrt) {
16152 return Ok(out);
16153 }
16154 let mut out = Vec::with_capacity(self.values.len());
16155 for v in &self.values {
16156 if v.is_missing() {
16157 out.push(Scalar::Float64(f64::NAN));
16158 continue;
16159 }
16160 match v {
16161 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).cbrt())),
16162 Scalar::Float64(x) => out.push(Scalar::Float64(x.cbrt())),
16163 _ => {
16164 return Err(ColumnError::Type(TypeError::NonNumericValue {
16165 value: format!("{v:?}"),
16166 dtype: self.dtype,
16167 }));
16168 }
16169 }
16170 }
16171 Self::new(DType::Float64, out)
16172 }
16173
16174 pub fn ldexp(&self, exp: i32) -> Result<Self, ColumnError> {
16178 let multiplier = 2.0_f64.powi(exp);
16179 let mut out = Vec::with_capacity(self.values.len());
16180 for v in &self.values {
16181 if v.is_missing() {
16182 out.push(Scalar::Float64(f64::NAN));
16183 continue;
16184 }
16185 match v {
16186 Scalar::Int64(x) => out.push(Scalar::Float64(*x as f64 * multiplier)),
16187 Scalar::Float64(x) => out.push(Scalar::Float64(x * multiplier)),
16188 _ => {
16189 return Err(ColumnError::Type(TypeError::NonNumericValue {
16190 value: format!("{v:?}"),
16191 dtype: self.dtype,
16192 }));
16193 }
16194 }
16195 }
16196 Self::new(DType::Float64, out)
16197 }
16198
16199 pub fn modf(&self) -> Result<(Self, Self), ColumnError> {
16204 let mut frac = Vec::with_capacity(self.values.len());
16205 let mut int = Vec::with_capacity(self.values.len());
16206 for v in &self.values {
16207 if v.is_missing() {
16208 frac.push(Scalar::Float64(f64::NAN));
16209 int.push(Scalar::Float64(f64::NAN));
16210 continue;
16211 }
16212 match v {
16213 Scalar::Int64(x) => {
16214 frac.push(Scalar::Float64(0.0));
16215 int.push(Scalar::Float64(*x as f64));
16216 }
16217 Scalar::Float64(x) => {
16218 let i = x.trunc();
16219 let f = x - i;
16220 frac.push(Scalar::Float64(f));
16221 int.push(Scalar::Float64(i));
16222 }
16223 _ => {
16224 return Err(ColumnError::Type(TypeError::NonNumericValue {
16225 value: format!("{v:?}"),
16226 dtype: self.dtype,
16227 }));
16228 }
16229 }
16230 }
16231 Ok((
16232 Self::new(DType::Float64, frac)?,
16233 Self::new(DType::Float64, int)?,
16234 ))
16235 }
16236
16237 pub fn frexp(&self) -> Result<(Self, Self), ColumnError> {
16244 let mut mantissa = Vec::with_capacity(self.values.len());
16245 let mut exponent = Vec::with_capacity(self.values.len());
16246 for v in &self.values {
16247 if v.is_missing() {
16248 mantissa.push(Scalar::Float64(f64::NAN));
16249 exponent.push(Scalar::Int64(0));
16250 continue;
16251 }
16252 match v {
16253 Scalar::Int64(x) => {
16254 let f = *x as f64;
16255 if f == 0.0 {
16256 mantissa.push(Scalar::Float64(0.0));
16257 exponent.push(Scalar::Int64(0));
16258 } else {
16259 let bits = f.abs().to_bits();
16260 let exp_bits = ((bits >> 52) & 0x7ff) as i64;
16261 let exp = exp_bits - 1022; let mant_bits = (bits & 0x000f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000;
16263 let mant = f64::from_bits(mant_bits);
16264 let mant = if f < 0.0 { -mant } else { mant };
16265 mantissa.push(Scalar::Float64(mant));
16266 exponent.push(Scalar::Int64(exp));
16267 }
16268 }
16269 Scalar::Float64(x) => {
16270 if x.is_nan() {
16271 mantissa.push(Scalar::Float64(f64::NAN));
16272 exponent.push(Scalar::Int64(0));
16273 } else if x.is_infinite() {
16274 mantissa.push(Scalar::Float64(*x));
16275 exponent.push(Scalar::Int64(0));
16276 } else if *x == 0.0 {
16277 mantissa.push(Scalar::Float64(*x)); exponent.push(Scalar::Int64(0));
16279 } else {
16280 let bits = x.abs().to_bits();
16281 let exp_bits = ((bits >> 52) & 0x7ff) as i64;
16282 if exp_bits == 0 {
16283 let scaled = x.abs() * 2.0_f64.powi(64);
16285 let sbits = scaled.to_bits();
16286 let sexp_bits = ((sbits >> 52) & 0x7ff) as i64;
16287 let exp = sexp_bits - 1022 - 64;
16288 let mant_bits = (sbits & 0x000f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000;
16289 let mant = f64::from_bits(mant_bits);
16290 let mant = if *x < 0.0 { -mant } else { mant };
16291 mantissa.push(Scalar::Float64(mant));
16292 exponent.push(Scalar::Int64(exp));
16293 } else {
16294 let exp = exp_bits - 1022;
16295 let mant_bits = (bits & 0x000f_ffff_ffff_ffff) | 0x3fe0_0000_0000_0000;
16296 let mant = f64::from_bits(mant_bits);
16297 let mant = if *x < 0.0 { -mant } else { mant };
16298 mantissa.push(Scalar::Float64(mant));
16299 exponent.push(Scalar::Int64(exp));
16300 }
16301 }
16302 }
16303 _ => {
16304 return Err(ColumnError::Type(TypeError::NonNumericValue {
16305 value: format!("{v:?}"),
16306 dtype: self.dtype,
16307 }));
16308 }
16309 }
16310 }
16311 Ok((
16312 Self::new(DType::Float64, mantissa)?,
16313 Self::new(DType::Int64, exponent)?,
16314 ))
16315 }
16316
16317 pub fn nextafter(&self, other: &Self) -> Result<Self, ColumnError> {
16322 if self.len() != other.len() {
16323 return Err(ColumnError::LengthMismatch {
16324 left: self.len(),
16325 right: other.len(),
16326 });
16327 }
16328 let mut out = Vec::with_capacity(self.values.len());
16329 for (v1, v2) in self.values.iter().zip(other.values.iter()) {
16330 if v1.is_missing() || v2.is_missing() {
16331 out.push(Scalar::Float64(f64::NAN));
16332 continue;
16333 }
16334 let x = v1.to_f64().map_err(ColumnError::Type)?;
16335 let y = v2.to_f64().map_err(ColumnError::Type)?;
16336 let result = if x.is_nan() || y.is_nan() {
16337 f64::NAN
16338 } else if x == y {
16339 x
16340 } else if x == 0.0 {
16341 if y > 0.0 {
16343 f64::from_bits(1) } else {
16345 -f64::from_bits(1) }
16347 } else {
16348 let bits = x.to_bits() as i64;
16349 let next_bits = if (x > 0.0) == (y > x) {
16350 bits + 1
16351 } else {
16352 bits - 1
16353 };
16354 f64::from_bits(next_bits as u64)
16355 };
16356 out.push(Scalar::Float64(result));
16357 }
16358 Self::new(DType::Float64, out)
16359 }
16360
16361 pub fn isneginf(&self) -> Result<Self, ColumnError> {
16366 let mut out = Vec::with_capacity(self.values.len());
16367 for v in &self.values {
16368 if v.is_missing() {
16369 out.push(Scalar::Bool(false));
16370 continue;
16371 }
16372 match v {
16373 Scalar::Int64(_) => out.push(Scalar::Bool(false)),
16374 Scalar::Float64(x) => out.push(Scalar::Bool(*x == f64::NEG_INFINITY)),
16375 _ => out.push(Scalar::Bool(false)),
16376 }
16377 }
16378 Self::new(DType::Bool, out)
16379 }
16380
16381 pub fn isposinf(&self) -> Result<Self, ColumnError> {
16386 let mut out = Vec::with_capacity(self.values.len());
16387 for v in &self.values {
16388 if v.is_missing() {
16389 out.push(Scalar::Bool(false));
16390 continue;
16391 }
16392 match v {
16393 Scalar::Int64(_) => out.push(Scalar::Bool(false)),
16394 Scalar::Float64(x) => out.push(Scalar::Bool(*x == f64::INFINITY)),
16395 _ => out.push(Scalar::Bool(false)),
16396 }
16397 }
16398 Self::new(DType::Bool, out)
16399 }
16400
16401 pub fn exp2(&self) -> Result<Self, ColumnError> {
16405 if let Some(data) = self.as_f64_slice() {
16409 return Ok(Self::from_f64_values(
16410 data.iter().map(|&x| x.exp2()).collect(),
16411 ));
16412 }
16413 if let Some(data) = self.as_i64_slice() {
16414 return Ok(Self::from_f64_values(
16415 data.iter().map(|&x| 2.0_f64.powi(x as i32)).collect(),
16416 ));
16417 }
16418 let mut out = Vec::with_capacity(self.values.len());
16419 for v in &self.values {
16420 if v.is_missing() {
16421 out.push(Scalar::Float64(f64::NAN));
16422 continue;
16423 }
16424 match v {
16425 Scalar::Int64(x) => out.push(Scalar::Float64(2.0_f64.powi(*x as i32))),
16426 Scalar::Float64(x) => out.push(Scalar::Float64(x.exp2())),
16427 _ => {
16428 return Err(ColumnError::Type(TypeError::NonNumericValue {
16429 value: format!("{v:?}"),
16430 dtype: self.dtype,
16431 }));
16432 }
16433 }
16434 }
16435 Self::new(DType::Float64, out)
16436 }
16437
16438 pub fn sinc(&self) -> Result<Self, ColumnError> {
16442 if let Some(out) = self.typed_float_unary(|x| {
16445 if x == 0.0 {
16446 1.0
16447 } else {
16448 let px = std::f64::consts::PI * x;
16449 px.sin() / px
16450 }
16451 }) {
16452 return Ok(out);
16453 }
16454 let mut out = Vec::with_capacity(self.values.len());
16455 for v in &self.values {
16456 if v.is_missing() {
16457 out.push(Scalar::Float64(f64::NAN));
16458 continue;
16459 }
16460 match v {
16461 Scalar::Int64(x) => {
16462 if *x == 0 {
16463 out.push(Scalar::Float64(1.0));
16464 } else {
16465 let px = std::f64::consts::PI * (*x as f64);
16466 out.push(Scalar::Float64(px.sin() / px));
16467 }
16468 }
16469 Scalar::Float64(x) => {
16470 if *x == 0.0 {
16471 out.push(Scalar::Float64(1.0));
16472 } else if x.is_nan() {
16473 out.push(Scalar::Float64(f64::NAN));
16474 } else {
16475 let px = std::f64::consts::PI * x;
16476 out.push(Scalar::Float64(px.sin() / px));
16477 }
16478 }
16479 _ => {
16480 return Err(ColumnError::Type(TypeError::NonNumericValue {
16481 value: format!("{v:?}"),
16482 dtype: self.dtype,
16483 }));
16484 }
16485 }
16486 }
16487 Self::new(DType::Float64, out)
16488 }
16489
16490 pub fn logaddexp(&self, other: &Self) -> Result<Self, ColumnError> {
16495 if self.len() != other.len() {
16496 return Err(ColumnError::LengthMismatch {
16497 left: self.len(),
16498 right: other.len(),
16499 });
16500 }
16501 let mut out = Vec::with_capacity(self.values.len());
16502 for (v1, v2) in self.values.iter().zip(other.values.iter()) {
16503 if v1.is_missing() || v2.is_missing() {
16504 out.push(Scalar::Float64(f64::NAN));
16505 continue;
16506 }
16507 let x = v1.to_f64().map_err(ColumnError::Type)?;
16508 let y = v2.to_f64().map_err(ColumnError::Type)?;
16509 let result = if x.is_nan() || y.is_nan() {
16510 f64::NAN
16511 } else if x == f64::NEG_INFINITY {
16512 y
16513 } else if y == f64::NEG_INFINITY {
16514 x
16515 } else if x == f64::INFINITY || y == f64::INFINITY {
16516 f64::INFINITY
16517 } else if x >= y {
16518 x + (y - x).exp().ln_1p()
16519 } else {
16520 y + (x - y).exp().ln_1p()
16521 };
16522 out.push(Scalar::Float64(result));
16523 }
16524 Self::new(DType::Float64, out)
16525 }
16526
16527 pub fn logaddexp2(&self, other: &Self) -> Result<Self, ColumnError> {
16531 if self.len() != other.len() {
16532 return Err(ColumnError::LengthMismatch {
16533 left: self.len(),
16534 right: other.len(),
16535 });
16536 }
16537 let ln2 = std::f64::consts::LN_2;
16538 let mut out = Vec::with_capacity(self.values.len());
16539 for (v1, v2) in self.values.iter().zip(other.values.iter()) {
16540 if v1.is_missing() || v2.is_missing() {
16541 out.push(Scalar::Float64(f64::NAN));
16542 continue;
16543 }
16544 let x = v1.to_f64().map_err(ColumnError::Type)?;
16545 let y = v2.to_f64().map_err(ColumnError::Type)?;
16546 let result = if x.is_nan() || y.is_nan() {
16547 f64::NAN
16548 } else if x == f64::NEG_INFINITY {
16549 y
16550 } else if y == f64::NEG_INFINITY {
16551 x
16552 } else if x == f64::INFINITY || y == f64::INFINITY {
16553 f64::INFINITY
16554 } else if x >= y {
16555 x + ((y - x) * ln2).exp().ln_1p() / ln2
16556 } else {
16557 y + ((x - y) * ln2).exp().ln_1p() / ln2
16558 };
16559 out.push(Scalar::Float64(result));
16560 }
16561 Self::new(DType::Float64, out)
16562 }
16563
16564 pub fn spacing(&self) -> Result<Self, ColumnError> {
16569 let mut out = Vec::with_capacity(self.values.len());
16570 for v in &self.values {
16571 if v.is_missing() {
16572 out.push(Scalar::Float64(f64::NAN));
16573 continue;
16574 }
16575 match v {
16576 Scalar::Int64(x) => {
16577 let f = (*x as f64).abs();
16578 if f == 0.0 {
16579 out.push(Scalar::Float64(f64::from_bits(1)));
16580 } else {
16581 let bits = f.to_bits();
16582 let next = f64::from_bits(bits + 1);
16583 out.push(Scalar::Float64(next - f));
16584 }
16585 }
16586 Scalar::Float64(x) => {
16587 if x.is_nan() || x.is_infinite() {
16588 out.push(Scalar::Float64(f64::NAN));
16589 } else {
16590 let f = x.abs();
16591 if f == 0.0 {
16592 out.push(Scalar::Float64(f64::from_bits(1)));
16593 } else {
16594 let bits = f.to_bits();
16595 let next = f64::from_bits(bits + 1);
16596 out.push(Scalar::Float64(next - f));
16597 }
16598 }
16599 }
16600 _ => {
16601 return Err(ColumnError::Type(TypeError::NonNumericValue {
16602 value: format!("{v:?}"),
16603 dtype: self.dtype,
16604 }));
16605 }
16606 }
16607 }
16608 Self::new(DType::Float64, out)
16609 }
16610
16611 pub fn radians(&self) -> Result<Self, ColumnError> {
16613 if let Some(out) = self.typed_float_unary(f64::to_radians) {
16614 return Ok(out);
16615 }
16616 let mut out = Vec::with_capacity(self.values.len());
16617 for v in &self.values {
16618 if v.is_missing() {
16619 out.push(Scalar::Float64(f64::NAN));
16620 continue;
16621 }
16622 match v {
16623 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).to_radians())),
16624 Scalar::Float64(x) => out.push(Scalar::Float64(x.to_radians())),
16625 _ => {
16626 return Err(ColumnError::Type(TypeError::NonNumericValue {
16627 value: format!("{v:?}"),
16628 dtype: self.dtype,
16629 }));
16630 }
16631 }
16632 }
16633 Self::new(DType::Float64, out)
16634 }
16635
16636 pub fn deg2rad(&self) -> Result<Self, ColumnError> {
16638 self.radians()
16639 }
16640
16641 pub fn degrees(&self) -> Result<Self, ColumnError> {
16643 if let Some(out) = self.typed_float_unary(f64::to_degrees) {
16644 return Ok(out);
16645 }
16646 let mut out = Vec::with_capacity(self.values.len());
16647 for v in &self.values {
16648 if v.is_missing() {
16649 out.push(Scalar::Float64(f64::NAN));
16650 continue;
16651 }
16652 match v {
16653 Scalar::Int64(x) => out.push(Scalar::Float64((*x as f64).to_degrees())),
16654 Scalar::Float64(x) => out.push(Scalar::Float64(x.to_degrees())),
16655 _ => {
16656 return Err(ColumnError::Type(TypeError::NonNumericValue {
16657 value: format!("{v:?}"),
16658 dtype: self.dtype,
16659 }));
16660 }
16661 }
16662 }
16663 Self::new(DType::Float64, out)
16664 }
16665
16666 pub fn rad2deg(&self) -> Result<Self, ColumnError> {
16668 self.degrees()
16669 }
16670
16671 pub fn reciprocal(&self) -> Result<Self, ColumnError> {
16673 if let Some(out) = self.typed_float_unary(|x| 1.0 / x) {
16674 return Ok(out);
16675 }
16676 let mut out = Vec::with_capacity(self.values.len());
16677 for v in &self.values {
16678 if v.is_missing() {
16679 out.push(Scalar::Float64(f64::NAN));
16680 continue;
16681 }
16682 match v {
16683 Scalar::Int64(x) => out.push(Scalar::Float64(1.0 / (*x as f64))),
16684 Scalar::Float64(x) => out.push(Scalar::Float64(1.0 / x)),
16685 _ => {
16686 return Err(ColumnError::Type(TypeError::NonNumericValue {
16687 value: format!("{v:?}"),
16688 dtype: self.dtype,
16689 }));
16690 }
16691 }
16692 }
16693 Self::new(DType::Float64, out)
16694 }
16695
16696 pub fn square(&self) -> Result<Self, ColumnError> {
16698 if let Some(data) = self.as_i64_slice() {
16702 return Ok(Self::from_i64_values(data.iter().map(|&x| x * x).collect()));
16703 }
16704 if let Some(data) = self.as_f64_slice() {
16705 return Ok(Self::from_f64_values(data.iter().map(|&x| x * x).collect()));
16706 }
16707 let mut out = Vec::with_capacity(self.values.len());
16708 for v in &self.values {
16709 if v.is_missing() {
16710 out.push(Scalar::Float64(f64::NAN));
16711 continue;
16712 }
16713 match v {
16714 Scalar::Int64(x) => out.push(Scalar::Int64(x * x)),
16715 Scalar::Float64(x) => out.push(Scalar::Float64(x * x)),
16716 _ => {
16717 return Err(ColumnError::Type(TypeError::NonNumericValue {
16718 value: format!("{v:?}"),
16719 dtype: self.dtype,
16720 }));
16721 }
16722 }
16723 }
16724 let dtype = match self.dtype {
16725 DType::Int64 => DType::Int64,
16726 _ => DType::Float64,
16727 };
16728 Self::new(dtype, out)
16729 }
16730
16731 pub fn shift(&self, periods: i64, fill: Scalar) -> Result<Self, ColumnError> {
16738 let len = self.values.len();
16739 if len == 0 || periods == 0 {
16740 return Ok(self.clone());
16741 }
16742 let abs = periods.unsigned_abs() as usize;
16743 if fill.is_missing()
16752 && let Some(data) = self.as_f64_slice()
16753 {
16754 let mut out = vec![f64::NAN; len];
16755 if abs < len {
16756 if periods > 0 {
16757 out[abs..].copy_from_slice(&data[..len - abs]);
16758 } else {
16759 out[..len - abs].copy_from_slice(&data[abs..]);
16760 }
16761 }
16762 return Ok(Self::from_f64_values(out));
16763 }
16764 let mut out: Vec<Scalar> = Vec::with_capacity(len);
16765 if abs >= len {
16766 for _ in 0..len {
16767 out.push(fill.clone());
16768 }
16769 } else if periods > 0 {
16770 for _ in 0..abs {
16771 out.push(fill.clone());
16772 }
16773 out.extend_from_slice(&self.values[..len - abs]);
16774 } else {
16775 out.extend_from_slice(&self.values[abs..]);
16776 for _ in 0..abs {
16777 out.push(fill.clone());
16778 }
16779 }
16780 Self::new(self.dtype, out)
16781 }
16782
16783 pub fn clip(&self, lower: Option<f64>, upper: Option<f64>) -> Result<Self, ColumnError> {
16790 let lower = lower.filter(|v| !v.is_nan());
16791 let upper = upper.filter(|v| !v.is_nan());
16792 let clamp = |mut x: f64| {
16800 if let Some(lo) = lower
16801 && x < lo
16802 {
16803 x = lo;
16804 }
16805 if let Some(hi) = upper
16806 && x > hi
16807 {
16808 x = hi;
16809 }
16810 x
16811 };
16812 if let Some(data) = self.as_f64_slice() {
16813 let out: Vec<f64> = data.iter().map(|&x| clamp(x)).collect();
16814 return Ok(Self::from_f64_values(out));
16815 }
16816 if let Some(data) = self.as_i64_slice() {
16817 let out: Vec<f64> = data.iter().map(|&x| clamp(x as f64)).collect();
16818 return Ok(Self::from_f64_values(out));
16819 }
16820
16821 let mut out = Vec::with_capacity(self.values.len());
16822 for v in &self.values {
16823 if v.is_missing() {
16824 out.push(v.clone());
16825 continue;
16826 }
16827 let numeric = match v.to_f64() {
16828 Ok(x) => x,
16829 Err(err) => return Err(ColumnError::Type(err)),
16830 };
16831 let mut clipped = numeric;
16832 if let Some(lo) = lower
16833 && clipped < lo
16834 {
16835 clipped = lo;
16836 }
16837 if let Some(hi) = upper
16838 && clipped > hi
16839 {
16840 clipped = hi;
16841 }
16842 out.push(Scalar::Float64(clipped));
16843 }
16844 Self::new(DType::Float64, out)
16845 }
16846
16847 pub fn round(&self, decimals: i32) -> Result<Self, ColumnError> {
16855 if matches!(self.dtype, DType::Bool) || (self.dtype == DType::Int64 && decimals >= 0) {
16856 return Ok(self.clone());
16857 }
16858 if self.dtype == DType::Int64 {
16859 let out = self
16860 .values
16861 .iter()
16862 .map(|v| match v {
16863 Scalar::Int64(value) => {
16864 Scalar::Int64(round_i64_negative_decimals(*value, decimals))
16865 }
16866 Scalar::Null(kind) => Scalar::Null(*kind),
16867 other => other.clone(),
16868 })
16869 .collect();
16870 return Self::new(DType::Int64, out);
16871 }
16872 let factor = 10f64.powi(decimals);
16873 if let Some(data) = self.as_f64_slice() {
16881 return Ok(Self::from_f64_values(
16882 data.iter()
16883 .map(|&x| (x * factor).round_ties_even() / factor)
16884 .collect(),
16885 ));
16886 }
16887 let mut out = Vec::with_capacity(self.values.len());
16888 for v in &self.values {
16889 if v.is_missing() {
16890 out.push(v.clone());
16891 continue;
16892 }
16893 match v.to_f64() {
16894 Ok(x) => out.push(Scalar::Float64((x * factor).round_ties_even() / factor)),
16895 Err(err) => return Err(ColumnError::Type(err)),
16896 }
16897 }
16898 Self::new(DType::Float64, out)
16899 }
16900
16901 pub fn isin(&self, needles: &[Scalar]) -> Result<Self, ColumnError> {
16907 #[derive(Hash, PartialEq, Eq)]
16908 enum Key<'a> {
16909 Bool(bool),
16910 Int64(i64),
16911 FloatBits(u64),
16912 Utf8(&'a str),
16913 Timedelta64(i64),
16914 Datetime64(i64),
16915 Period(i64),
16916 Interval(u64, u64, IntervalClosed),
16917 }
16918 fn key_of(v: &Scalar) -> Option<Key<'_>> {
16919 if v.is_missing() {
16920 return None;
16921 }
16922 Some(match v {
16923 Scalar::Bool(b) => Key::Bool(*b),
16924 Scalar::Int64(i) => Key::Int64(*i),
16925 Scalar::Float64(f) => {
16926 let norm = if *f == 0.0 { 0.0 } else { *f };
16927 Key::FloatBits(norm.to_bits())
16928 }
16929 Scalar::Utf8(s) => Key::Utf8(s.as_str()),
16930 Scalar::Timedelta64(v) => Key::Timedelta64(*v),
16931 Scalar::Datetime64(v) => Key::Datetime64(*v),
16932 Scalar::Period(p) => Key::Period(p.ordinal),
16933 Scalar::Interval(v) => {
16934 let (left, right, closed) = interval_key(v);
16935 Key::Interval(left, right, closed)
16936 }
16937 Scalar::Null(_) => return None,
16938 })
16939 }
16940
16941 if let Some(data) = self.as_i64_slice() {
16950 let mut n_min = i64::MAX;
16951 let mut n_max = i64::MIN;
16952 let mut saw_int_needle = false;
16953 for needle in needles {
16954 if let Scalar::Int64(v) = needle {
16955 saw_int_needle = true;
16956 n_min = n_min.min(*v);
16957 n_max = n_max.max(*v);
16958 }
16959 }
16960 if !saw_int_needle {
16961 return Ok(Self::from_bool_values(vec![false; data.len()]));
16962 }
16963 let span = i128::from(n_max) - i128::from(n_min) + 1;
16964 if span > 0 && span <= (1i128 << 24) {
16965 let mut present = vec![false; span as usize];
16966 for needle in needles {
16967 if let Scalar::Int64(v) = needle {
16968 present[(v - n_min) as usize] = true;
16969 }
16970 }
16971 let out: Vec<bool> = data
16972 .iter()
16973 .map(|&v| v >= n_min && v <= n_max && present[(v - n_min) as usize])
16974 .collect();
16975 return Ok(Self::from_bool_values(out));
16976 }
16977 }
16978
16979 let mut lookup: FxHashSet<Key<'_>> = FxHashSet::default();
16980 for n in needles {
16981 if let Some(k) = key_of(n) {
16982 lookup.insert(k);
16983 }
16984 }
16985
16986 let out: Vec<bool> = self
16992 .values
16993 .iter()
16994 .map(|v| match key_of(v) {
16995 Some(k) => lookup.contains(&k),
16996 None => false,
16997 })
16998 .collect();
16999 Ok(Self::from_bool_values(out))
17000 }
17001
17002 pub fn unique(&self) -> Result<Self, ColumnError> {
17008 if let Some(data) = self.as_i64_slice()
17015 && let Some((min, range)) = i64_direct_address_range(data)
17016 {
17017 let mut seen = vec![false; range];
17018 let mut out: Vec<i64> = Vec::new();
17019 for &v in data {
17020 let slot = (v as i128 - min as i128) as usize;
17021 if !seen[slot] {
17022 seen[slot] = true;
17023 out.push(v);
17024 }
17025 }
17026 return Ok(Self::from_i64_values(out));
17027 }
17028
17029 #[derive(Hash, PartialEq, Eq)]
17030 enum Key<'a> {
17031 Bool(bool),
17032 Int64(i64),
17033 FloatBits(u64),
17034 Utf8(&'a str),
17035 Timedelta64(i64),
17036 Datetime64(i64),
17037 Period(i64),
17038 Interval(u64, u64, IntervalClosed),
17039 }
17040
17041 let mut seen: FxHashSet<Key<'_>> = FxHashSet::default();
17042 let mut out = Vec::new();
17043 for v in &self.values {
17044 if v.is_missing() {
17045 continue;
17046 }
17047 let key = match v {
17048 Scalar::Bool(b) => Key::Bool(*b),
17049 Scalar::Int64(i) => Key::Int64(*i),
17050 Scalar::Float64(f) => {
17051 let norm = if *f == 0.0 { 0.0 } else { *f };
17052 Key::FloatBits(norm.to_bits())
17053 }
17054 Scalar::Utf8(s) => Key::Utf8(s.as_str()),
17055 Scalar::Timedelta64(v) => Key::Timedelta64(*v),
17056 Scalar::Datetime64(v) => Key::Datetime64(*v),
17057 Scalar::Period(p) => Key::Period(p.ordinal),
17058 Scalar::Interval(v) => {
17059 let (left, right, closed) = interval_key(v);
17060 Key::Interval(left, right, closed)
17061 }
17062 Scalar::Null(_) => continue,
17063 };
17064 if seen.insert(key) {
17065 out.push(v.clone());
17066 }
17067 }
17068 Self::new(self.dtype, out)
17069 }
17070
17071 pub fn setdiff1d(&self, other: &Self) -> Result<Self, ColumnError> {
17075 let other_unique = other.unique()?;
17076 let other_set: FxHashSet<SetMemberKey<'_>> = other_unique
17079 .values()
17080 .iter()
17081 .filter_map(set_member_key)
17082 .collect();
17083 let mut seen: FxHashSet<SetMemberKey<'_>> = FxHashSet::default();
17084 let mut out = Vec::new();
17085 for v in &self.values {
17086 let Some(key) = set_member_key(v) else {
17087 continue;
17088 };
17089 if !other_set.contains(&key) && seen.insert(key) {
17090 out.push(v.clone());
17091 }
17092 }
17093 Self::new(self.dtype, out)
17094 }
17095
17096 pub fn intersect1d(&self, other: &Self) -> Result<Self, ColumnError> {
17100 let self_unique = self.unique()?;
17101 let other_unique = other.unique()?;
17102 let other_set: FxHashSet<SetMemberKey<'_>> = other_unique
17103 .values()
17104 .iter()
17105 .filter_map(set_member_key)
17106 .collect();
17107 let mut out = Vec::new();
17108 for v in self_unique.values() {
17109 let Some(key) = set_member_key(v) else {
17110 continue;
17111 };
17112 if other_set.contains(&key) {
17113 out.push(v.clone());
17114 }
17115 }
17116 Self::new(self.dtype, out)
17117 }
17118
17119 pub fn union1d(&self, other: &Self) -> Result<Self, ColumnError> {
17123 let mut combined = self.values.to_vec();
17124 combined.extend(other.values().iter().cloned());
17125 let temp = Self::new(self.dtype, combined)?;
17126 temp.unique()
17127 }
17128
17129 pub fn setxor1d(&self, other: &Self) -> Result<Self, ColumnError> {
17134 let a_unique = self.unique()?;
17135 let b_unique = other.unique()?;
17136 let a_set: FxHashSet<SetMemberKey<'_>> = a_unique
17137 .values()
17138 .iter()
17139 .filter_map(set_member_key)
17140 .collect();
17141 let b_set: FxHashSet<SetMemberKey<'_>> = b_unique
17142 .values()
17143 .iter()
17144 .filter_map(set_member_key)
17145 .collect();
17146 let mut out = Vec::new();
17147 for v in a_unique.values() {
17149 let Some(key) = set_member_key(v) else {
17150 continue;
17151 };
17152 if !b_set.contains(&key) {
17153 out.push(v.clone());
17154 }
17155 }
17156 for v in b_unique.values() {
17158 let Some(key) = set_member_key(v) else {
17159 continue;
17160 };
17161 if !a_set.contains(&key) {
17162 out.push(v.clone());
17163 }
17164 }
17165 Self::new(self.dtype, out)
17166 }
17167
17168 pub fn in1d(&self, other: &Self) -> Result<Self, ColumnError> {
17172 let other_unique = other.unique()?;
17173 let other_set: FxHashSet<SetMemberKey<'_>> = other_unique
17174 .values()
17175 .iter()
17176 .filter_map(set_member_key)
17177 .collect();
17178 let mut out = Vec::with_capacity(self.values.len());
17180 for v in &self.values {
17181 let found = match set_member_key(v) {
17182 Some(key) => other_set.contains(&key),
17183 None => false, };
17185 out.push(found);
17186 }
17187 Ok(Self::from_bool_values(out))
17188 }
17189
17190 pub fn value_counts(&self) -> Result<(Self, Self), ColumnError> {
17196 self.value_counts_with_options(false, true, false, true)
17197 }
17198
17199 pub fn value_counts_with_options(
17205 &self,
17206 normalize: bool,
17207 sort: bool,
17208 ascending: bool,
17209 dropna: bool,
17210 ) -> Result<(Self, Self), ColumnError> {
17211 let mut counts: Vec<(Scalar, usize)> = Vec::new();
17220 let mut index: rustc_hash::FxHashMap<SetMemberKey<'_>, usize> =
17221 rustc_hash::FxHashMap::default();
17222 let mut missing_count = 0_usize;
17223
17224 for value in &self.values {
17225 if value.is_missing() {
17226 missing_count += 1;
17227 continue;
17228 }
17229 let Some(key) = set_member_key(value) else {
17230 counts.push((value.clone(), 1));
17232 continue;
17233 };
17234 if let Some(&i) = index.get(&key) {
17235 counts[i].1 += 1;
17236 } else {
17237 index.insert(key, counts.len());
17238 counts.push((value.clone(), 1));
17239 }
17240 }
17241
17242 if !dropna && missing_count > 0 {
17243 counts.push((Scalar::Null(NullKind::NaN), missing_count));
17244 }
17245
17246 if sort {
17247 if ascending {
17248 counts.sort_by_key(|(_, count)| *count);
17249 } else {
17250 counts.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
17251 }
17252 }
17253
17254 let total = if normalize {
17255 counts.iter().map(|(_, count)| *count).sum::<usize>() as f64
17256 } else {
17257 1.0
17258 };
17259
17260 let mut values_out = Vec::with_capacity(counts.len());
17261 let mut counts_out = Vec::with_capacity(counts.len());
17262 for (value, count) in counts {
17263 values_out.push(value);
17264 if normalize {
17265 let normalized = if total == 0.0 {
17266 0.0
17267 } else {
17268 count as f64 / total
17269 };
17270 counts_out.push(Scalar::Float64(normalized));
17271 } else {
17272 counts_out.push(Scalar::Int64(i64::try_from(count).unwrap_or(i64::MAX)));
17273 }
17274 }
17275
17276 let values = Self::new(self.dtype, values_out)?;
17277 let counts = Self::new(
17278 if normalize {
17279 DType::Float64
17280 } else {
17281 DType::Int64
17282 },
17283 counts_out,
17284 )?;
17285 Ok((values, counts))
17286 }
17287
17288 #[must_use]
17289 pub fn semantic_eq(&self, other: &Self) -> bool {
17290 self.dtype == other.dtype
17291 && self.values.len() == other.values.len()
17292 && self
17293 .values
17294 .iter()
17295 .zip(&other.values)
17296 .all(|(left, right)| left.semantic_eq(right))
17297 }
17298
17299 pub fn isclose(&self, other: &Self, rtol: f64, atol: f64) -> Result<Self, ColumnError> {
17303 if self.len() != other.len() {
17304 return Err(ColumnError::LengthMismatch {
17305 left: self.len(),
17306 right: other.len(),
17307 });
17308 }
17309 let mut out = Vec::with_capacity(self.values.len());
17310 for (a, b) in self.values.iter().zip(&other.values) {
17311 if a.is_missing() || b.is_missing() {
17312 out.push(Scalar::Bool(false));
17313 continue;
17314 }
17315 let af = a.to_f64().map_err(ColumnError::Type)?;
17316 let bf = b.to_f64().map_err(ColumnError::Type)?;
17317 let close = (af - bf).abs() <= atol + rtol * bf.abs();
17318 out.push(Scalar::Bool(close));
17319 }
17320 Self::new(DType::Bool, out)
17321 }
17322
17323 pub fn allclose(&self, other: &Self, rtol: f64, atol: f64) -> Result<bool, ColumnError> {
17327 let close = self.isclose(other, rtol, atol)?;
17328 for v in close.values() {
17329 match v {
17330 Scalar::Bool(true) => continue,
17331 Scalar::Bool(false) => return Ok(false),
17332 _ => return Ok(false),
17333 }
17334 }
17335 Ok(true)
17336 }
17337}
17338
17339pub struct CrackIndex {
17358 perm: Vec<usize>,
17361 cracks: Vec<(f64, usize)>,
17365}
17366
17367impl CrackIndex {
17368 #[must_use]
17370 pub fn new(len: usize) -> Self {
17371 Self {
17372 perm: (0..len).collect(),
17373 cracks: Vec::new(),
17374 }
17375 }
17376
17377 #[must_use]
17379 pub fn num_cracks(&self) -> usize {
17380 self.cracks.len()
17381 }
17382
17383 pub fn filter_gt(&mut self, column: &Column, value: f64) -> Vec<usize> {
17385 let split = self.crack_at(column, value);
17386 self.perm[split..].to_vec()
17387 }
17388
17389 pub fn filter_lte(&mut self, column: &Column, value: f64) -> Vec<usize> {
17391 let split = self.crack_at(column, value);
17392 self.perm[..split]
17393 .iter()
17394 .copied()
17395 .filter(|&idx| {
17396 column
17397 .value(idx)
17398 .and_then(|v| v.to_f64().ok())
17399 .is_some_and(|f| f <= value)
17400 })
17401 .collect()
17402 }
17403
17404 pub fn filter_gte(&mut self, column: &Column, value: f64) -> Vec<usize> {
17406 let split = self.crack_at(column, value);
17409 let mut result: Vec<usize> = self.perm[split..].to_vec();
17412 for &idx in &self.perm[..split] {
17413 if let Some(v) = column.value(idx)
17414 && let Ok(f) = v.to_f64()
17415 && f == value
17416 {
17417 result.push(idx);
17418 }
17419 }
17420 result
17421 }
17422
17423 pub fn filter_lt(&mut self, column: &Column, value: f64) -> Vec<usize> {
17425 let split = self.crack_at(column, value);
17426 self.perm[..split]
17428 .iter()
17429 .copied()
17430 .filter(|&idx| {
17431 column
17432 .value(idx)
17433 .and_then(|v| v.to_f64().ok())
17434 .is_some_and(|f| f < value)
17435 })
17436 .collect()
17437 }
17438
17439 pub fn filter_eq(&mut self, column: &Column, value: f64) -> Vec<usize> {
17441 let split = self.crack_at(column, value);
17442 self.perm[..split]
17444 .iter()
17445 .copied()
17446 .filter(|&idx| {
17447 column
17448 .value(idx)
17449 .and_then(|v| v.to_f64().ok())
17450 .is_some_and(|f| f == value)
17451 })
17452 .collect()
17453 }
17454
17455 fn crack_at(&mut self, column: &Column, value: f64) -> usize {
17458 if let Ok(pos) = self.cracks.binary_search_by(|probe| {
17460 probe
17461 .0
17462 .partial_cmp(&value)
17463 .unwrap_or(std::cmp::Ordering::Equal)
17464 }) {
17465 return self.cracks[pos].1;
17466 }
17467
17468 let (region_start, region_end) = self.find_region(value);
17470
17471 let split = self.partition_region(column, region_start, region_end, value);
17474
17475 let insert_pos = self
17477 .cracks
17478 .binary_search_by(|probe| {
17479 probe
17480 .0
17481 .partial_cmp(&value)
17482 .unwrap_or(std::cmp::Ordering::Equal)
17483 })
17484 .unwrap_or_else(|pos| pos);
17485 self.cracks.insert(insert_pos, (value, split));
17486
17487 split
17488 }
17489
17490 fn find_region(&self, value: f64) -> (usize, usize) {
17492 let mut start = 0;
17493 let mut end = self.perm.len();
17494
17495 for &(crack_val, crack_pos) in &self.cracks {
17496 if crack_val < value {
17497 start = start.max(crack_pos);
17498 } else {
17499 end = end.min(crack_pos);
17500 break;
17501 }
17502 }
17503
17504 (start, end)
17505 }
17506
17507 fn partition_region(&mut self, column: &Column, start: usize, end: usize, pivot: f64) -> usize {
17510 let region = &mut self.perm[start..end];
17512 let mut write = 0;
17513
17514 for read in 0..region.len() {
17515 let idx = region[read];
17516 let val = column
17517 .value(idx)
17518 .and_then(|v| v.to_f64().ok())
17519 .unwrap_or(f64::NEG_INFINITY); if val <= pivot {
17522 region.swap(write, read);
17523 write += 1;
17524 }
17525 }
17526
17527 start + write
17528 }
17529}
17530
17531#[cfg(test)]
17532mod tests {
17533 use std::sync::Arc;
17534
17535 use fp_types::{
17536 DType, Interval, IntervalClosed, NullKind, Period, PeriodFreq, Scalar, SparseDType,
17537 };
17538
17539 use super::{
17540 ArithmeticOp, BoolAffineSelectionWitness, Column, ColumnData, ColumnError, ScalarValues,
17541 SparseColumn, ValidityMask,
17542 };
17543
17544 #[test]
17545 fn reindex_injects_missing_values() {
17546 let column = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)])
17547 .expect("column should build");
17548
17549 let out = column
17550 .reindex_by_positions(&[Some(1), None, Some(0)])
17551 .expect("reindex should work");
17552
17553 assert_eq!(
17554 out.values(),
17555 &[
17556 Scalar::Int64(20),
17557 Scalar::Null(NullKind::Null),
17558 Scalar::Int64(10)
17559 ]
17560 );
17561 }
17562
17563 #[test]
17564 fn take_positions_matches_validated_materialization() {
17565 let column = Column::new(
17566 DType::Float64,
17567 vec![
17568 Scalar::Float64(1.5),
17569 Scalar::Null(NullKind::NaN),
17570 Scalar::Float64(3.5),
17571 ],
17572 )
17573 .expect("column should build");
17574
17575 let positions = [2, 1, 0, 2];
17576 let gathered = column.take_positions(&positions);
17577 let expected_values = positions
17578 .iter()
17579 .map(|&position| column.values()[position].clone())
17580 .collect::<Vec<_>>();
17581 let expected =
17582 Column::new(column.dtype(), expected_values).expect("validated materialization");
17583
17584 assert_eq!(gathered.dtype(), expected.dtype());
17585 assert_eq!(gathered.values(), expected.values());
17586 assert_eq!(gathered.validity(), expected.validity());
17587
17588 let empty = column.take_positions(&[]);
17589 assert_eq!(empty.dtype(), column.dtype());
17590 assert!(empty.values().is_empty());
17591 assert_eq!(empty.validity(), &ValidityMask::all_invalid(0));
17592 }
17593
17594 #[test]
17595 fn take_position_runs_nullable_float64_matches_take_positions() {
17596 let column =
17597 Column::from_f64_values(vec![1.0, 2.0, f64::NAN, 4.0, 5.0, 6.0, f64::NAN, 8.0]);
17598 let runs = [(0, 2), (3, 3), (7, 1)];
17599 let positions = [0, 1, 3, 4, 5, 7];
17600
17601 assert!(column.supports_fast_position_run_gather());
17602 let gathered = column.take_position_runs(&runs, positions.len());
17603 let expected = column.take_positions(&positions);
17604
17605 assert_eq!(gathered.dtype(), expected.dtype());
17606 assert_eq!(gathered.values(), expected.values());
17607 assert_eq!(gathered.validity(), expected.validity());
17608 assert!(matches!(
17609 &gathered.values,
17610 ScalarValues::LazyAllValidFloat64 { .. } | ScalarValues::LazyNullableFloat64 { .. }
17611 ));
17612 }
17613
17614 #[test]
17615 fn take_positions_all_valid_primitives_match_validated_materialization() {
17616 let cases = [
17617 (
17618 DType::Bool,
17619 vec![Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(false)],
17620 ),
17621 (
17622 DType::Int64,
17623 vec![Scalar::Int64(10), Scalar::Int64(-5), Scalar::Int64(42)],
17624 ),
17625 (
17626 DType::Float64,
17627 vec![
17628 Scalar::Float64(1.25),
17629 Scalar::Float64(-0.0),
17630 Scalar::Float64(9.5),
17631 ],
17632 ),
17633 (
17634 DType::Timedelta64,
17635 vec![
17636 Scalar::Timedelta64(10),
17637 Scalar::Timedelta64(-5),
17638 Scalar::Timedelta64(42),
17639 ],
17640 ),
17641 (
17642 DType::Datetime64,
17643 vec![
17644 Scalar::Datetime64(10),
17645 Scalar::Datetime64(-5),
17646 Scalar::Datetime64(42),
17647 ],
17648 ),
17649 (
17650 DType::Period,
17651 vec![
17652 Scalar::Period(Period::new(10, PeriodFreq::Daily)),
17653 Scalar::Period(Period::new(-5, PeriodFreq::Daily)),
17654 Scalar::Period(Period::new(42, PeriodFreq::Daily)),
17655 ],
17656 ),
17657 ];
17658
17659 let positions = [2, 0, 2, 1];
17660 for (dtype, values) in cases {
17661 let column = Column::new(dtype, values).expect("column should build");
17662 let gathered = column.take_positions(&positions);
17663 let expected_values = positions
17664 .iter()
17665 .map(|&position| column.values()[position].clone())
17666 .collect::<Vec<_>>();
17667 let expected =
17668 Column::new(column.dtype(), expected_values).expect("validated materialization");
17669
17670 assert_eq!(gathered.dtype(), expected.dtype());
17671 assert_eq!(gathered.values(), expected.values());
17672 assert_eq!(gathered.validity(), expected.validity());
17673 }
17674 }
17675
17676 #[test]
17677 fn take_positions_preserves_exact_null_kind_contract() {
17678 for (dtype, real) in [
17690 (DType::Float64, Scalar::Float64(2.5)),
17691 (DType::Int64, Scalar::Int64(7)),
17692 ] {
17693 let source = Column::new(
17694 dtype,
17695 vec![
17696 Scalar::Null(NullKind::NaN),
17697 Scalar::Null(NullKind::NaT),
17698 Scalar::Null(NullKind::Null),
17699 real,
17700 ],
17701 )
17702 .expect("column builds");
17703 let stored = source.values().to_vec();
17707 let positions = [3, 2, 1, 0, 1];
17708 let gathered = source.take_positions(&positions);
17709 for (out_idx, &pos) in positions.iter().enumerate() {
17710 assert_eq!(
17711 gathered.values()[out_idx],
17712 stored[pos],
17713 "dtype {dtype:?}: take_positions must reproduce the exact stored scalar \
17714 (incl. NullKind) for source position {pos}",
17715 );
17716 assert_eq!(
17718 gathered.validity().get(out_idx),
17719 source.validity().get(pos),
17720 "dtype {dtype:?}: validity must follow the gathered position {pos}",
17721 );
17722 }
17723 }
17724 }
17725
17726 #[test]
17727 fn primitive_columns_cache_typed_data_for_take_positions() {
17728 let column = Column::new(
17729 DType::Float64,
17730 vec![
17731 Scalar::Float64(1.25),
17732 Scalar::Float64(-0.0),
17733 Scalar::Float64(9.5),
17734 ],
17735 )
17736 .expect("column should build");
17737
17738 assert!(matches!(column.data, Some(ColumnData::Float64(_))));
17739 let positions = [2, 0, 1, 2];
17740 let gathered = column.take_positions(&positions);
17741 let expected = Column::new(
17742 DType::Float64,
17743 positions
17744 .iter()
17745 .map(|&position| column.values()[position].clone())
17746 .collect(),
17747 )
17748 .expect("validated materialization");
17749
17750 assert_eq!(gathered.values(), expected.values());
17751 assert_eq!(gathered.validity(), expected.validity());
17752 }
17753
17754 #[test]
17755 fn float64_take_positions_defers_scalar_materialization() {
17756 let column = Column::new(
17757 DType::Float64,
17758 vec![
17759 Scalar::Float64(1.25),
17760 Scalar::Float64(-0.0),
17761 Scalar::Float64(9.5),
17762 ],
17763 )
17764 .expect("column should build");
17765
17766 let positions = [2, 0, 1, 2];
17767 let gathered = column.take_positions(&positions);
17768
17769 assert!(
17770 matches!(&gathered.values, ScalarValues::LazyAllValidFloat64 { .. }),
17771 "Float64 gather should defer scalar materialization"
17772 );
17773 if let ScalarValues::LazyAllValidFloat64 { data, values, .. } = &gathered.values {
17774 assert_eq!(
17775 data.iter().map(|value| value.to_bits()).collect::<Vec<_>>(),
17776 vec![
17777 9.5f64.to_bits(),
17778 1.25f64.to_bits(),
17779 (-0.0f64).to_bits(),
17780 9.5f64.to_bits(),
17781 ]
17782 );
17783 assert!(values.get().is_none());
17784 }
17785 assert_eq!(gathered.len(), positions.len());
17786 assert_eq!(
17787 gathered.validity(),
17788 &ValidityMask::all_valid(positions.len())
17789 );
17790
17791 let expected = Column::new(
17792 DType::Float64,
17793 positions
17794 .iter()
17795 .map(|&position| column.values()[position].clone())
17796 .collect(),
17797 )
17798 .expect("validated materialization");
17799
17800 assert_eq!(gathered.values(), expected.values());
17801 assert!(
17802 matches!(&gathered.values, ScalarValues::LazyAllValidFloat64 { .. }),
17803 "Float64 gather should stay lazy after read"
17804 );
17805 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &gathered.values {
17806 assert!(values.get().is_some());
17807 }
17808 assert_eq!(gathered.validity(), expected.validity());
17809 }
17810
17811 #[test]
17812 fn float64_take_positions_contiguous_range_returns_slice_view() {
17813 let data: Vec<f64> = (0..160)
17814 .map(|i| match i {
17815 40 => -0.0,
17816 41 => f64::INFINITY,
17817 42 => f64::from_bits(1),
17818 _ => i as f64 + 0.5,
17819 })
17820 .collect();
17821 let expected_bits: Vec<u64> = data[32..112].iter().map(|value| value.to_bits()).collect();
17822 let column = Column::from_f64_values(data);
17823 let positions: Vec<usize> = (32..112).collect();
17824
17825 let gathered = column.take_positions(&positions);
17826
17827 assert!(
17828 matches!(
17829 &gathered.values,
17830 ScalarValues::LazyAllValidFloat64Slice { .. }
17831 ),
17832 "large contiguous Float64 takes should share the source buffer"
17833 );
17834 if let ScalarValues::LazyAllValidFloat64Slice {
17835 start, len, values, ..
17836 } = &gathered.values
17837 {
17838 assert_eq!((*start, *len), (32, 80));
17839 assert!(values.get().is_none());
17840 }
17841 assert_eq!(
17842 gathered.as_f64_slice().map(|values| {
17843 values
17844 .iter()
17845 .map(|value| value.to_bits())
17846 .collect::<Vec<_>>()
17847 }),
17848 Some(expected_bits)
17849 );
17850
17851 let expected = Column::from_f64_values(
17852 column.as_f64_slice().expect("source stays typed")[32..112].to_vec(),
17853 );
17854 assert_eq!(gathered.values(), expected.values());
17855 assert_eq!(gathered.validity(), expected.validity());
17856 if let ScalarValues::LazyAllValidFloat64Slice { values, .. } = &gathered.values {
17857 assert!(values.get().is_some());
17858 }
17859 }
17860
17861 #[test]
17862 fn float64_take_positions_contiguous_range_slices_existing_slice_view() {
17863 let data: Vec<f64> = (0..192).map(|i| (i as f64).mul_add(0.25, -7.0)).collect();
17864 let column = Column::from_f64_values(data);
17865 let first_positions: Vec<usize> = (20..128).collect();
17866 let first = column.take_positions(&first_positions);
17867 let second_positions: Vec<usize> = (10..74).collect();
17868
17869 let second = first.take_positions(&second_positions);
17870
17871 assert!(
17872 matches!(
17873 &second.values,
17874 ScalarValues::LazyAllValidFloat64Slice { .. }
17875 ),
17876 "nested contiguous Float64 take should remain a slice view"
17877 );
17878 if let ScalarValues::LazyAllValidFloat64Slice {
17879 start, len, values, ..
17880 } = &second.values
17881 {
17882 assert_eq!((*start, *len), (30, 64));
17883 assert!(values.get().is_none());
17884 }
17885 let expected = Column::from_f64_values(
17886 column.as_f64_slice().expect("source stays typed")[30..94].to_vec(),
17887 );
17888 assert_eq!(second.as_f64_slice(), expected.as_f64_slice());
17889 assert_eq!(second.values(), expected.values());
17890 }
17891
17892 #[test]
17893 fn take_contiguous_range_uses_typed_views_without_positions() {
17894 let f64_data: Vec<f64> = (0..160)
17895 .map(|i| if i == 72 { -0.0 } else { i as f64 * 0.5 })
17896 .collect();
17897 let f64_column = Column::from_f64_values(f64_data);
17898 let f64_range = f64_column.take_contiguous_range(64, 80);
17899 assert!(
17900 matches!(
17901 &f64_range.values,
17902 ScalarValues::LazyAllValidFloat64Slice { .. }
17903 ),
17904 "Float64 range gather should be a zero-copy slice view"
17905 );
17906 assert_eq!(
17907 f64_range.as_f64_slice().map(|values| {
17908 values
17909 .iter()
17910 .map(|value| value.to_bits())
17911 .collect::<Vec<_>>()
17912 }),
17913 f64_column.as_f64_slice().map(|values| values[64..144]
17914 .iter()
17915 .map(|value| value.to_bits())
17916 .collect::<Vec<_>>())
17917 );
17918
17919 let mut bytes = Vec::new();
17920 let mut offsets = Vec::with_capacity(6);
17921 offsets.push(0);
17922 for value in ["k000", "k001", "k002", "k003", "k004"] {
17923 bytes.extend_from_slice(value.as_bytes());
17924 offsets.push(bytes.len());
17925 }
17926 let utf8_column = Column::from_utf8_contiguous(bytes, offsets);
17927 let utf8_range = utf8_column.take_contiguous_range(1, 3);
17928 assert!(
17929 matches!(&utf8_range.values, ScalarValues::LazyUtf8Slice { .. }),
17930 "Utf8 range gather should be a zero-copy slice view"
17931 );
17932 assert_eq!(
17933 utf8_range.values(),
17934 &[
17935 Scalar::Utf8("k001".to_owned()),
17936 Scalar::Utf8("k002".to_owned()),
17937 Scalar::Utf8("k003".to_owned())
17938 ]
17939 );
17940 }
17941
17942 #[test]
17943 fn float64_take_positions_regular_stride_defers_contiguous_gather() {
17944 let data: Vec<f64> = (0..4096)
17945 .map(|i| match i {
17946 4 => -0.0,
17947 19 => f64::INFINITY,
17948 _ => i as f64 * 0.25,
17949 })
17950 .collect();
17951 let column = Column::from_f64_values(data.clone());
17952 let positions: Vec<usize> = (0..1024).map(|i| 3 + i * 4).collect();
17953
17954 let gathered = column.take_positions(&positions);
17955
17956 assert!(
17957 matches!(&gathered.values, ScalarValues::LazyStridedFloat64 { .. }),
17958 "wide regular Float64 gather should carry a strided view"
17959 );
17960 if let ScalarValues::LazyStridedFloat64 {
17961 start,
17962 step,
17963 len,
17964 expanded,
17965 values,
17966 ..
17967 } = &gathered.values
17968 {
17969 assert_eq!((*start, *step, *len), (3, 4, positions.len()));
17970 assert!(expanded.get().is_none());
17971 assert!(values.get().is_none());
17972 }
17973
17974 let expected_bits: Vec<u64> = positions.iter().map(|&pos| data[pos].to_bits()).collect();
17975 let gathered_bits: Vec<u64> = gathered
17976 .as_f64_slice()
17977 .expect("strided Float64 view must expose a contiguous typed view")
17978 .iter()
17979 .map(|value| value.to_bits())
17980 .collect();
17981 assert_eq!(gathered_bits, expected_bits);
17982 assert_eq!(
17983 gathered.validity(),
17984 &ValidityMask::all_valid(positions.len())
17985 );
17986
17987 let expected = Column::new(
17988 DType::Float64,
17989 positions
17990 .iter()
17991 .map(|&position| column.values()[position].clone())
17992 .collect(),
17993 )
17994 .expect("validated materialization");
17995 assert_eq!(gathered.values(), expected.values());
17996 assert_eq!(gathered.validity(), expected.validity());
17997 }
17998
17999 #[test]
18000 fn take_positions_with_affine_certificate_uses_lazy_strided_float64() {
18001 let data: Vec<f64> = (0..4096)
18002 .map(|i| match i {
18003 8 => -0.0,
18004 23 => f64::NEG_INFINITY,
18005 _ => i as f64 * 0.5,
18006 })
18007 .collect();
18008 let column = Column::from_f64_values(data.clone());
18009 let positions: Vec<usize> = (0..1024).map(|i| 2 + i * 3).collect();
18010
18011 let gathered = column.take_positions_with_affine_certificate(&positions, 2, 3);
18012
18013 assert!(
18014 matches!(&gathered.values, ScalarValues::LazyStridedFloat64 { .. }),
18015 "certified wide regular Float64 gather should carry a strided view"
18016 );
18017 if let ScalarValues::LazyStridedFloat64 {
18018 start,
18019 step,
18020 len,
18021 expanded,
18022 values,
18023 ..
18024 } = &gathered.values
18025 {
18026 assert_eq!((*start, *step, *len), (2, 3, positions.len()));
18027 assert!(expanded.get().is_none());
18028 assert!(values.get().is_none());
18029 }
18030
18031 let expected_bits: Vec<u64> = positions.iter().map(|&pos| data[pos].to_bits()).collect();
18032 let gathered_bits: Vec<u64> = gathered
18033 .as_f64_slice()
18034 .expect("certified strided Float64 view must expose typed data")
18035 .iter()
18036 .map(|value| value.to_bits())
18037 .collect();
18038 assert_eq!(gathered_bits, expected_bits);
18039 assert_eq!(
18040 gathered.validity(),
18041 &ValidityMask::all_valid(positions.len())
18042 );
18043 }
18044
18045 #[test]
18046 fn bounded_arithmetic_progression_positions_rejects_non_affine_or_oob() {
18047 assert_eq!(
18048 Column::bounded_arithmetic_progression_positions(&[3, 7, 11, 15], 16),
18049 Some((3, 4))
18050 );
18051 assert_eq!(
18052 Column::bounded_arithmetic_progression_positions(&[3, 7, 12], 16),
18053 None
18054 );
18055 assert_eq!(
18056 Column::bounded_arithmetic_progression_positions(&[3, 3, 3], 16),
18057 None
18058 );
18059 assert_eq!(
18060 Column::bounded_arithmetic_progression_positions(&[3, 7, 11, 15], 15),
18061 None
18062 );
18063 assert_eq!(
18064 Column::bounded_arithmetic_progression_positions(&[usize::MAX - 1, usize::MAX], 8),
18065 None
18066 );
18067 }
18068
18069 #[test]
18070 fn reindex_all_present_matches_materialization_and_keeps_float64_lazy() {
18071 let column = Column::from_f64_values(vec![1.25, -0.0, f64::INFINITY]);
18072
18073 let positions = [Some(2), Some(0), Some(1), Some(2)];
18074 let gathered = column
18075 .reindex_by_positions(&positions)
18076 .expect("all-present reindex should gather");
18077
18078 assert!(
18079 matches!(&gathered.values, ScalarValues::LazyAllValidFloat64 { .. }),
18080 "all-present Float64 reindex should defer scalar materialization"
18081 );
18082 if let ScalarValues::LazyAllValidFloat64 { data, values, .. } = &gathered.values {
18083 assert_eq!(
18084 data.iter().map(|value| value.to_bits()).collect::<Vec<_>>(),
18085 vec![
18086 f64::INFINITY.to_bits(),
18087 1.25f64.to_bits(),
18088 (-0.0f64).to_bits(),
18089 f64::INFINITY.to_bits(),
18090 ]
18091 );
18092 assert!(values.get().is_none());
18093 }
18094
18095 let expected = Column::new(
18096 DType::Float64,
18097 positions
18098 .iter()
18099 .map(|&position| column.values()[position.expect("present position")].clone())
18100 .collect(),
18101 )
18102 .expect("validated scalar materialization");
18103
18104 assert_eq!(gathered.dtype(), expected.dtype());
18105 assert_eq!(gathered.values(), expected.values());
18106 assert_eq!(gathered.validity(), expected.validity());
18107 }
18108
18109 #[test]
18110 fn column_equality_ignores_skipped_typed_cache() {
18111 let column = Column::new(
18112 DType::Int64,
18113 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
18114 )
18115 .expect("column should build");
18116
18117 let json = serde_json::to_string(&column).expect("serialize");
18118 let roundtrip: Column = serde_json::from_str(&json).expect("deserialize");
18119
18120 assert!(column.data.is_some());
18121 assert!(roundtrip.data.is_none());
18122 assert_eq!(column, roundtrip);
18123 }
18124
18125 #[test]
18126 fn column_clone_preserves_values_without_copying_private_cache() {
18127 let column = Column::new(
18128 DType::Int64,
18129 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
18130 )
18131 .expect("column should build");
18132
18133 let cloned = column.clone();
18134
18135 assert!(column.data.is_some());
18136 assert!(cloned.data.is_none());
18137 assert_eq!(column, cloned);
18138 }
18139
18140 #[test]
18141 fn dense_primitive_clone_defers_float64_scalar_materialization_from_typed_cache() {
18142 let column = Column::new(
18143 DType::Float64,
18144 vec![
18145 Scalar::Float64(1.5),
18146 Scalar::Float64(-0.0),
18147 Scalar::Float64(3.25),
18148 ],
18149 )
18150 .expect("column should build");
18151
18152 let cloned_values = column
18153 .clone_dense_values_from_cache()
18154 .expect("all-valid Float64 typed cache should clone");
18155 assert!(
18156 matches!(&cloned_values, ScalarValues::LazyAllValidFloat64 { .. }),
18157 "Float64 clone should defer scalar materialization"
18158 );
18159 if let ScalarValues::LazyAllValidFloat64 { data, values, .. } = &cloned_values {
18160 assert_eq!(
18161 data.iter().map(|value| value.to_bits()).collect::<Vec<_>>(),
18162 vec![1.5f64.to_bits(), (-0.0f64).to_bits(), 3.25f64.to_bits()]
18163 );
18164 assert!(values.get().is_none());
18165 }
18166
18167 let cloned = column.clone();
18168 assert!(
18169 matches!(&cloned.values, ScalarValues::LazyAllValidFloat64 { .. }),
18170 "Column::clone should keep all-valid Float64 clone values lazy"
18171 );
18172 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &cloned.values {
18173 assert!(values.get().is_none());
18174 }
18175 assert_eq!(cloned.values(), column.values());
18176 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &cloned.values {
18177 assert!(values.get().is_some());
18178 }
18179 assert_eq!(cloned.validity(), column.validity());
18180 assert!(cloned.data.is_none());
18181 }
18182
18183 #[test]
18184 fn dense_primitive_clone_falls_back_for_missing_values() {
18185 let column = Column::new(
18186 DType::Float64,
18187 vec![
18188 Scalar::Float64(1.5),
18189 Scalar::Null(NullKind::NaN),
18190 Scalar::Null(NullKind::Null),
18191 ],
18192 )
18193 .expect("column should build");
18194
18195 assert!(column.clone_dense_values_from_cache().is_none());
18196 let cloned = column.clone();
18197 assert_eq!(cloned.values(), column.values());
18198 assert_eq!(cloned.validity(), column.validity());
18199 assert!(cloned.data.is_none());
18200 }
18201
18202 #[test]
18203 fn numeric_addition_propagates_missing() {
18204 let left = Column::from_values(vec![
18205 Scalar::Int64(1),
18206 Scalar::Null(NullKind::Null),
18207 Scalar::Float64(f64::NAN),
18208 ])
18209 .expect("left");
18210 let right = Column::from_values(vec![Scalar::Int64(2), Scalar::Int64(5), Scalar::Int64(3)])
18211 .expect("right");
18212
18213 let out = left
18214 .binary_numeric(&right, ArithmeticOp::Add)
18215 .expect("add should pass");
18216
18217 assert_eq!(out.values()[0], Scalar::Float64(3.0));
18218 assert_eq!(out.values()[1], Scalar::Null(NullKind::NaN));
18219 assert_eq!(out.values()[2], Scalar::Null(NullKind::NaN));
18220 }
18221
18222 #[test]
18223 fn sparse_column_omits_fill_values_and_materializes_dense() {
18224 let dtype = SparseDType::new(DType::Int64, Scalar::Int64(0)).expect("sparse dtype");
18225 let sparse = SparseColumn::from_dense(
18226 dtype,
18227 vec![
18228 Scalar::Int64(0),
18229 Scalar::Int64(5),
18230 Scalar::Int64(0),
18231 Scalar::Int64(-2),
18232 ],
18233 )
18234 .expect("sparse column");
18235
18236 assert_eq!(sparse.value_dtype(), DType::Int64);
18237 assert_eq!(sparse.fill_value(), &Scalar::Int64(0));
18238 assert_eq!(sparse.len(), 4);
18239 assert_eq!(sparse.npoints(), 2);
18240 assert_eq!(sparse.indices(), &[1, 3]);
18241 assert_eq!(
18242 sparse.stored_values(),
18243 &[Scalar::Int64(5), Scalar::Int64(-2)]
18244 );
18245
18246 let dense = sparse.to_dense_column().expect("dense column");
18247 assert_eq!(dense.dtype(), DType::Int64);
18248 assert_eq!(
18249 dense.values(),
18250 &[
18251 Scalar::Int64(0),
18252 Scalar::Int64(5),
18253 Scalar::Int64(0),
18254 Scalar::Int64(-2),
18255 ]
18256 );
18257 }
18258
18259 #[test]
18260 fn sparse_column_preserves_nulls_when_fill_is_not_missing() {
18261 let dtype = SparseDType::new(DType::Float64, Scalar::Float64(0.0)).expect("sparse dtype");
18262 let sparse = SparseColumn::from_dense(
18263 dtype,
18264 vec![
18265 Scalar::Float64(0.0),
18266 Scalar::Null(NullKind::NaN),
18267 Scalar::Float64(2.5),
18268 ],
18269 )
18270 .expect("sparse column");
18271
18272 assert_eq!(sparse.indices(), &[1, 2]);
18273 assert_eq!(sparse.npoints(), 2);
18274 assert!((sparse.density() - (2.0 / 3.0)).abs() < f64::EPSILON);
18275 assert!(sparse.stored_values()[0].is_missing());
18276 assert_eq!(sparse.stored_values()[1], Scalar::Float64(2.5));
18277
18278 let dense = sparse.to_dense_column().expect("dense column");
18279 assert_eq!(
18280 dense.values(),
18281 &[
18282 Scalar::Float64(0.0),
18283 Scalar::Null(NullKind::NaN),
18284 Scalar::Float64(2.5),
18285 ]
18286 );
18287 }
18288
18289 #[test]
18290 fn sparse_column_missing_fill_omits_missing_values() {
18291 let dtype =
18292 SparseDType::new(DType::Float64, Scalar::Null(NullKind::NaN)).expect("sparse dtype");
18293 let sparse = SparseColumn::from_dense(
18294 dtype,
18295 vec![
18296 Scalar::Null(NullKind::Null),
18297 Scalar::Float64(1.5),
18298 Scalar::Float64(f64::NAN),
18299 ],
18300 )
18301 .expect("sparse column");
18302
18303 assert_eq!(sparse.fill_value(), &Scalar::Null(NullKind::NaN));
18304 assert_eq!(sparse.indices(), &[1]);
18305 assert_eq!(sparse.stored_values(), &[Scalar::Float64(1.5)]);
18306 assert_eq!(
18307 sparse.to_dense_values(),
18308 vec![
18309 Scalar::Null(NullKind::NaN),
18310 Scalar::Float64(1.5),
18311 Scalar::Null(NullKind::NaN),
18312 ]
18313 );
18314 }
18315
18316 #[test]
18319 fn validity_mask_from_values_packs_correctly() {
18320 let values = vec![
18321 Scalar::Int64(1),
18322 Scalar::Null(NullKind::Null),
18323 Scalar::Int64(3),
18324 ];
18325 let mask = ValidityMask::from_values(&values);
18326 assert_eq!(mask.len(), 3);
18327 assert!(mask.get(0));
18328 assert!(!mask.get(1));
18329 assert!(mask.get(2));
18330 assert_eq!(mask.count_valid(), 2);
18331 }
18332
18333 #[test]
18334 fn validity_mask_all_valid() {
18335 let mask = ValidityMask::all_valid(100);
18336 assert_eq!(mask.len(), 100);
18337 assert_eq!(mask.count_valid(), 100);
18338 assert!(
18339 mask.words.is_empty(),
18340 "all-valid masks store only the logical length"
18341 );
18342 for i in 0..100 {
18343 assert!(mask.get(i), "bit {i} should be valid");
18344 }
18345 }
18346
18347 #[test]
18348 fn validity_mask_all_valid_sentinel_matches_explicit_words() {
18349 for len in [1, 2, 63, 64, 65, 127, 128, 129] {
18350 let sentinel = ValidityMask::all_valid(len);
18351 let explicit =
18352 ValidityMask::from_words(ValidityMask::materialized_all_valid_words(len), len);
18353
18354 assert_eq!(sentinel, explicit, "len {len}");
18355 assert_eq!(
18356 sentinel.bits().collect::<Vec<_>>(),
18357 explicit.bits().collect::<Vec<_>>(),
18358 "len {len}"
18359 );
18360 assert!(sentinel.all(), "len {len}");
18361 assert_eq!(sentinel.count_invalid(), 0, "len {len}");
18362 }
18363 }
18364
18365 #[test]
18366 fn validity_mask_all_valid_sentinel_materializes_on_clear() {
18367 let mut mask = ValidityMask::all_valid(130);
18368 mask.set(64, true);
18369 assert!(
18370 mask.words.is_empty(),
18371 "setting a valid bit preserves the sentinel"
18372 );
18373
18374 mask.set(64, false);
18375 assert!(!mask.words.is_empty(), "clearing a bit materializes words");
18376 assert_eq!(mask.len(), 130);
18377 assert_eq!(mask.count_valid(), 129);
18378 assert!(!mask.get(64));
18379 assert!(mask.get(63));
18380 assert!(mask.get(65));
18381 assert_eq!(mask.bits().filter(|valid| *valid).count(), 129);
18382 }
18383
18384 #[test]
18385 fn validity_mask_sparse_invalid_ranges_match_explicit_bitmap() {
18386 let sparse = ValidityMask::from_invalid_ranges(Arc::from(vec![(2, 3), (9, 2)]), 12);
18387 let mut explicit = ValidityMask::all_valid(12);
18388 for idx in [2, 3, 4, 9, 10] {
18389 explicit.set(idx, false);
18390 }
18391
18392 assert!(sparse.words.is_empty());
18393 assert!(sparse.invalid_ranges.is_some());
18394 assert_eq!(sparse, explicit);
18395 assert_eq!(sparse.count_valid(), 7);
18396 assert_eq!(sparse.count_invalid(), 5);
18397 assert!(sparse.get(1));
18398 assert!(!sparse.get(3));
18399 assert!(sparse.get(8));
18400 assert!(!sparse.get(10));
18401 assert_eq!(sparse.slice(1, 6), explicit.slice(1, 6));
18402 assert_eq!(sparse.not_mask(), explicit.not_mask());
18403
18404 let mut mutated = sparse.clone();
18405 mutated.set(2, true);
18406 explicit.set(2, true);
18407 assert_eq!(mutated, explicit);
18408 assert!(mutated.invalid_ranges.is_none());
18409 }
18410
18411 #[test]
18412 fn validity_mask_invalid_range_visitor_merges_word_boundaries() {
18413 let mut mask = ValidityMask::all_valid(140);
18414 for idx in 60..68 {
18415 mask.set(idx, false);
18416 }
18417 for idx in [3, 90, 91, 139] {
18418 mask.set(idx, false);
18419 }
18420
18421 let mut ranges = Vec::new();
18422 mask.for_each_invalid_range(|start, len| ranges.push((start, len)));
18423 assert_eq!(ranges, vec![(3, 1), (60, 8), (90, 2), (139, 1)]);
18424
18425 let sparse = ValidityMask::from_invalid_ranges(Arc::from(ranges.clone()), 140);
18426 let mut sparse_ranges = Vec::new();
18427 sparse.for_each_invalid_range(|start, len| sparse_ranges.push((start, len)));
18428 assert_eq!(sparse_ranges, ranges);
18429 }
18430
18431 #[test]
18432 fn validity_mask_all_invalid() {
18433 let mask = ValidityMask::all_invalid(100);
18434 assert_eq!(mask.len(), 100);
18435 assert_eq!(mask.count_valid(), 0);
18436 for i in 0..100 {
18437 assert!(!mask.get(i), "bit {i} should be invalid");
18438 }
18439 }
18440
18441 #[test]
18442 fn validity_mask_set_and_get() {
18443 let mut mask = ValidityMask::all_invalid(128);
18444 mask.set(0, true);
18445 mask.set(63, true);
18446 mask.set(64, true);
18447 mask.set(127, true);
18448 assert!(mask.get(0));
18449 assert!(mask.get(63));
18450 assert!(mask.get(64));
18451 assert!(mask.get(127));
18452 assert!(!mask.get(1));
18453 assert_eq!(mask.count_valid(), 4);
18454
18455 mask.set(63, false);
18456 assert!(!mask.get(63));
18457 assert_eq!(mask.count_valid(), 3);
18458 }
18459
18460 #[test]
18461 fn validity_mask_and_or_not() {
18462 let mut a = ValidityMask::all_invalid(4);
18463 a.set(0, true);
18464 a.set(1, true);
18465
18466 let mut b = ValidityMask::all_invalid(4);
18467 b.set(1, true);
18468 b.set(2, true);
18469
18470 let and = a.and_mask(&b);
18471 assert!(and.get(1));
18472 assert!(!and.get(0));
18473 assert!(!and.get(2));
18474 assert_eq!(and.count_valid(), 1);
18475
18476 let or = a.or_mask(&b);
18477 assert!(or.get(0));
18478 assert!(or.get(1));
18479 assert!(or.get(2));
18480 assert!(!or.get(3));
18481 assert_eq!(or.count_valid(), 3);
18482
18483 let not_a = a.not_mask();
18484 assert!(!not_a.get(0));
18485 assert!(!not_a.get(1));
18486 assert!(not_a.get(2));
18487 assert!(not_a.get(3));
18488 assert_eq!(not_a.count_valid(), 2);
18489 }
18490
18491 #[test]
18492 fn validity_mask_sentinel_mask_algebra_matches_explicit_bitmap() {
18493 let all = ValidityMask::all_valid(5);
18494 let nullable = ValidityMask::from_values(&[
18495 Scalar::Int64(1),
18496 Scalar::Null(NullKind::Null),
18497 Scalar::Int64(3),
18498 Scalar::Null(NullKind::NaN),
18499 Scalar::Int64(5),
18500 ]);
18501
18502 assert_eq!(all.and_mask(&nullable), nullable);
18503 assert_eq!(nullable.and_mask(&all), nullable);
18504 assert_eq!(all.or_mask(&nullable), all);
18505 assert_eq!(nullable.or_mask(&all), all);
18506 assert_eq!(
18507 all.xor_mask(&nullable).bits().collect::<Vec<_>>(),
18508 vec![false, true, false, true, false]
18509 );
18510 assert_eq!(
18511 all.not_mask().bits().collect::<Vec<_>>(),
18512 vec![false, false, false, false, false]
18513 );
18514 assert_eq!(
18515 all.slice(1, 3).bits().collect::<Vec<_>>(),
18516 vec![true, true, true]
18517 );
18518 assert_eq!(
18519 all.concat(&ValidityMask::all_valid(2)),
18520 ValidityMask::all_valid(7)
18521 );
18522 }
18523
18524 #[test]
18525 fn validity_mask_bits_iterator() {
18526 let values = vec![
18527 Scalar::Int64(1),
18528 Scalar::Null(NullKind::Null),
18529 Scalar::Int64(3),
18530 Scalar::Float64(f64::NAN),
18531 ];
18532 let mask = ValidityMask::from_values(&values);
18533 let bits: Vec<bool> = mask.bits().collect();
18534 assert_eq!(bits, vec![true, false, true, false]);
18535 }
18536
18537 #[test]
18538 fn validity_mask_serde_round_trip() {
18539 let values = vec![
18540 Scalar::Int64(1),
18541 Scalar::Null(NullKind::Null),
18542 Scalar::Int64(3),
18543 ];
18544 let mask = ValidityMask::from_values(&values);
18545 let json = serde_json::to_string(&mask).expect("serialize");
18546 let back: ValidityMask = serde_json::from_str(&json).expect("deserialize");
18547 assert_eq!(mask, back);
18548 assert!(json.contains("\"bits\""), "should serialize as bits field");
18550 }
18551
18552 #[test]
18553 fn validity_mask_empty() {
18554 let mask = ValidityMask::from_values(&[]);
18555 assert!(mask.is_empty());
18556 assert_eq!(mask.len(), 0);
18557 assert_eq!(mask.count_valid(), 0);
18558 assert_eq!(mask.bits().count(), 0);
18559 }
18560
18561 #[test]
18562 fn validity_mask_count_invalid_matches_complement() {
18563 let mask = ValidityMask::from_values(&[
18564 Scalar::Int64(1),
18565 Scalar::Null(NullKind::NaN),
18566 Scalar::Int64(2),
18567 Scalar::Null(NullKind::Null),
18568 Scalar::Int64(3),
18569 ]);
18570 assert_eq!(mask.count_valid(), 3);
18571 assert_eq!(mask.count_invalid(), 2);
18572 assert_eq!(mask.count_valid() + mask.count_invalid(), mask.len());
18573 }
18574
18575 #[test]
18576 fn validity_mask_any_and_all() {
18577 let all_set = ValidityMask::all_valid(4);
18578 assert!(all_set.any());
18579 assert!(all_set.all());
18580
18581 let none_set = ValidityMask::all_invalid(4);
18582 assert!(!none_set.any());
18583 assert!(!none_set.all());
18584
18585 let mixed = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::NaN)]);
18586 assert!(mixed.any());
18587 assert!(!mixed.all());
18588
18589 let empty = ValidityMask::all_invalid(0);
18590 assert!(!empty.any());
18591 assert!(empty.all()); }
18593
18594 #[test]
18595 fn validity_mask_xor_finds_differences() {
18596 let a = ValidityMask::from_values(&[
18597 Scalar::Int64(1),
18598 Scalar::Int64(2),
18599 Scalar::Null(NullKind::NaN),
18600 Scalar::Int64(4),
18601 ]);
18602 let b = ValidityMask::from_values(&[
18603 Scalar::Int64(1),
18604 Scalar::Null(NullKind::NaN),
18605 Scalar::Null(NullKind::NaN),
18606 Scalar::Int64(4),
18607 ]);
18608 let diff = a.xor_mask(&b);
18609 assert_eq!(diff.len(), 4);
18610 assert!(!diff.get(0));
18615 assert!(diff.get(1));
18616 assert!(!diff.get(2));
18617 assert!(!diff.get(3));
18618 }
18619
18620 #[test]
18621 fn validity_mask_slice_extracts_range() {
18622 let mask = ValidityMask::from_values(&[
18623 Scalar::Int64(1), Scalar::Null(NullKind::NaN), Scalar::Int64(3), Scalar::Int64(4), Scalar::Null(NullKind::NaN), ]);
18629 let sub = mask.slice(1, 3);
18630 assert_eq!(sub.len(), 3);
18631 assert!(!sub.get(0));
18632 assert!(sub.get(1));
18633 assert!(sub.get(2));
18634 }
18635
18636 #[test]
18637 fn validity_mask_slice_past_end_clamps() {
18638 let mask = ValidityMask::all_valid(3);
18639 let sub = mask.slice(2, 10);
18640 assert_eq!(sub.len(), 1);
18641 assert!(sub.get(0));
18642
18643 let empty = mask.slice(100, 5);
18644 assert!(empty.is_empty());
18645 }
18646
18647 #[test]
18648 fn validity_mask_concat_appends() {
18649 let a = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::NaN)]);
18650 let b = ValidityMask::from_values(&[Scalar::Int64(2), Scalar::Int64(3)]);
18651 let merged = a.concat(&b);
18652 assert_eq!(merged.len(), 4);
18653 assert!(merged.get(0));
18654 assert!(!merged.get(1));
18655 assert!(merged.get(2));
18656 assert!(merged.get(3));
18657 }
18658
18659 #[test]
18660 fn validity_mask_first_last_valid() {
18661 let mask = ValidityMask::from_values(&[
18662 Scalar::Null(NullKind::NaN),
18663 Scalar::Null(NullKind::NaN),
18664 Scalar::Int64(1),
18665 Scalar::Int64(2),
18666 Scalar::Null(NullKind::NaN),
18667 ]);
18668 assert_eq!(mask.first_valid(), Some(2));
18669 assert_eq!(mask.last_valid(), Some(3));
18670
18671 let none_set = ValidityMask::all_invalid(3);
18672 assert_eq!(none_set.first_valid(), None);
18673 assert_eq!(none_set.last_valid(), None);
18674 }
18675
18676 #[test]
18677 fn validity_mask_boundary_65_elements() {
18678 let mut values = vec![Scalar::Int64(1); 65];
18679 values[64] = Scalar::Null(NullKind::Null);
18680 let mask = ValidityMask::from_values(&values);
18681 assert_eq!(mask.len(), 65);
18682 assert_eq!(mask.count_valid(), 64);
18683 assert!(mask.get(63));
18684 assert!(!mask.get(64));
18685 }
18686
18687 #[test]
18688 fn validity_mask_equality() {
18689 let a = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::Null)]);
18690 let b = ValidityMask::from_values(&[Scalar::Int64(1), Scalar::Null(NullKind::Null)]);
18691 let c = ValidityMask::from_values(&[Scalar::Null(NullKind::Null), Scalar::Int64(1)]);
18692 assert_eq!(a, b);
18693 assert_ne!(a, c);
18694 }
18695
18696 #[test]
18697 fn validity_mask_nan_is_invalid() {
18698 let values = vec![
18699 Scalar::Float64(1.0),
18700 Scalar::Float64(f64::NAN),
18701 Scalar::Null(NullKind::NaN),
18702 ];
18703 let mask = ValidityMask::from_values(&values);
18704 assert!(mask.get(0));
18705 assert!(!mask.get(1), "Float64(NaN) should be invalid");
18706 assert!(!mask.get(2), "Null(NaN) should be invalid");
18707 assert_eq!(mask.count_valid(), 1);
18708 }
18709
18710 #[test]
18711 fn validity_mask_dense_null_half() {
18712 let values: Vec<Scalar> = (0..1000)
18713 .map(|i| {
18714 if i % 2 == 0 {
18715 Scalar::Int64(i)
18716 } else {
18717 Scalar::Null(NullKind::Null)
18718 }
18719 })
18720 .collect();
18721 let mask = ValidityMask::from_values(&values);
18722 assert_eq!(mask.len(), 1000);
18723 assert_eq!(mask.count_valid(), 500);
18724 }
18725
18726 #[test]
18729 fn column_data_float64_roundtrip() {
18730 let values = vec![
18731 Scalar::Float64(1.5),
18732 Scalar::Null(NullKind::NaN),
18733 Scalar::Float64(3.0),
18734 ];
18735 let validity = ValidityMask::from_values(&values);
18736 let data = super::ColumnData::from_scalars(&values, fp_types::DType::Float64);
18737 let back = data.to_scalars(fp_types::DType::Float64, &validity);
18738 assert_eq!(back.len(), 3);
18739 assert_eq!(back[0], Scalar::Float64(1.5));
18740 assert!(back[1].is_nan(), "position 1 should be NaN-missing");
18741 assert_eq!(back[2], Scalar::Float64(3.0));
18742 }
18743
18744 #[test]
18745 fn column_data_int64_roundtrip() {
18746 let values = vec![
18747 Scalar::Int64(10),
18748 Scalar::Null(NullKind::Null),
18749 Scalar::Int64(30),
18750 ];
18751 let validity = ValidityMask::from_values(&values);
18752 let data = super::ColumnData::from_scalars(&values, fp_types::DType::Int64);
18753 assert_eq!(data.len(), 3);
18754 let back = data.to_scalars(fp_types::DType::Int64, &validity);
18755 assert_eq!(back[0], Scalar::Int64(10));
18756 assert!(back[1].is_missing());
18757 assert_eq!(back[2], Scalar::Int64(30));
18758 }
18759
18760 #[test]
18761 fn column_data_interval_roundtrip_and_column_uniques_5g5uj() {
18762 let first = Interval::new(0.0, 1.0, IntervalClosed::Right);
18763 let second = Interval::new(1.0, 2.0, IntervalClosed::Right);
18764 let values = vec![
18765 Scalar::Interval(first),
18766 Scalar::Null(NullKind::Null),
18767 Scalar::Interval(second),
18768 Scalar::Interval(first),
18769 ];
18770 let validity = ValidityMask::from_values(&values);
18771 let data = super::ColumnData::from_scalars(&values, DType::Interval);
18772 assert_eq!(data.len(), 4);
18773 let back = data.to_scalars(DType::Interval, &validity);
18774 assert_eq!(back[0], Scalar::Interval(first));
18775 assert!(back[1].is_missing());
18776 assert_eq!(back[2], Scalar::Interval(second));
18777 assert_eq!(back[3], Scalar::Interval(first));
18778
18779 let column = Column::new(DType::Interval, values).expect("interval column");
18780 assert_eq!(column.dtype(), DType::Interval);
18781 assert!(column.has_duplicates());
18782 let uniques = column.unique().expect("unique intervals");
18783 assert_eq!(
18784 uniques.values(),
18785 &[Scalar::Interval(first), Scalar::Interval(second)]
18786 );
18787 }
18788
18789 #[test]
18790 fn vectorized_f64_addition_matches_scalar() {
18791 let left = Column::from_values(vec![
18792 Scalar::Float64(1.0),
18793 Scalar::Float64(2.0),
18794 Scalar::Float64(3.0),
18795 ])
18796 .expect("left");
18797 let right = Column::from_values(vec![
18798 Scalar::Float64(10.0),
18799 Scalar::Float64(20.0),
18800 Scalar::Float64(30.0),
18801 ])
18802 .expect("right");
18803
18804 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
18805 assert_eq!(result.values()[0], Scalar::Float64(11.0));
18806 assert_eq!(result.values()[1], Scalar::Float64(22.0));
18807 assert_eq!(result.values()[2], Scalar::Float64(33.0));
18808 }
18809
18810 #[test]
18811 fn vectorized_i64_addition_matches_scalar() {
18812 let left = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
18813 .expect("left");
18814 let right = Column::from_values(vec![
18815 Scalar::Int64(10),
18816 Scalar::Int64(20),
18817 Scalar::Int64(30),
18818 ])
18819 .expect("right");
18820
18821 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
18822 assert_eq!(result.values()[0], Scalar::Int64(11));
18823 assert_eq!(result.values()[1], Scalar::Int64(22));
18824 assert_eq!(result.values()[2], Scalar::Int64(33));
18825 }
18826
18827 #[test]
18828 fn vectorized_binary_all_valid_keeps_typed_output_lazy() {
18829 let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
18830 let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
18831
18832 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
18833
18834 assert!(result.validity().all());
18835 assert_eq!(result.as_f64_slice(), Some([11.0, 22.0, 33.0].as_slice()));
18836 assert!(matches!(
18837 &result.values,
18838 ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
18839 ));
18840 }
18841
18842 #[test]
18843 fn vectorized_binary_operation_nan_matches_scalar_validity() {
18844 let left = Column::from_f64_values(vec![f64::INFINITY]);
18845 let right = Column::from_f64_values(vec![f64::INFINITY]);
18846
18847 let result = left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub");
18848
18849 assert!(!result.validity().get(0));
18850 assert!(matches!(result.values()[0], Scalar::Float64(v) if v.is_nan()));
18851 }
18852
18853 #[test]
18854 fn vectorized_f64_with_nulls_propagates_missing() {
18855 let left = Column::from_values(vec![
18856 Scalar::Float64(1.0),
18857 Scalar::Null(NullKind::NaN),
18858 Scalar::Float64(3.0),
18859 ])
18860 .expect("left");
18861 let right = Column::from_values(vec![
18862 Scalar::Float64(10.0),
18863 Scalar::Float64(20.0),
18864 Scalar::Null(NullKind::NaN),
18865 ])
18866 .expect("right");
18867
18868 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
18869 assert_eq!(result.values()[0], Scalar::Float64(11.0));
18870 assert!(result.values()[1].is_nan(), "null+valid should be NaN");
18871 assert!(result.values()[2].is_nan(), "valid+null should be NaN");
18872 }
18873
18874 #[test]
18875 fn aligned_binary_f64_matches_reindex_then_binary_numeric() {
18876 let left = Column::new(
18877 DType::Float64,
18878 vec![
18879 Scalar::Float64(1.0),
18880 Scalar::Float64(f64::NAN),
18881 Scalar::Float64(3.5),
18882 ],
18883 )
18884 .expect("left");
18885 let right = Column::new(
18886 DType::Float64,
18887 vec![
18888 Scalar::Float64(10.0),
18889 Scalar::Float64(20.0),
18890 Scalar::Null(NullKind::NaN),
18891 ],
18892 )
18893 .expect("right");
18894 let left_positions = [Some(2), None, Some(1), Some(0)];
18895 let right_positions = [None, Some(0), Some(2), Some(1)];
18896
18897 let expected_left = left
18898 .reindex_by_positions(&left_positions)
18899 .expect("left reindex");
18900 let expected_right = right
18901 .reindex_by_positions(&right_positions)
18902 .expect("right reindex");
18903 let expected = expected_left
18904 .binary_numeric(&expected_right, ArithmeticOp::Add)
18905 .expect("generic add");
18906 let actual = left
18907 .aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
18908 .expect("aligned add");
18909
18910 assert_eq!(actual.dtype(), expected.dtype());
18911 assert_eq!(actual.values(), expected.values());
18912 assert_eq!(actual.validity().len(), expected.validity().len());
18913 for idx in 0..actual.len() {
18914 assert_eq!(actual.validity().get(idx), expected.validity().get(idx));
18915 }
18916 }
18917
18918 #[test]
18919 fn aligned_binary_f64_all_valid_keeps_typed_output_lazy() {
18920 let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
18921 let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
18922 let left_positions = [Some(0), Some(1), Some(2)];
18923 let right_positions = [Some(0), Some(1), Some(2)];
18924
18925 let actual = left
18926 .aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
18927 .expect("aligned add");
18928
18929 assert!(actual.validity().all());
18930 assert_eq!(actual.as_f64_slice(), Some([11.0, 22.0, 33.0].as_slice()));
18931 assert!(matches!(
18932 &actual.values,
18933 ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
18934 ));
18935 }
18936
18937 #[test]
18938 fn aligned_binary_f64_nullable_gaps_keep_typed_output_lazy() {
18939 let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
18940 let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
18941 let left_positions = [Some(0), Some(1), Some(2), None];
18942 let right_positions = [None, Some(0), Some(1), Some(2)];
18943
18944 let expected_left = left
18945 .reindex_by_positions(&left_positions)
18946 .expect("left reindex");
18947 let expected_right = right
18948 .reindex_by_positions(&right_positions)
18949 .expect("right reindex");
18950 let expected = expected_left
18951 .binary_numeric(&expected_right, ArithmeticOp::Add)
18952 .expect("generic add");
18953 let actual = left
18954 .aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
18955 .expect("aligned add");
18956
18957 assert_eq!(actual.dtype(), expected.dtype());
18958 assert_eq!(actual.validity(), expected.validity());
18959 assert!(matches!(
18960 &actual.values,
18961 ScalarValues::LazyNullableFloat64 { values, .. } if values.get().is_none()
18962 ));
18963 assert_eq!(actual.values(), expected.values());
18964 }
18965
18966 #[test]
18967 fn aligned_binary_f64_int64_unit_ranges_matches_position_alignment() {
18968 let left = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
18969 let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]);
18970 let left_positions = [Some(0), Some(1), Some(2), None];
18971 let right_positions = [None, Some(0), Some(1), Some(2)];
18972
18973 let expected = left
18974 .aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
18975 .expect("position aligned add");
18976 let actual = left
18977 .aligned_binary_f64_int64_unit_ranges(&right, (0, 2), (1, 3), (0, 3), ArithmeticOp::Add)
18978 .expect("unit range aligned add");
18979
18980 assert_eq!(actual.dtype(), expected.dtype());
18981 assert_eq!(actual.validity(), expected.validity());
18982 assert!(matches!(
18983 &actual.values,
18984 ScalarValues::LazyNullableFloat64 { values, .. } if values.get().is_none()
18985 ));
18986 assert_eq!(actual.values(), expected.values());
18987 }
18988
18989 #[test]
18990 fn aligned_binary_f64_operation_nan_keeps_float_nan_materialization() {
18991 let left = Column::from_f64_values(vec![f64::INFINITY]);
18992 let right = Column::from_f64_values(vec![f64::INFINITY]);
18993 let positions = [Some(0)];
18994
18995 let actual = left
18996 .aligned_binary_f64(&right, &positions, &positions, ArithmeticOp::Sub)
18997 .expect("aligned sub");
18998
18999 assert!(!actual.validity().get(0));
19000 assert!(matches!(
19001 &actual.values,
19002 ScalarValues::LazyNullableFloat64 { values, .. } if values.get().is_none()
19003 ));
19004 assert!(matches!(actual.values()[0], Scalar::Float64(value) if value.is_nan()));
19005 }
19006
19007 #[test]
19008 fn apply_f64_slices_matches_fn_pointer_per_element_f64simd() {
19009 let vals = [
19014 0.0_f64,
19015 -0.0,
19016 1.0,
19017 -1.0,
19018 2.5,
19019 -3.0,
19020 4.0,
19021 0.5,
19022 f64::NAN,
19023 f64::INFINITY,
19024 f64::NEG_INFINITY,
19025 1e300,
19026 -1e-300,
19027 ];
19028 let a: Vec<f64> = vals.to_vec();
19029 for op in [
19030 ArithmeticOp::Add,
19031 ArithmeticOp::Sub,
19032 ArithmeticOp::Mul,
19033 ArithmeticOp::Div,
19034 ArithmeticOp::Mod,
19035 ArithmeticOp::Pow,
19036 ArithmeticOp::FloorDiv,
19037 ] {
19038 for shift in 0..vals.len() {
19039 let b: Vec<f64> = (0..vals.len())
19040 .map(|i| vals[(i + shift) % vals.len()])
19041 .collect();
19042 let got = super::apply_f64_slices_nan_tracked(op, &a, &b).0;
19043 let apply = super::binary_f64_apply(op);
19044 let expected: Vec<f64> = a.iter().zip(&b).map(|(x, y)| apply(*x, *y)).collect();
19045 for i in 0..a.len() {
19046 assert_eq!(
19047 got[i].to_bits(),
19048 expected[i].to_bits(),
19049 "op={op:?} a={} b={}",
19050 a[i],
19051 b[i]
19052 );
19053 }
19054 }
19055 }
19056 }
19057
19058 #[test]
19059 fn apply_f64_slices_parallel_matches_serial_nan_tracking() {
19060 let n = (1usize << 20) + 17;
19061 let mut a: Vec<f64> = (0..n).map(|i| i as f64 * 0.25 + 1.0).collect();
19062 let mut b: Vec<f64> = (0..n).map(|i| i as f64 * 0.125 - 7.0).collect();
19063 a[1024] = f64::NAN;
19064 a[n - 3] = f64::INFINITY;
19065 b[n - 3] = f64::INFINITY;
19066
19067 let (got, got_input_nan, got_output_nan) =
19068 super::apply_f64_slices_nan_tracked(ArithmeticOp::Sub, &a, &b);
19069 let mut expected = vec![0.0_f64; n];
19070 let (expected_input_nan, expected_output_nan) =
19071 super::apply_f64_slices_nan_tracked_into(ArithmeticOp::Sub, &a, &b, &mut expected);
19072
19073 assert_eq!(got_input_nan, expected_input_nan);
19074 assert_eq!(got_output_nan, expected_output_nan);
19075 for i in 0..n {
19076 assert_eq!(got[i].to_bits(), expected[i].to_bits(), "i={i}");
19077 }
19078 }
19079
19080 #[test]
19081 fn aligned_binary_f64_same_positions_matches_identity_alignment() {
19082 let left = Column::new(
19083 DType::Float64,
19084 vec![
19085 Scalar::Float64(1.0),
19086 Scalar::Float64(f64::NAN),
19087 Scalar::Float64(3.0),
19088 ],
19089 )
19090 .expect("left");
19091 let right = Column::new(
19092 DType::Float64,
19093 vec![
19094 Scalar::Float64(10.0),
19095 Scalar::Float64(20.0),
19096 Scalar::Null(NullKind::NaN),
19097 ],
19098 )
19099 .expect("right");
19100 let positions = [Some(0), Some(1), Some(2)];
19101
19102 let expected = left
19103 .aligned_binary_f64(&right, &positions, &positions, ArithmeticOp::Add)
19104 .expect("identity aligned add");
19105 let actual = left
19106 .aligned_binary_f64_same_positions(&right, ArithmeticOp::Add)
19107 .expect("same-position add");
19108
19109 assert_eq!(actual.dtype(), expected.dtype());
19110 assert_eq!(actual.values(), expected.values());
19111 for idx in 0..actual.len() {
19112 assert_eq!(actual.validity().get(idx), expected.validity().get(idx));
19113 }
19114 }
19115
19116 #[test]
19117 fn aligned_binary_f64_same_positions_matches_general_path_for_all_ops_with_nan_inf() {
19118 let make = |data: Vec<f64>| -> Column {
19131 let len = data.len();
19132 Column {
19133 dtype: DType::Float64,
19134 values: ScalarValues::lazy_all_valid_float64(data),
19135 validity: ValidityMask::all_valid(len),
19136 data: None,
19137 }
19138 };
19139 let left = make(vec![1.0, f64::NAN, 2.0, f64::INFINITY, 1.0, f64::NAN, -3.5]);
19140 let right = make(vec![10.0, 3.0, f64::NAN, f64::INFINITY, f64::NAN, 0.0, 2.0]);
19141 assert!(left.validity().all());
19142 assert!(right.validity().all());
19143 let n = left.len();
19144 let positions: Vec<Option<usize>> = (0..n).map(Some).collect();
19145
19146 for op in [
19147 ArithmeticOp::Add,
19148 ArithmeticOp::Sub,
19149 ArithmeticOp::Mul,
19150 ArithmeticOp::Div,
19151 ArithmeticOp::Mod,
19152 ArithmeticOp::Pow,
19153 ArithmeticOp::FloorDiv,
19154 ] {
19155 let expected = left
19156 .aligned_binary_f64(&right, &positions, &positions, op)
19157 .expect("general aligned path");
19158 let actual = left
19159 .aligned_binary_f64_same_positions(&right, op)
19160 .expect("same-position fast path");
19161
19162 assert_eq!(actual.dtype(), expected.dtype(), "dtype op={op:?}");
19163 assert_eq!(actual.len(), expected.len(), "len op={op:?}");
19164 let got = actual.values();
19165 let want = expected.values();
19166 for i in 0..n {
19167 match (&got[i], &want[i]) {
19169 (Scalar::Float64(g), Scalar::Float64(w)) => {
19170 assert_eq!(g.to_bits(), w.to_bits(), "value bits op={op:?} slot={i}")
19171 }
19172 (g, w) => assert_eq!(g, w, "scalar op={op:?} slot={i}"),
19173 }
19174 assert_eq!(
19175 actual.validity().get(i),
19176 expected.validity().get(i),
19177 "validity op={op:?} slot={i}"
19178 );
19179 }
19180 }
19181 }
19182
19183 #[test]
19184 fn aligned_binary_f64_borrows_lazy_float64_clone_data() {
19185 let left = Column::from_f64_values(vec![1.0, f64::NAN, 4.0]).clone();
19186 let right = Column::from_f64_values(vec![10.0, 20.0, 30.0]).clone();
19187
19188 assert!(left.data.is_none());
19189 assert!(right.data.is_none());
19190 assert!(matches!(
19191 &left.values,
19192 ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
19193 ));
19194 assert!(matches!(
19195 &right.values,
19196 ScalarValues::LazyAllValidFloat64 { values, .. } if values.get().is_none()
19197 ));
19198
19199 let left_positions = [Some(0), Some(1), Some(2), None];
19200 let right_positions = [Some(2), Some(1), None, Some(0)];
19201 let actual = left
19202 .aligned_binary_f64(&right, &left_positions, &right_positions, ArithmeticOp::Add)
19203 .expect("aligned add");
19204
19205 assert_eq!(
19206 actual.values(),
19207 &[
19208 Scalar::Float64(31.0),
19209 Scalar::Null(NullKind::NaN),
19210 Scalar::Null(NullKind::NaN),
19211 Scalar::Null(NullKind::NaN),
19212 ]
19213 );
19214 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &left.values {
19215 assert!(values.get().is_none());
19216 }
19217 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &right.values {
19218 assert!(values.get().is_none());
19219 }
19220 }
19221
19222 #[test]
19223 fn from_f64_values_marks_nan_missing_like_scalar_path() {
19224 let typed = Column::from_f64_values(vec![1.0, f64::NAN, 3.0, f64::NAN]);
19228 let scalar = Column::new(
19229 DType::Float64,
19230 vec![
19231 Scalar::Float64(1.0),
19232 Scalar::Float64(f64::NAN),
19233 Scalar::Float64(3.0),
19234 Scalar::Float64(f64::NAN),
19235 ],
19236 )
19237 .expect("scalar col");
19238
19239 for idx in 0..typed.len() {
19241 assert_eq!(
19242 typed.validity().get(idx),
19243 scalar.validity().get(idx),
19244 "validity mismatch at {idx}"
19245 );
19246 }
19247 assert!(typed.validity().get(0));
19248 assert!(!typed.validity().get(1));
19249 assert!(typed.validity().get(2));
19250 assert!(!typed.validity().get(3));
19251 assert_eq!(typed.validity().count_valid(), 2);
19252
19253 assert!(typed.as_f64_slice().is_none());
19256
19257 let clean = Column::from_f64_values(vec![1.0, 2.0, 3.0]);
19259 assert!(clean.validity().all());
19260 assert_eq!(clean.as_f64_slice(), Some([1.0, 2.0, 3.0].as_slice()));
19261 }
19262
19263 #[test]
19264 fn repeated_slices_float64_exposes_cached_typed_slice() {
19265 let column = Column::from_f64_repeated_slices_shared(
19266 vec![11.0, 22.0, 33.0, 44.0],
19267 Arc::from([(1usize, 2usize), (0, 3), (3, 1)].as_slice()),
19268 6,
19269 );
19270 let expected = [22.0, 33.0, 11.0, 22.0, 33.0, 44.0];
19271
19272 assert_eq!(column.as_f64_slice(), Some(expected.as_slice()));
19273 assert_eq!(column.as_f64_slice(), Some(expected.as_slice()));
19274 assert_eq!(column.all_valid_f64_to_vec(), Some(expected.to_vec()));
19275 assert_eq!(
19276 column.values(),
19277 &[
19278 Scalar::Float64(22.0),
19279 Scalar::Float64(33.0),
19280 Scalar::Float64(11.0),
19281 Scalar::Float64(22.0),
19282 Scalar::Float64(33.0),
19283 Scalar::Float64(44.0),
19284 ]
19285 );
19286 }
19287
19288 #[test]
19289 fn repeated_slices_float64_expands_periodic_prefix() {
19290 let column = Column::from_f64_repeated_slices_shared(
19291 vec![1.0, 2.0, 3.0],
19292 Arc::from([(0usize, 3usize), (0, 3), (0, 2)].as_slice()),
19293 8,
19294 );
19295
19296 assert_eq!(
19297 column.as_f64_slice(),
19298 Some([1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0].as_slice())
19299 );
19300 assert_eq!(
19301 column.all_valid_f64_to_vec(),
19302 Some(vec![1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0])
19303 );
19304 }
19305
19306 #[test]
19307 fn finite_float64_arc_view_uses_constructor_witness() {
19308 let finite = Column::from_values(vec![
19309 Scalar::Float64(1.0),
19310 Scalar::Float64(-0.0),
19311 Scalar::Float64(3.5),
19312 ])
19313 .expect("finite float column");
19314 assert!(
19315 finite.as_f64_finite_arc_view_source(3).is_some(),
19316 "all-finite Float64 columns should expose the finite Arc view"
19317 );
19318 assert!(
19319 finite.clone().as_f64_finite_arc_view_source(3).is_some(),
19320 "finite witness should survive Column::clone"
19321 );
19322
19323 let with_infinity =
19324 Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(f64::INFINITY)])
19325 .expect("infinite float column");
19326 assert!(
19327 with_infinity.as_f64_finite_arc_view_source(2).is_none(),
19328 "infinity is valid Float64 data but must not enter finite dot fast paths"
19329 );
19330
19331 let with_nan = Column::from_f64_values(vec![1.0, f64::NAN]);
19332 assert!(
19333 with_nan.as_f64_finite_arc_view_source(2).is_none(),
19334 "NaN-bearing Float64 columns are nullable and must not expose all-valid views"
19335 );
19336 }
19337
19338 #[test]
19339 fn from_f64_all_valid_chunks_materializes_in_chunk_order() {
19340 let first: Arc<[f64]> = Arc::from(vec![9.0, 1.0, 2.0, 8.0]);
19341 let second: Arc<[f64]> = Arc::from(vec![3.0, 4.0, 5.0]);
19342 let column = Column::from_f64_all_valid_chunks(
19343 vec![(Arc::clone(&first), 1, 2), (Arc::clone(&second), 0, 3)],
19344 5,
19345 );
19346
19347 assert_eq!(column.len(), 5);
19348 assert!(column.validity().all());
19349 assert_eq!(
19350 column.as_f64_slice(),
19351 Some([1.0, 2.0, 3.0, 4.0, 5.0].as_slice())
19352 );
19353 assert_eq!(
19354 column.values(),
19355 &[
19356 Scalar::Float64(1.0),
19357 Scalar::Float64(2.0),
19358 Scalar::Float64(3.0),
19359 Scalar::Float64(4.0),
19360 Scalar::Float64(5.0),
19361 ]
19362 );
19363 }
19364
19365 #[test]
19366 fn from_i64_all_valid_chunks_materializes_in_chunk_order() {
19367 let first: Arc<[i64]> = Arc::from(vec![99, 1, 2, 88]);
19368 let second: Arc<[i64]> = Arc::from(vec![3, 4, 5]);
19369 let column = Column::from_i64_all_valid_chunks(
19370 vec![(Arc::clone(&first), 1, 2), (Arc::clone(&second), 0, 3)],
19371 5,
19372 );
19373
19374 assert_eq!(column.len(), 5);
19375 assert!(column.validity().all());
19376 assert_eq!(column.as_i64_slice(), Some([1, 2, 3, 4, 5].as_slice()));
19377 assert_eq!(
19378 column.values(),
19379 &[
19380 Scalar::Int64(1),
19381 Scalar::Int64(2),
19382 Scalar::Int64(3),
19383 Scalar::Int64(4),
19384 Scalar::Int64(5),
19385 ]
19386 );
19387 assert_eq!(column.clone(), Column::from_i64_values(vec![1, 2, 3, 4, 5]));
19388 }
19389
19390 #[test]
19391 fn from_f64_all_valid_dot_product_materializes_left_fold_rows() {
19392 let a0: Arc<[f64]> = Arc::from(vec![99.0, 1.0, 3.0, 5.0]);
19393 let a1: Arc<[f64]> = Arc::from(vec![2.0, 4.0, 6.0]);
19394 let b: Arc<[f64]> = Arc::from(vec![10.0, 0.5]);
19395 let column = Column::from_f64_all_valid_dot_product(
19396 vec![(Arc::clone(&a0), 1), (Arc::clone(&a1), 0)],
19397 b,
19398 3,
19399 );
19400
19401 assert_eq!(column.len(), 3);
19402 assert!(column.validity().all());
19403 assert_eq!(column.as_f64_slice(), Some([11.0, 32.0, 53.0].as_slice()));
19404 assert_eq!(
19405 column.values(),
19406 &[
19407 Scalar::Float64(11.0),
19408 Scalar::Float64(32.0),
19409 Scalar::Float64(53.0),
19410 ]
19411 );
19412 }
19413
19414 #[test]
19415 fn vectorized_i64_with_nulls_propagates_missing() {
19416 let left = Column::from_values(vec![
19417 Scalar::Int64(1),
19418 Scalar::Null(NullKind::Null),
19419 Scalar::Int64(3),
19420 ])
19421 .expect("left");
19422 let right = Column::from_values(vec![
19423 Scalar::Int64(10),
19424 Scalar::Int64(20),
19425 Scalar::Null(NullKind::Null),
19426 ])
19427 .expect("right");
19428
19429 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
19430 assert_eq!(result.values()[0], Scalar::Int64(11));
19431 assert!(result.values()[1].is_missing());
19432 assert!(result.values()[2].is_missing());
19433 }
19434
19435 #[test]
19436 fn column_from_values_preserves_mixed_utf8_numeric_scalars() {
19437 let column = Column::from_values(vec![Scalar::Utf8("x".into()), Scalar::Int64(1)])
19438 .expect("mixed object-like constructor should succeed");
19439
19440 assert_eq!(column.dtype(), DType::Utf8);
19441 assert_eq!(
19442 column.values(),
19443 &[Scalar::Utf8("x".into()), Scalar::Int64(1)]
19444 );
19445 }
19446
19447 #[test]
19448 fn vectorized_division_promotes_to_float64() {
19449 let left = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(21)]).expect("left");
19450 let right = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(7)]).expect("right");
19451
19452 let result = left.binary_numeric(&right, ArithmeticOp::Div).expect("div");
19453 assert_eq!(result.dtype(), fp_types::DType::Float64);
19455 assert!(matches!(result.values()[0], Scalar::Float64(v) if (v - 10.0/3.0).abs() < 1e-10));
19456 assert_eq!(result.values()[1], Scalar::Float64(3.0));
19457 }
19458
19459 #[test]
19460 fn vectorized_all_four_ops_f64() {
19461 let left = Column::from_values(vec![Scalar::Float64(10.0)]).expect("left");
19462 let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
19463
19464 let add = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
19465 let sub = left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub");
19466 let mul = left.binary_numeric(&right, ArithmeticOp::Mul).expect("mul");
19467 let div = left.binary_numeric(&right, ArithmeticOp::Div).expect("div");
19468
19469 assert_eq!(add.values()[0], Scalar::Float64(13.0));
19470 assert_eq!(sub.values()[0], Scalar::Float64(7.0));
19471 assert_eq!(mul.values()[0], Scalar::Float64(30.0));
19472 assert!(matches!(div.values()[0], Scalar::Float64(v) if (v - 10.0/3.0).abs() < 1e-10));
19473 }
19474
19475 #[test]
19476 fn pandas_arithmetic_aliases_match_binary_numeric() {
19477 let left = Column::from_values(vec![Scalar::Float64(10.0)]).expect("left");
19478 let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
19479
19480 assert_eq!(
19481 left.add(&right).expect("add"),
19482 left.binary_numeric(&right, ArithmeticOp::Add).expect("add")
19483 );
19484 assert_eq!(
19485 left.sub(&right).expect("sub"),
19486 left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub")
19487 );
19488 assert_eq!(
19489 left.mul(&right).expect("mul"),
19490 left.binary_numeric(&right, ArithmeticOp::Mul).expect("mul")
19491 );
19492 assert_eq!(
19493 left.div(&right).expect("div"),
19494 left.binary_numeric(&right, ArithmeticOp::Div).expect("div")
19495 );
19496 assert_eq!(
19497 left.divide(&right).expect("divide"),
19498 left.div(&right).expect("div")
19499 );
19500 }
19501
19502 #[test]
19503 fn remaining_pandas_arithmetic_aliases_match_binary_numeric() {
19504 let left = Column::from_values(vec![Scalar::Float64(10.0)]).expect("left");
19505 let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
19506
19507 assert_eq!(
19508 left.subtract(&right).expect("subtract"),
19509 left.sub(&right).expect("sub")
19510 );
19511 assert_eq!(
19512 left.multiply(&right).expect("multiply"),
19513 left.mul(&right).expect("mul")
19514 );
19515 assert_eq!(
19516 left.truediv(&right).expect("truediv"),
19517 left.div(&right).expect("div")
19518 );
19519 assert_eq!(
19520 left.floordiv(&right).expect("floordiv"),
19521 left.binary_numeric(&right, ArithmeticOp::FloorDiv)
19522 .expect("floordiv")
19523 );
19524 assert_eq!(
19525 left.r#mod(&right).expect("mod"),
19526 left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod")
19527 );
19528 assert_eq!(
19529 left.pow(&right).expect("pow"),
19530 left.binary_numeric(&right, ArithmeticOp::Pow).expect("pow")
19531 );
19532 }
19533
19534 #[test]
19535 fn pandas_reverse_arithmetic_aliases_swap_operands() {
19536 let series = Column::from_values(vec![Scalar::Float64(10.0)]).expect("series");
19537 let other = Column::from_values(vec![Scalar::Float64(3.0)]).expect("other");
19538
19539 assert_eq!(
19540 series.radd(&other).expect("radd"),
19541 other
19542 .binary_numeric(&series, ArithmeticOp::Add)
19543 .expect("add")
19544 );
19545 assert_eq!(
19546 series.rsub(&other).expect("rsub"),
19547 other
19548 .binary_numeric(&series, ArithmeticOp::Sub)
19549 .expect("sub")
19550 );
19551 assert_eq!(
19552 series.rmul(&other).expect("rmul"),
19553 other
19554 .binary_numeric(&series, ArithmeticOp::Mul)
19555 .expect("mul")
19556 );
19557 assert_eq!(
19558 series.rdiv(&other).expect("rdiv"),
19559 other
19560 .binary_numeric(&series, ArithmeticOp::Div)
19561 .expect("div")
19562 );
19563 assert_eq!(
19564 series.rtruediv(&other).expect("rtruediv"),
19565 series.rdiv(&other).expect("rdiv")
19566 );
19567 assert_eq!(
19568 series.rfloordiv(&other).expect("rfloordiv"),
19569 other
19570 .binary_numeric(&series, ArithmeticOp::FloorDiv)
19571 .expect("floordiv")
19572 );
19573 assert_eq!(
19574 series.rmod(&other).expect("rmod"),
19575 other
19576 .binary_numeric(&series, ArithmeticOp::Mod)
19577 .expect("mod")
19578 );
19579 assert_eq!(
19580 series.rpow(&other).expect("rpow"),
19581 other
19582 .binary_numeric(&series, ArithmeticOp::Pow)
19583 .expect("pow")
19584 );
19585 }
19586
19587 #[test]
19588 fn vectorized_f64_mod_pow_floordiv() {
19589 let left = Column::from_values(vec![
19590 Scalar::Float64(10.0),
19591 Scalar::Float64(2.0),
19592 Scalar::Float64(-3.0),
19593 ])
19594 .expect("left");
19595 let right = Column::from_values(vec![
19596 Scalar::Float64(3.0),
19597 Scalar::Float64(3.0),
19598 Scalar::Float64(2.0),
19599 ])
19600 .expect("right");
19601
19602 let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
19603 assert_eq!(modulo.dtype(), DType::Float64);
19604 assert!(matches!(modulo.values()[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
19605 assert!(matches!(modulo.values()[1], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
19606 assert!(matches!(modulo.values()[2], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
19607
19608 let pow = left.binary_numeric(&right, ArithmeticOp::Pow).expect("pow");
19609 assert_eq!(pow.dtype(), DType::Float64);
19610 assert!(matches!(pow.values()[0], Scalar::Float64(v) if (v - 1000.0).abs() < 1e-10));
19611 assert!(matches!(pow.values()[1], Scalar::Float64(v) if (v - 8.0).abs() < 1e-10));
19612 assert!(matches!(pow.values()[2], Scalar::Float64(v) if (v - 9.0).abs() < 1e-10));
19613
19614 let floordiv = left
19615 .binary_numeric(&right, ArithmeticOp::FloorDiv)
19616 .expect("floordiv");
19617 assert_eq!(floordiv.dtype(), DType::Float64);
19618 assert!(matches!(floordiv.values()[0], Scalar::Float64(v) if (v - 3.0).abs() < 1e-10));
19619 assert!(matches!(floordiv.values()[1], Scalar::Float64(v) if (v - 0.0).abs() < 1e-10));
19620 assert!(matches!(floordiv.values()[2], Scalar::Float64(v) if (v - -2.0).abs() < 1e-10));
19621 }
19622
19623 #[test]
19624 fn int_pow_stays_int64_and_negative_exponent_raises_3w0xn() {
19625 let base = Column::from_values(vec![Scalar::Int64(2), Scalar::Int64(3), Scalar::Int64(10)])
19628 .expect("base");
19629 let exp = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(2), Scalar::Int64(2)])
19630 .expect("exp");
19631 let pow = base
19632 .binary_numeric(&exp, ArithmeticOp::Pow)
19633 .expect("int pow");
19634 assert_eq!(pow.dtype(), DType::Int64);
19635 assert_eq!(pow.values()[0], Scalar::Int64(8));
19636 assert_eq!(pow.values()[1], Scalar::Int64(9));
19637 assert_eq!(pow.values()[2], Scalar::Int64(100));
19638
19639 let neg_exp =
19641 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(-1), Scalar::Int64(2)])
19642 .expect("neg_exp");
19643 let err = base
19644 .binary_numeric(&neg_exp, ArithmeticOp::Pow)
19645 .expect_err("negative integer power must raise");
19646 assert!(matches!(err, ColumnError::NegativeIntegerPower));
19647
19648 let exp_f = Column::from_values(vec![
19650 Scalar::Float64(3.0),
19651 Scalar::Float64(2.0),
19652 Scalar::Float64(2.0),
19653 ])
19654 .expect("exp_f");
19655 let pow_f = base
19656 .binary_numeric(&exp_f, ArithmeticOp::Pow)
19657 .expect("mixed int/float pow");
19658 assert_eq!(pow_f.dtype(), DType::Float64);
19659 assert!(matches!(pow_f.values()[0], Scalar::Float64(v) if (v - 8.0).abs() < 1e-10));
19660 }
19661
19662 #[test]
19663 fn int64_mod_floordiv_preserves_dtype() {
19664 let left = Column::from_values(vec![
19666 Scalar::Int64(10),
19667 Scalar::Int64(20),
19668 Scalar::Int64(30),
19669 ])
19670 .expect("left");
19671 let right = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(7), Scalar::Int64(4)])
19672 .expect("right");
19673
19674 let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
19675 assert_eq!(modulo.dtype(), DType::Int64, "mod should preserve Int64");
19676 assert_eq!(modulo.values()[0], Scalar::Int64(1));
19677 assert_eq!(modulo.values()[1], Scalar::Int64(6));
19678 assert_eq!(modulo.values()[2], Scalar::Int64(2));
19679
19680 let floordiv = left
19681 .binary_numeric(&right, ArithmeticOp::FloorDiv)
19682 .expect("floordiv");
19683 assert_eq!(
19684 floordiv.dtype(),
19685 DType::Int64,
19686 "floordiv should preserve Int64"
19687 );
19688 assert_eq!(floordiv.values()[0], Scalar::Int64(3));
19689 assert_eq!(floordiv.values()[1], Scalar::Int64(2));
19690 assert_eq!(floordiv.values()[2], Scalar::Int64(7));
19691 }
19692
19693 #[test]
19694 fn int64_mod_floordiv_match_pandas_negative_operand_signs() {
19695 let left = Column::from_values(vec![
19696 Scalar::Int64(7),
19697 Scalar::Int64(-7),
19698 Scalar::Int64(-7),
19699 Scalar::Int64(7),
19700 ])
19701 .expect("left");
19702 let right = Column::from_values(vec![
19703 Scalar::Int64(-3),
19704 Scalar::Int64(3),
19705 Scalar::Int64(-3),
19706 Scalar::Int64(3),
19707 ])
19708 .expect("right");
19709
19710 let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
19711 assert_eq!(modulo.dtype(), DType::Int64);
19712 assert_eq!(
19713 modulo.values(),
19714 &[
19715 Scalar::Int64(-2),
19716 Scalar::Int64(2),
19717 Scalar::Int64(-1),
19718 Scalar::Int64(1)
19719 ]
19720 );
19721
19722 let floordiv = left
19723 .binary_numeric(&right, ArithmeticOp::FloorDiv)
19724 .expect("floordiv");
19725 assert_eq!(floordiv.dtype(), DType::Int64);
19726 assert_eq!(
19727 floordiv.values(),
19728 &[
19729 Scalar::Int64(-3),
19730 Scalar::Int64(-3),
19731 Scalar::Int64(2),
19732 Scalar::Int64(2)
19733 ]
19734 );
19735 }
19736
19737 #[test]
19738 fn float64_mod_floordiv_match_pandas_negative_operand_signs() {
19739 let left = Column::from_values(vec![
19740 Scalar::Float64(7.0),
19741 Scalar::Float64(-7.0),
19742 Scalar::Float64(-7.0),
19743 Scalar::Float64(7.0),
19744 ])
19745 .expect("left");
19746 let right = Column::from_values(vec![
19747 Scalar::Float64(-3.0),
19748 Scalar::Float64(3.0),
19749 Scalar::Float64(-3.0),
19750 Scalar::Float64(3.0),
19751 ])
19752 .expect("right");
19753
19754 let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
19755 assert_eq!(modulo.dtype(), DType::Float64);
19756 assert!(matches!(modulo.values()[0], Scalar::Float64(v) if (v + 2.0).abs() < 1e-10));
19757 assert!(matches!(modulo.values()[1], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
19758 assert!(matches!(modulo.values()[2], Scalar::Float64(v) if (v + 1.0).abs() < 1e-10));
19759 assert!(matches!(modulo.values()[3], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
19760
19761 let floordiv = left
19762 .binary_numeric(&right, ArithmeticOp::FloorDiv)
19763 .expect("floordiv");
19764 assert_eq!(floordiv.dtype(), DType::Float64);
19765 assert!(matches!(floordiv.values()[0], Scalar::Float64(v) if (v + 3.0).abs() < 1e-10));
19766 assert!(matches!(floordiv.values()[1], Scalar::Float64(v) if (v + 3.0).abs() < 1e-10));
19767 assert!(matches!(floordiv.values()[2], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
19768 assert!(matches!(floordiv.values()[3], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
19769 }
19770
19771 #[test]
19772 fn int64_mod_floordiv_with_zero_promotes_to_float() {
19773 let left = Column::from_values(vec![
19775 Scalar::Int64(10),
19776 Scalar::Int64(20),
19777 Scalar::Int64(30),
19778 ])
19779 .expect("left");
19780 let right = Column::from_values(vec![
19781 Scalar::Int64(3),
19782 Scalar::Int64(0), Scalar::Int64(4),
19784 ])
19785 .expect("right");
19786
19787 let modulo = left.binary_numeric(&right, ArithmeticOp::Mod).expect("mod");
19788 assert_eq!(
19789 modulo.dtype(),
19790 DType::Float64,
19791 "mod with zero should promote to Float64"
19792 );
19793 assert!(matches!(modulo.values()[0], Scalar::Float64(v) if (v - 1.0).abs() < 1e-10));
19794 assert!(matches!(modulo.values()[1], Scalar::Float64(v) if v.is_nan()));
19795 assert!(matches!(modulo.values()[2], Scalar::Float64(v) if (v - 2.0).abs() < 1e-10));
19796
19797 let floordiv = left
19798 .binary_numeric(&right, ArithmeticOp::FloorDiv)
19799 .expect("floordiv");
19800 assert_eq!(
19801 floordiv.dtype(),
19802 DType::Float64,
19803 "floordiv with zero should promote to Float64"
19804 );
19805 assert!(matches!(floordiv.values()[0], Scalar::Float64(v) if (v - 3.0).abs() < 1e-10));
19806 assert!(matches!(floordiv.values()[1], Scalar::Float64(v) if v.is_infinite()));
19807 assert!(matches!(floordiv.values()[2], Scalar::Float64(v) if (v - 7.0).abs() < 1e-10));
19808 }
19809
19810 #[test]
19811 fn vectorized_empty_columns() {
19812 let left = Column::from_values(vec![]).expect("left");
19813 let right = Column::from_values(vec![]).expect("right");
19814 let result = left
19815 .binary_numeric(&right, ArithmeticOp::Add)
19816 .expect("add empty");
19817 assert!(result.is_empty());
19818 }
19819
19820 #[test]
19821 fn vectorized_large_column_matches_scalar_semantics() {
19822 let n = 4096;
19824 let left_values: Vec<Scalar> = (0..n).map(|i| Scalar::Float64(i as f64)).collect();
19825 let right_values: Vec<Scalar> = (0..n).map(|i| Scalar::Float64((n - i) as f64)).collect();
19826
19827 let left = Column::from_values(left_values).expect("left");
19828 let right = Column::from_values(right_values).expect("right");
19829
19830 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
19831
19832 for (i, v) in result.values().iter().enumerate() {
19834 assert_eq!(*v, Scalar::Float64(n as f64), "position {i} should be {n}");
19835 }
19836 }
19837
19838 #[test]
19839 fn vectorized_nan_vs_null_distinction_preserved() {
19840 let left =
19842 Column::from_values(vec![Scalar::Float64(f64::NAN), Scalar::Null(NullKind::NaN)])
19843 .expect("left");
19844 let right =
19845 Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("right");
19846
19847 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
19848 assert!(result.values()[0].is_nan(), "NaN + valid = NaN");
19850 assert!(result.values()[1].is_nan(), "NaN-null + valid = NaN");
19851 }
19852
19853 #[test]
19854 fn vectorized_mixed_type_falls_back_to_scalar() {
19855 let left = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("left");
19857 let right =
19858 Column::from_values(vec![Scalar::Float64(0.5), Scalar::Float64(1.5)]).expect("right");
19859
19860 let result = left.binary_numeric(&right, ArithmeticOp::Add).expect("add");
19861 assert_eq!(result.dtype(), fp_types::DType::Float64);
19862 assert_eq!(result.values()[0], Scalar::Float64(1.5));
19863 assert_eq!(result.values()[1], Scalar::Float64(3.5));
19864 }
19865
19866 #[test]
19867 fn vectorized_i64_sub_and_mul() {
19868 let left = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("left");
19869 let right = Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(5)]).expect("right");
19870
19871 let sub = left.binary_numeric(&right, ArithmeticOp::Sub).expect("sub");
19872 assert_eq!(sub.values()[0], Scalar::Int64(7));
19873 assert_eq!(sub.values()[1], Scalar::Int64(15));
19874
19875 let mul = left.binary_numeric(&right, ArithmeticOp::Mul).expect("mul");
19876 assert_eq!(mul.values()[0], Scalar::Int64(30));
19877 assert_eq!(mul.values()[1], Scalar::Int64(100));
19878 }
19879
19880 mod crack_tests {
19883 use fp_types::Scalar;
19884
19885 use super::super::*;
19886
19887 fn make_column(values: &[f64]) -> Column {
19888 Column::from_values(values.iter().map(|&v| Scalar::Float64(v)).collect()).expect("col")
19889 }
19890
19891 #[test]
19892 fn crack_filter_gt_basic() {
19893 let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
19894 let mut crack = CrackIndex::new(col.len());
19895
19896 let gt3 = crack.filter_gt(&col, 3.0);
19897 let mut gt3_vals: Vec<f64> = gt3
19898 .iter()
19899 .map(|&i| col.values()[i].to_f64().unwrap())
19900 .collect();
19901 gt3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
19902 assert_eq!(gt3_vals, vec![5.0, 7.0]);
19903 assert_eq!(crack.num_cracks(), 1);
19904 }
19905
19906 #[test]
19907 fn crack_filter_lte_basic() {
19908 let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
19909 let mut crack = CrackIndex::new(col.len());
19910
19911 let lte3 = crack.filter_lte(&col, 3.0);
19912 let mut lte3_vals: Vec<f64> = lte3
19913 .iter()
19914 .map(|&i| col.values()[i].to_f64().unwrap())
19915 .collect();
19916 lte3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
19917 assert_eq!(lte3_vals, vec![1.0, 2.0, 3.0]);
19918 }
19919
19920 #[test]
19921 fn crack_filter_eq() {
19922 let col = make_column(&[1.0, 3.0, 3.0, 7.0, 3.0]);
19923 let mut crack = CrackIndex::new(col.len());
19924
19925 let eq3 = crack.filter_eq(&col, 3.0);
19926 assert_eq!(eq3.len(), 3, "three values equal to 3.0");
19927 for &idx in &eq3 {
19928 assert_eq!(col.values()[idx].to_f64().unwrap(), 3.0);
19929 }
19930 }
19931
19932 #[test]
19933 fn crack_filter_lt() {
19934 let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
19935 let mut crack = CrackIndex::new(col.len());
19936
19937 let lt3 = crack.filter_lt(&col, 3.0);
19938 let mut lt3_vals: Vec<f64> = lt3
19939 .iter()
19940 .map(|&i| col.values()[i].to_f64().unwrap())
19941 .collect();
19942 lt3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
19943 assert_eq!(lt3_vals, vec![1.0, 2.0]);
19944 }
19945
19946 #[test]
19947 fn crack_filter_gte() {
19948 let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
19949 let mut crack = CrackIndex::new(col.len());
19950
19951 let gte3 = crack.filter_gte(&col, 3.0);
19952 let mut gte3_vals: Vec<f64> = gte3
19953 .iter()
19954 .map(|&i| col.values()[i].to_f64().unwrap())
19955 .collect();
19956 gte3_vals.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
19957 assert_eq!(gte3_vals, vec![3.0, 5.0, 7.0]);
19958 }
19959
19960 #[test]
19961 fn crack_progressive_refinement() {
19962 let col = make_column(&[10.0, 2.0, 8.0, 4.0, 6.0, 1.0, 9.0, 3.0, 7.0, 5.0]);
19963 let mut crack = CrackIndex::new(col.len());
19964
19965 let gt5 = crack.filter_gt(&col, 5.0);
19967 assert_eq!(gt5.len(), 5);
19968 assert_eq!(crack.num_cracks(), 1);
19969
19970 let gt3 = crack.filter_gt(&col, 3.0);
19972 assert_eq!(gt3.len(), 7); assert_eq!(crack.num_cracks(), 2);
19974
19975 let gt7 = crack.filter_gt(&col, 7.0);
19977 assert_eq!(gt7.len(), 3); assert_eq!(crack.num_cracks(), 3);
19979 }
19980
19981 #[test]
19982 fn crack_duplicate_crack_point_is_idempotent() {
19983 let col = make_column(&[1.0, 5.0, 3.0, 7.0, 2.0]);
19984 let mut crack = CrackIndex::new(col.len());
19985
19986 let gt3_first = crack.filter_gt(&col, 3.0);
19987 let gt3_second = crack.filter_gt(&col, 3.0);
19988
19989 let mut a: Vec<usize> = gt3_first;
19991 let mut b: Vec<usize> = gt3_second;
19992 a.sort_unstable();
19993 b.sort_unstable();
19994 assert_eq!(a, b);
19995 assert_eq!(crack.num_cracks(), 1, "no duplicate crack point");
19996 }
19997
19998 #[test]
19999 fn crack_empty_column() {
20000 let col = make_column(&[]);
20001 let mut crack = CrackIndex::new(col.len());
20002
20003 assert!(crack.filter_gt(&col, 5.0).is_empty());
20004 assert!(crack.filter_lte(&col, 5.0).is_empty());
20005 }
20006
20007 #[test]
20008 fn crack_single_element() {
20009 let col = make_column(&[42.0]);
20010 let mut crack = CrackIndex::new(col.len());
20011
20012 assert!(crack.filter_gt(&col, 42.0).is_empty());
20013 assert_eq!(crack.filter_lte(&col, 42.0).len(), 1);
20014 assert_eq!(crack.filter_eq(&col, 42.0).len(), 1);
20015 }
20016
20017 #[test]
20018 fn crack_all_same_values() {
20019 let col = make_column(&[5.0, 5.0, 5.0, 5.0]);
20020 let mut crack = CrackIndex::new(col.len());
20021
20022 assert!(crack.filter_gt(&col, 5.0).is_empty());
20023 assert_eq!(crack.filter_lte(&col, 5.0).len(), 4);
20024 assert_eq!(crack.filter_eq(&col, 5.0).len(), 4);
20025 }
20026
20027 #[test]
20028 fn crack_isomorphism_with_full_scan() {
20029 let col = make_column(&[10.0, 2.0, 8.0, 4.0, 6.0, 1.0, 9.0, 3.0, 7.0, 5.0]);
20031 let mut crack = CrackIndex::new(col.len());
20032
20033 for pivot in [1.0, 3.0, 5.0, 7.0, 9.0, 0.0, 11.0] {
20034 let mut cracked: Vec<usize> = crack.filter_gt(&col, pivot);
20035 cracked.sort_unstable();
20036
20037 let mut naive: Vec<usize> = (0..col.len())
20038 .filter(|&i| col.values()[i].to_f64().unwrap() > pivot)
20039 .collect();
20040 naive.sort_unstable();
20041
20042 assert_eq!(
20043 cracked, naive,
20044 "cracked vs naive mismatch for pivot={pivot}"
20045 );
20046 }
20047 }
20048
20049 #[test]
20050 fn crack_int64_column() {
20051 let col = Column::from_values(vec![
20052 Scalar::Int64(10),
20053 Scalar::Int64(5),
20054 Scalar::Int64(3),
20055 Scalar::Int64(8),
20056 Scalar::Int64(1),
20057 ])
20058 .expect("col");
20059 let mut crack = CrackIndex::new(col.len());
20060
20061 let gt5 = crack.filter_gt(&col, 5.0);
20062 let mut gt5_vals: Vec<i64> = gt5
20063 .iter()
20064 .filter_map(|&i| match &col.values()[i] {
20065 Scalar::Int64(v) => Some(*v),
20066 _ => None,
20067 })
20068 .collect();
20069 assert_eq!(gt5_vals.len(), gt5.len(), "expected Int64 values");
20070 gt5_vals.sort_unstable();
20071 assert_eq!(gt5_vals, vec![8, 10]);
20072 }
20073
20074 #[test]
20075 fn crack_large_column_correctness() {
20076 let n = 1000;
20077 let values: Vec<f64> = (0..n).map(|i| ((i * 7 + 13) % n) as f64).collect();
20078 let col = make_column(&values);
20079 let mut crack = CrackIndex::new(col.len());
20080
20081 for pivot in [100.0, 500.0, 250.0, 750.0, 50.0, 900.0] {
20083 let mut cracked: Vec<usize> = crack.filter_gt(&col, pivot);
20084 cracked.sort_unstable();
20085
20086 let mut naive: Vec<usize> =
20087 (0..n as usize).filter(|&i| values[i] > pivot).collect();
20088 naive.sort_unstable();
20089
20090 assert_eq!(cracked, naive, "large column mismatch for pivot={pivot}");
20091 }
20092 }
20093 }
20094
20095 mod comparison_tests {
20098 use fp_types::{NullKind, Scalar};
20099
20100 use super::super::*;
20101
20102 #[test]
20103 fn comparison_gt_int64() {
20104 let left =
20105 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(5), Scalar::Int64(3)])
20106 .expect("left");
20107 let right =
20108 Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(3), Scalar::Int64(3)])
20109 .expect("right");
20110
20111 let result = left
20112 .binary_comparison(&right, ComparisonOp::Gt)
20113 .expect("gt");
20114 assert_eq!(result.dtype(), fp_types::DType::Bool);
20115 assert_eq!(result.values()[0], Scalar::Bool(false));
20116 assert_eq!(result.values()[1], Scalar::Bool(true));
20117 assert_eq!(result.values()[2], Scalar::Bool(false));
20118 }
20119
20120 #[test]
20121 fn comparison_all_ops_numeric() {
20122 let left = Column::from_values(vec![Scalar::Float64(5.0)]).expect("left");
20123 let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
20124
20125 let gt = left
20126 .binary_comparison(&right, ComparisonOp::Gt)
20127 .expect("gt");
20128 let lt = left
20129 .binary_comparison(&right, ComparisonOp::Lt)
20130 .expect("lt");
20131 let eq = left
20132 .binary_comparison(&right, ComparisonOp::Eq)
20133 .expect("eq");
20134 let ne = left
20135 .binary_comparison(&right, ComparisonOp::Ne)
20136 .expect("ne");
20137 let ge = left
20138 .binary_comparison(&right, ComparisonOp::Ge)
20139 .expect("ge");
20140 let le = left
20141 .binary_comparison(&right, ComparisonOp::Le)
20142 .expect("le");
20143
20144 assert_eq!(gt.values()[0], Scalar::Bool(true));
20145 assert_eq!(lt.values()[0], Scalar::Bool(false));
20146 assert_eq!(eq.values()[0], Scalar::Bool(false));
20147 assert_eq!(ne.values()[0], Scalar::Bool(true));
20148 assert_eq!(ge.values()[0], Scalar::Bool(true));
20149 assert_eq!(le.values()[0], Scalar::Bool(false));
20150 }
20151
20152 #[test]
20153 fn pandas_comparison_aliases_match_binary_comparison() {
20154 let left = Column::from_values(vec![Scalar::Float64(5.0)]).expect("left");
20155 let right = Column::from_values(vec![Scalar::Float64(3.0)]).expect("right");
20156
20157 assert_eq!(
20158 left.eq(&right).expect("eq"),
20159 left.binary_comparison(&right, ComparisonOp::Eq)
20160 .expect("eq")
20161 );
20162 assert_eq!(
20163 left.ne(&right).expect("ne"),
20164 left.binary_comparison(&right, ComparisonOp::Ne)
20165 .expect("ne")
20166 );
20167 assert_eq!(
20168 left.lt(&right).expect("lt"),
20169 left.binary_comparison(&right, ComparisonOp::Lt)
20170 .expect("lt")
20171 );
20172 assert_eq!(
20173 left.le(&right).expect("le"),
20174 left.binary_comparison(&right, ComparisonOp::Le)
20175 .expect("le")
20176 );
20177 assert_eq!(
20178 left.gt(&right).expect("gt"),
20179 left.binary_comparison(&right, ComparisonOp::Gt)
20180 .expect("gt")
20181 );
20182 assert_eq!(
20183 left.ge(&right).expect("ge"),
20184 left.binary_comparison(&right, ComparisonOp::Ge)
20185 .expect("ge")
20186 );
20187 }
20188
20189 #[test]
20190 fn comparison_equality_equal_values() {
20191 let col = Column::from_values(vec![Scalar::Int64(42)]).expect("col");
20192 let result = col.binary_comparison(&col, ComparisonOp::Eq).expect("eq");
20193 assert_eq!(result.values()[0], Scalar::Bool(true));
20194
20195 let ne = col.binary_comparison(&col, ComparisonOp::Ne).expect("ne");
20196 assert_eq!(ne.values()[0], Scalar::Bool(false));
20197 }
20198
20199 #[test]
20200 fn comparison_null_propagation() {
20201 let left = Column::from_values(vec![
20202 Scalar::Int64(1),
20203 Scalar::Null(NullKind::Null),
20204 Scalar::Int64(3),
20205 ])
20206 .expect("left");
20207 let right = Column::from_values(vec![
20208 Scalar::Int64(2),
20209 Scalar::Int64(2),
20210 Scalar::Null(NullKind::Null),
20211 ])
20212 .expect("right");
20213
20214 let result = left
20215 .binary_comparison(&right, ComparisonOp::Gt)
20216 .expect("gt");
20217 assert_eq!(result.values()[0], Scalar::Bool(false));
20218 assert!(result.values()[1].is_missing(), "null op valid = null");
20219 assert!(result.values()[2].is_missing(), "valid op null = null");
20220 }
20221
20222 #[test]
20223 fn comparison_utf8_lexicographic() {
20224 let left = Column::from_values(vec![
20225 Scalar::Utf8("banana".to_string()),
20226 Scalar::Utf8("apple".to_string()),
20227 ])
20228 .expect("left");
20229 let right = Column::from_values(vec![
20230 Scalar::Utf8("apple".to_string()),
20231 Scalar::Utf8("cherry".to_string()),
20232 ])
20233 .expect("right");
20234
20235 let gt = left
20236 .binary_comparison(&right, ComparisonOp::Gt)
20237 .expect("gt");
20238 assert_eq!(gt.values()[0], Scalar::Bool(true));
20239 assert_eq!(gt.values()[1], Scalar::Bool(false));
20240 }
20241
20242 #[test]
20243 fn compare_scalar_gt() {
20244 let col = Column::from_values(vec![
20245 Scalar::Int64(1),
20246 Scalar::Int64(5),
20247 Scalar::Null(NullKind::Null),
20248 Scalar::Int64(3),
20249 ])
20250 .expect("col");
20251
20252 let result = col
20253 .compare_scalar(&Scalar::Int64(3), ComparisonOp::Gt)
20254 .expect("gt");
20255 assert_eq!(result.values()[0], Scalar::Bool(false));
20256 assert_eq!(result.values()[1], Scalar::Bool(true));
20257 assert!(result.values()[2].is_missing());
20258 assert_eq!(result.values()[3], Scalar::Bool(false));
20259 }
20260
20261 #[test]
20262 fn compare_scalar_with_missing_scalar() {
20263 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
20264
20265 let result = col
20266 .compare_scalar(&Scalar::Null(NullKind::Null), ComparisonOp::Eq)
20267 .expect("eq");
20268 assert!(result.values()[0].is_missing());
20269 assert!(result.values()[1].is_missing());
20270 }
20271
20272 #[test]
20273 fn filter_by_mask_basic() {
20274 let col = Column::from_values(vec![
20275 Scalar::Int64(10),
20276 Scalar::Int64(20),
20277 Scalar::Int64(30),
20278 Scalar::Int64(40),
20279 ])
20280 .expect("col");
20281 let mask = Column::from_values(vec![
20282 Scalar::Bool(true),
20283 Scalar::Bool(false),
20284 Scalar::Bool(true),
20285 Scalar::Bool(false),
20286 ])
20287 .expect("mask");
20288
20289 let result = col.filter_by_mask(&mask).expect("filter");
20290 assert_eq!(result.len(), 2);
20291 assert_eq!(result.values()[0], Scalar::Int64(10));
20292 assert_eq!(result.values()[1], Scalar::Int64(30));
20293 }
20294
20295 #[test]
20296 fn filter_by_mask_float64_typed_path_matches_scalar() {
20297 let col = Column::from_f64_values(vec![1.5, -0.0, 2.5, f64::INFINITY, 0.0]);
20301 let mask = Column::from_values(vec![
20302 Scalar::Bool(true),
20303 Scalar::Bool(true),
20304 Scalar::Bool(false),
20305 Scalar::Bool(true),
20306 Scalar::Null(NullKind::Null), ])
20308 .expect("mask");
20309 let result = col.filter_by_mask(&mask).expect("filter");
20310 assert_eq!(result.dtype(), DType::Float64);
20311 assert_eq!(
20312 result.values(),
20313 &[
20314 Scalar::Float64(1.5),
20315 Scalar::Float64(-0.0),
20316 Scalar::Float64(f64::INFINITY),
20317 ]
20318 );
20319 }
20320
20321 #[test]
20322 fn compare_scalar_typed_path_matches_scalar_compare() {
20323 let f64_vals = vec![1.5f64, -0.0, 0.0, 2.5, -3.0, f64::INFINITY, 100.0];
20327 let i64_vals = vec![1i64, -2, 0, 5, 100, -7];
20328 let ops = [
20329 ComparisonOp::Gt,
20330 ComparisonOp::Lt,
20331 ComparisonOp::Eq,
20332 ComparisonOp::Ne,
20333 ComparisonOp::Ge,
20334 ComparisonOp::Le,
20335 ];
20336 for op in ops {
20337 for &probe in &[0.0f64, 1.5, 2.5, -3.0, f64::INFINITY] {
20339 let got = Column::from_f64_values(f64_vals.clone())
20340 .compare_scalar(&Scalar::Float64(probe), op)
20341 .expect("f64 cmp");
20342 let expected: Vec<Scalar> = f64_vals
20343 .iter()
20344 .map(|&v| {
20345 Scalar::Bool(
20346 scalar_compare(&Scalar::Float64(v), &Scalar::Float64(probe), op)
20347 .unwrap(),
20348 )
20349 })
20350 .collect();
20351 assert_eq!(
20352 got.values(),
20353 expected.as_slice(),
20354 "f64 op {op:?} probe {probe}"
20355 );
20356 }
20357 let got = Column::from_f64_values(f64_vals.clone())
20359 .compare_scalar(&Scalar::Int64(2), op)
20360 .expect("f64-vs-i64 cmp");
20361 let expected: Vec<Scalar> = f64_vals
20362 .iter()
20363 .map(|&v| {
20364 Scalar::Bool(
20365 scalar_compare(&Scalar::Float64(v), &Scalar::Int64(2), op).unwrap(),
20366 )
20367 })
20368 .collect();
20369 assert_eq!(got.values(), expected.as_slice(), "f64-vs-i64 op {op:?}");
20370 let got = Column::from_i64_values(i64_vals.clone())
20372 .compare_scalar(&Scalar::Int64(0), op)
20373 .expect("i64 cmp");
20374 let expected: Vec<Scalar> = i64_vals
20375 .iter()
20376 .map(|&v| {
20377 Scalar::Bool(
20378 scalar_compare(&Scalar::Int64(v), &Scalar::Int64(0), op).unwrap(),
20379 )
20380 })
20381 .collect();
20382 assert_eq!(got.values(), expected.as_slice(), "i64 op {op:?}");
20383 }
20384 }
20385
20386 #[test]
20387 #[ignore = "perf timing harness, run with --ignored"]
20388 fn compare_scalar_typed_vs_aos_timing() {
20389 use std::time::Instant;
20390 let n = 5_000_000usize;
20391 let raw: Vec<f64> = (0..n).map(|i| (i % 1000) as f64 - 500.0).collect();
20392 let scalars: Vec<Scalar> = raw.iter().map(|&v| Scalar::Float64(v)).collect();
20393 let probe = Scalar::Float64(0.0);
20394 let op = ComparisonOp::Gt;
20395
20396 let t = Instant::now();
20398 let aos: Vec<Scalar> = scalars
20399 .iter()
20400 .map(|v| Scalar::Bool(scalar_compare(v, &probe, op).unwrap()))
20401 .collect();
20402 let aos_ns = t.elapsed().as_nanos();
20403 std::hint::black_box(&aos);
20404
20405 let col = Column::from_f64_values(raw.clone());
20407 let t = Instant::now();
20408 let typed = col.compare_scalar(&probe, op).expect("typed cmp");
20409 let typed_ns = t.elapsed().as_nanos();
20410 std::hint::black_box(&typed);
20411
20412 assert_eq!(typed.values(), aos.as_slice(), "typed must match AoS");
20413 let ratio = aos_ns as f64 / typed_ns as f64;
20414 println!(
20415 "compare_scalar Gt n={n}: AoS {aos_ns}ns typed {typed_ns}ns Score={ratio:.2}x"
20416 );
20417 }
20418
20419 #[test]
20420 fn filter_by_mask_null_treated_as_false() {
20421 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
20422 let mask = Column::from_values(vec![Scalar::Bool(true), Scalar::Null(NullKind::Null)])
20423 .expect("mask");
20424
20425 let result = col.filter_by_mask(&mask).expect("filter");
20426 assert_eq!(result.len(), 1);
20427 assert_eq!(result.values()[0], Scalar::Int64(1));
20428 }
20429
20430 #[test]
20431 fn filter_by_mask_rejects_non_boolean_mask() {
20432 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
20433 let mask = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(0)]).expect("mask");
20434
20435 let err = col.filter_by_mask(&mask).expect_err("non-bool mask");
20436 assert!(matches!(err, ColumnError::InvalidMaskType { .. }));
20437 }
20438
20439 #[test]
20440 fn filter_by_mask_empty_result() {
20441 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
20442 let mask =
20443 Column::from_values(vec![Scalar::Bool(false), Scalar::Bool(false)]).expect("mask");
20444
20445 let result = col.filter_by_mask(&mask).expect("filter");
20446 assert!(result.is_empty());
20447 }
20448
20449 #[test]
20450 fn filter_by_mask_matches_scalar_oracle_7mlq1() {
20451 fn next(seed: &mut u64) -> u64 {
20454 *seed = seed
20455 .wrapping_mul(6364136223846793005)
20456 .wrapping_add(1442695040888963407);
20457 *seed
20458 }
20459
20460 fn mask_values(seed: &mut u64, len: usize) -> Vec<Scalar> {
20461 let mut mask = Vec::with_capacity(len);
20462 for _ in 0..len {
20463 mask.push(match next(seed) % 5 {
20464 0 => Scalar::Null(NullKind::Null),
20465 1 | 2 => Scalar::Bool(false),
20466 _ => Scalar::Bool(true),
20467 });
20468 }
20469 mask
20470 }
20471
20472 fn assert_filter(case: usize, family: &str, values: Vec<Scalar>, mask: Vec<Scalar>) {
20473 let input = Column::from_values(values).expect("column");
20474 let mask = Column::from_values(mask).expect("mask");
20475 let expected = input
20476 .values()
20477 .iter()
20478 .zip(mask.values().iter())
20479 .filter_map(|(value, mask_value)| {
20480 matches!(mask_value, Scalar::Bool(true)).then_some(value.clone())
20481 })
20482 .collect::<Vec<_>>();
20483
20484 let filtered = input.filter_by_mask(&mask).expect("filter_by_mask");
20485 assert_eq!(
20486 filtered.dtype(),
20487 input.dtype(),
20488 "case={case} family={family}: dtype changed"
20489 );
20490 assert_eq!(
20491 filtered.len(),
20492 expected.len(),
20493 "case={case} family={family}: length mismatch"
20494 );
20495 for (pos, (actual, expected)) in filtered.values().iter().zip(&expected).enumerate()
20496 {
20497 assert!(
20498 actual.semantic_eq(expected),
20499 "case={case} family={family} pos={pos}: expected {expected:?}, got {actual:?}"
20500 );
20501 }
20502 }
20503
20504 let mut seed = 0x7f11_7e12_5ca1_ab1e_u64;
20505 for case in 0..180 {
20506 let len = (next(&mut seed) % 79 + 1) as usize;
20507
20508 let mut floats = Vec::with_capacity(len);
20509 floats.push(Scalar::Float64(case as f64 / 7.0));
20510 for _ in 1..len {
20511 let raw = (next(&mut seed) % 12_001) as i64 - 6_000;
20512 floats.push(match next(&mut seed) % 8 {
20513 0 => Scalar::Float64(f64::NAN),
20514 1 => Scalar::Float64(f64::INFINITY),
20515 2 => Scalar::Float64(f64::NEG_INFINITY),
20516 3 => Scalar::Float64(-0.0),
20517 _ => Scalar::Float64(raw as f64 / 31.0),
20518 });
20519 }
20520 assert_filter(case, "float", floats, mask_values(&mut seed, len));
20521
20522 let mut ints = Vec::with_capacity(len);
20523 ints.push(Scalar::Int64(case as i64));
20524 for _ in 1..len {
20525 let raw = (next(&mut seed) % 67) as i64 - 33;
20526 ints.push(match next(&mut seed) % 6 {
20527 0 => Scalar::Null(NullKind::Null),
20528 1 => Scalar::Null(NullKind::NaN),
20529 _ => Scalar::Int64(raw),
20530 });
20531 }
20532 assert_filter(case, "int", ints, mask_values(&mut seed, len));
20533
20534 let mut bools = Vec::with_capacity(len);
20535 bools.push(Scalar::Bool(case & 1 == 0));
20536 for _ in 1..len {
20537 bools.push(match next(&mut seed) % 5 {
20538 0 => Scalar::Null(NullKind::Null),
20539 1 => Scalar::Null(NullKind::NaN),
20540 raw => Scalar::Bool(raw & 1 == 0),
20541 });
20542 }
20543 assert_filter(case, "bool", bools, mask_values(&mut seed, len));
20544
20545 let mut utf8 = Vec::with_capacity(len);
20546 utf8.push(Scalar::Utf8(format!("mask{}", case % 23)));
20547 for pos in 1..len {
20548 utf8.push(match next(&mut seed) % 7 {
20549 0 => Scalar::Null(NullKind::Null),
20550 1 => Scalar::Null(NullKind::NaN),
20551 raw => Scalar::Utf8(format!("mask{}_{}", raw, pos % 17)),
20552 });
20553 }
20554 assert_filter(case, "utf8", utf8, mask_values(&mut seed, len));
20555
20556 let mut timedeltas = Vec::with_capacity(len);
20557 timedeltas.push(Scalar::Timedelta64(case as i64 - 45));
20558 for _ in 1..len {
20559 let raw = (next(&mut seed) % 181) as i64 - 90;
20560 timedeltas.push(match next(&mut seed) % 7 {
20561 0 => Scalar::Null(NullKind::Null),
20562 1 => Scalar::Timedelta64(i64::MIN),
20563 _ => Scalar::Timedelta64(raw),
20564 });
20565 }
20566 assert_filter(case, "timedelta", timedeltas, mask_values(&mut seed, len));
20567 }
20568 }
20569
20570 #[test]
20571 fn fillna_replaces_missing() {
20572 let col = Column::from_values(vec![
20573 Scalar::Int64(1),
20574 Scalar::Null(NullKind::Null),
20575 Scalar::Int64(3),
20576 Scalar::Null(NullKind::Null),
20577 ])
20578 .expect("col");
20579
20580 let result = col.fillna(&Scalar::Int64(0)).expect("fillna");
20581 assert_eq!(result.values()[0], Scalar::Int64(1));
20582 assert_eq!(result.values()[1], Scalar::Int64(0));
20583 assert_eq!(result.values()[2], Scalar::Int64(3));
20584 assert_eq!(result.values()[3], Scalar::Int64(0));
20585 assert_eq!(result.validity().count_valid(), 4);
20586 }
20587
20588 #[test]
20589 fn fillna_matches_scalar_replacement_oracle_56isx() {
20590 fn next(seed: &mut u64) -> u64 {
20593 *seed = seed
20594 .wrapping_mul(3202034522624059733)
20595 .wrapping_add(4354685564936845319);
20596 *seed
20597 }
20598
20599 fn assert_fillna(case: usize, family: &str, values: Vec<Scalar>, fill: Scalar) {
20600 let input = Column::from_values(values).expect("column");
20601 let expected = input
20602 .values()
20603 .iter()
20604 .map(|value| {
20605 if value.is_missing() {
20606 fill.clone()
20607 } else {
20608 value.clone()
20609 }
20610 })
20611 .collect::<Vec<_>>();
20612
20613 let filled = input.fillna(&fill).expect("fillna");
20614 assert_eq!(
20615 filled.dtype(),
20616 input.dtype(),
20617 "case={case} family={family}: dtype changed"
20618 );
20619 assert_eq!(
20620 filled.len(),
20621 input.len(),
20622 "case={case} family={family}: length changed"
20623 );
20624 assert_eq!(
20625 filled.values(),
20626 expected.as_slice(),
20627 "case={case} family={family}: replacement mismatch"
20628 );
20629 assert_eq!(
20630 filled.validity().count_valid(),
20631 filled.len(),
20632 "case={case} family={family}: fillna left invalid positions"
20633 );
20634 }
20635
20636 let mut seed = 0xf111_ca5c_a1a5_56a1_u64;
20637 for case in 0..180 {
20638 let len = (next(&mut seed) % 73 + 1) as usize;
20639
20640 let mut floats = Vec::with_capacity(len);
20641 floats.push(Scalar::Float64(case as f64 / 5.0));
20642 for _ in 1..len {
20643 let raw = (next(&mut seed) % 16_001) as i64 - 8_000;
20644 floats.push(match next(&mut seed) % 7 {
20645 0 | 1 => Scalar::Float64(f64::NAN),
20646 2 => Scalar::Float64(f64::INFINITY),
20647 3 => Scalar::Float64(f64::NEG_INFINITY),
20648 _ => Scalar::Float64(raw as f64 / 37.0),
20649 });
20650 }
20651 assert_fillna(case, "float", floats, Scalar::Float64(-123.5));
20652
20653 let mut ints = Vec::with_capacity(len);
20654 ints.push(Scalar::Int64(case as i64 - 90));
20655 for _ in 1..len {
20656 let raw = (next(&mut seed) % 101) as i64 - 50;
20657 ints.push(match next(&mut seed) % 6 {
20658 0 => Scalar::Null(NullKind::Null),
20659 1 => Scalar::Null(NullKind::NaN),
20660 _ => Scalar::Int64(raw),
20661 });
20662 }
20663 assert_fillna(case, "int", ints, Scalar::Int64(-777));
20664
20665 let mut bools = Vec::with_capacity(len);
20666 bools.push(Scalar::Bool(case & 1 == 0));
20667 for _ in 1..len {
20668 bools.push(match next(&mut seed) % 5 {
20669 0 => Scalar::Null(NullKind::Null),
20670 1 => Scalar::Null(NullKind::NaN),
20671 raw => Scalar::Bool(raw & 1 == 0),
20672 });
20673 }
20674 assert_fillna(case, "bool", bools, Scalar::Bool(true));
20675
20676 let mut utf8 = Vec::with_capacity(len);
20677 utf8.push(Scalar::Utf8(format!("fill{}", case % 19)));
20678 for pos in 1..len {
20679 utf8.push(match next(&mut seed) % 7 {
20680 0 => Scalar::Null(NullKind::Null),
20681 1 => Scalar::Null(NullKind::NaN),
20682 raw => Scalar::Utf8(format!("fill{}_{}", raw, pos % 13)),
20683 });
20684 }
20685 assert_fillna(case, "utf8", utf8, Scalar::Utf8("filled".into()));
20686
20687 let mut timedeltas = Vec::with_capacity(len);
20688 timedeltas.push(Scalar::Timedelta64(case as i64));
20689 for _ in 1..len {
20690 let raw = (next(&mut seed) % 149) as i64 - 74;
20691 timedeltas.push(match next(&mut seed) % 7 {
20692 0 => Scalar::Null(NullKind::Null),
20693 1 => Scalar::Timedelta64(i64::MIN),
20694 _ => Scalar::Timedelta64(raw),
20695 });
20696 }
20697 assert_fillna(case, "timedelta", timedeltas, Scalar::Timedelta64(123_456));
20698 }
20699 }
20700
20701 #[test]
20702 fn dropna_removes_missing() {
20703 let col = Column::from_values(vec![
20704 Scalar::Int64(1),
20705 Scalar::Null(NullKind::Null),
20706 Scalar::Int64(3),
20707 Scalar::Null(NullKind::NaN),
20708 ])
20709 .expect("col");
20710
20711 let result = col.dropna().expect("dropna");
20712 assert_eq!(result.len(), 2);
20713 assert_eq!(result.values()[0], Scalar::Int64(1));
20714 assert_eq!(result.values()[1], Scalar::Int64(3));
20715 }
20716
20717 #[test]
20718 fn dropna_matches_order_preserving_scalar_oracle_vbbe4() {
20719 fn next(seed: &mut u64) -> u64 {
20722 *seed = seed
20723 .wrapping_mul(2862933555777941757)
20724 .wrapping_add(3037000493);
20725 *seed
20726 }
20727
20728 fn assert_dropna(case: usize, family: &str, values: Vec<Scalar>) {
20729 let input = Column::from_values(values).expect("column");
20730 let expected = input
20731 .values()
20732 .iter()
20733 .filter(|value| !value.is_missing())
20734 .cloned()
20735 .collect::<Vec<_>>();
20736
20737 let dropped = input.dropna().expect("dropna");
20738 assert_eq!(
20739 dropped.dtype(),
20740 input.dtype(),
20741 "case={case} family={family}: dtype changed"
20742 );
20743 assert_eq!(
20744 dropped.len(),
20745 expected.len(),
20746 "case={case} family={family}: length mismatch"
20747 );
20748 assert_eq!(
20749 dropped.count(),
20750 expected.len(),
20751 "case={case} family={family}: count mismatch"
20752 );
20753 assert!(
20754 dropped.values().iter().all(|value| !value.is_missing()),
20755 "case={case} family={family}: dropna left missing values in {:?}",
20756 dropped.values()
20757 );
20758 assert_eq!(
20759 dropped.values(),
20760 expected.as_slice(),
20761 "case={case} family={family}: order/value mismatch"
20762 );
20763 }
20764
20765 assert_dropna(
20766 usize::MAX,
20767 "all_float_missing",
20768 vec![Scalar::Float64(f64::NAN), Scalar::Float64(f64::NAN)],
20769 );
20770 assert_dropna(
20771 usize::MAX - 1,
20772 "all_timedelta_missing",
20773 vec![
20774 Scalar::Timedelta64(i64::MIN),
20775 Scalar::Null(NullKind::Null),
20776 Scalar::Timedelta64(i64::MIN),
20777 ],
20778 );
20779
20780 let mut seed = 0xd20f_ca55_0b5e_7a11_u64;
20781 for case in 0..180 {
20782 let len = (next(&mut seed) % 71 + 1) as usize;
20783
20784 let mut floats = Vec::with_capacity(len);
20785 floats.push(Scalar::Float64(case as f64 / 3.0));
20786 for _ in 1..len {
20787 let raw = (next(&mut seed) % 20_001) as i64 - 10_000;
20788 floats.push(match next(&mut seed) % 8 {
20789 0 | 1 => Scalar::Float64(f64::NAN),
20790 2 => Scalar::Float64(f64::INFINITY),
20791 3 => Scalar::Float64(f64::NEG_INFINITY),
20792 4 => Scalar::Float64(-0.0),
20793 _ => Scalar::Float64(raw as f64 / 29.0),
20794 });
20795 }
20796 assert_dropna(case, "float", floats);
20797
20798 let mut ints = Vec::with_capacity(len);
20799 ints.push(Scalar::Int64(case as i64));
20800 for _ in 1..len {
20801 let raw = (next(&mut seed) % 59) as i64 - 29;
20802 ints.push(match next(&mut seed) % 6 {
20803 0 => Scalar::Null(NullKind::Null),
20804 1 => Scalar::Null(NullKind::NaN),
20805 _ => Scalar::Int64(raw),
20806 });
20807 }
20808 assert_dropna(case, "int", ints);
20809
20810 let mut bools = Vec::with_capacity(len);
20811 bools.push(Scalar::Bool(case & 1 == 0));
20812 for _ in 1..len {
20813 bools.push(match next(&mut seed) % 5 {
20814 0 => Scalar::Null(NullKind::Null),
20815 1 => Scalar::Null(NullKind::NaN),
20816 raw => Scalar::Bool(raw & 1 == 1),
20817 });
20818 }
20819 assert_dropna(case, "bool", bools);
20820
20821 let mut utf8 = Vec::with_capacity(len);
20822 utf8.push(Scalar::Utf8(format!("u{}", case % 17)));
20823 for pos in 1..len {
20824 utf8.push(match next(&mut seed) % 7 {
20825 0 => Scalar::Null(NullKind::Null),
20826 1 => Scalar::Null(NullKind::NaN),
20827 raw => Scalar::Utf8(format!("u{}_{}", raw, pos % 11)),
20828 });
20829 }
20830 assert_dropna(case, "utf8", utf8);
20831
20832 let mut timedeltas = Vec::with_capacity(len);
20833 timedeltas.push(Scalar::Timedelta64(case as i64 - 90));
20834 for _ in 1..len {
20835 let raw = (next(&mut seed) % 123) as i64 - 61;
20836 timedeltas.push(match next(&mut seed) % 7 {
20837 0 => Scalar::Null(NullKind::Null),
20838 1 => Scalar::Timedelta64(i64::MIN),
20839 _ => Scalar::Timedelta64(raw),
20840 });
20841 }
20842 assert_dropna(case, "timedelta", timedeltas);
20843 }
20844 }
20845
20846 #[test]
20847 fn comparison_empty_columns() {
20848 let left = Column::from_values(vec![]).expect("left");
20849 let right = Column::from_values(vec![]).expect("right");
20850 let result = left
20851 .binary_comparison(&right, ComparisonOp::Eq)
20852 .expect("eq");
20853 assert!(result.is_empty());
20854 }
20855
20856 #[test]
20857 fn comparison_length_mismatch_error() {
20858 let left = Column::from_values(vec![Scalar::Int64(1)]).expect("left");
20859 let right =
20860 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("right");
20861 assert!(left.binary_comparison(&right, ComparisonOp::Eq).is_err());
20862 }
20863
20864 #[test]
20865 fn comparison_bool_ordering() {
20866 let left =
20867 Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("left");
20868 let right =
20869 Column::from_values(vec![Scalar::Bool(false), Scalar::Bool(true)]).expect("right");
20870
20871 let gt = left
20872 .binary_comparison(&right, ComparisonOp::Gt)
20873 .expect("gt");
20874 assert_eq!(gt.values()[0], Scalar::Bool(true));
20875 assert_eq!(gt.values()[1], Scalar::Bool(false));
20876 }
20877 }
20878
20879 mod iter_and_predicates {
20880 use fp_types::NullKind;
20881
20882 use super::*;
20883
20884 #[test]
20885 fn iter_values_preserves_order() {
20886 let col =
20887 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
20888 .expect("col");
20889 let collected: Vec<_> = col.iter_values().cloned().collect();
20890 assert_eq!(collected, col.values());
20891 }
20892
20893 #[test]
20894 fn to_vec_returns_owned_clone() {
20895 let col = Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(6)]).expect("col");
20896 let v = col.to_vec();
20897 assert_eq!(v, vec![Scalar::Int64(5), Scalar::Int64(6)]);
20898 assert_eq!(col.len(), 2);
20900 }
20901
20902 #[test]
20903 fn copy_returns_independent_clone() {
20904 let col = Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(6)]).expect("col");
20905 let copied = col.copy();
20906 let viewed = col.view();
20907 let transposed = col.transpose();
20908 assert_eq!(copied, col);
20909 assert_eq!(viewed, col);
20910 assert_eq!(transposed, col);
20911 assert_eq!(col.t(), transposed);
20912 assert_eq!(col.T(), transposed);
20913 assert_ne!(copied.values().as_ptr(), col.values().as_ptr());
20914 assert_ne!(viewed.values().as_ptr(), col.values().as_ptr());
20915 assert_ne!(transposed.values().as_ptr(), col.values().as_ptr());
20916 }
20917
20918 #[test]
20919 fn item_extracts_single_value_and_rejects_other_lengths() {
20920 let single = Column::from_values(vec![Scalar::Int64(5)]).expect("col");
20921 assert_eq!(single.item(), Ok(Scalar::Int64(5)));
20922
20923 let empty = Column::from_values(Vec::<Scalar>::new()).expect("col");
20924 assert_eq!(
20925 empty.item(),
20926 Err(crate::ColumnError::InvalidLength {
20927 operation: "item()",
20928 expected: 1,
20929 actual: 0,
20930 })
20931 );
20932
20933 let multi = Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(6)]).expect("col");
20934 assert_eq!(
20935 multi.item(),
20936 Err(crate::ColumnError::InvalidLength {
20937 operation: "item()",
20938 expected: 1,
20939 actual: 2,
20940 })
20941 );
20942 }
20943
20944 #[test]
20945 fn has_any_missing_detects_null() {
20946 let populated =
20947 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
20948 assert!(!populated.has_any_missing());
20949 assert_eq!(populated.hasnans(), populated.has_any_missing());
20950 assert_eq!(populated.nbytes(), populated.memory_usage(false));
20951
20952 let with_null =
20953 Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
20954 .expect("col");
20955 assert!(with_null.has_any_missing());
20956 assert_eq!(with_null.hasnans(), with_null.has_any_missing());
20957 assert_eq!(with_null.nbytes(), with_null.memory_usage(false));
20958 }
20959
20960 #[test]
20961 fn missingness_probes_use_nullable_int64_validity_without_scalar_materialization_eo8jv() {
20962 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(0, 2), (5, 1)]), 6);
20963 let mixed = Column::from_i64_values_with_validity((10_i64..16).collect(), validity);
20964
20965 assert!(mixed.has_any_missing());
20966 assert_eq!(mixed.hasnans(), mixed.has_any_missing());
20967 assert!(!mixed.all_missing());
20968 if let ScalarValues::LazyNullableInt64 { values, .. } = &mixed.values {
20969 assert!(values.get().is_none());
20970 }
20971
20972 let all_invalid =
20973 Column::from_i64_values_with_validity(vec![0, 0, 0], ValidityMask::all_invalid(3));
20974 assert!(all_invalid.has_any_missing());
20975 assert!(all_invalid.all_missing());
20976 if let ScalarValues::LazyNullableInt64 { values, .. } = &all_invalid.values {
20977 assert!(values.get().is_none());
20978 }
20979 }
20980
20981 #[test]
20982 fn missingness_probes_float64_raw_path_checks_nan_eo8jv() {
20983 let mixed = Column {
20984 dtype: DType::Float64,
20985 values: ScalarValues::lazy_all_valid_float64(vec![1.0, f64::NAN, f64::INFINITY]),
20986 validity: ValidityMask::all_valid(3),
20987 data: None,
20988 };
20989 assert!(mixed.has_any_missing());
20990 assert!(!mixed.all_missing());
20991 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &mixed.values {
20992 assert!(values.get().is_none());
20993 }
20994
20995 let all_nan = Column {
20996 dtype: DType::Float64,
20997 values: ScalarValues::lazy_all_valid_float64(vec![f64::NAN, f64::NAN]),
20998 validity: ValidityMask::all_valid(2),
20999 data: None,
21000 };
21001 assert!(all_nan.has_any_missing());
21002 assert!(all_nan.all_missing());
21003 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &all_nan.values {
21004 assert!(values.get().is_none());
21005 }
21006 }
21007
21008 #[test]
21009 fn all_missing_empty_is_true() {
21010 let empty = Column::from_values(Vec::<Scalar>::new()).expect("col");
21011 assert!(empty.all_missing());
21012
21013 let all_null = Column::from_values(vec![
21014 Scalar::Null(NullKind::NaN),
21015 Scalar::Null(NullKind::Null),
21016 ])
21017 .expect("col");
21018 assert!(all_null.all_missing());
21019
21020 let mixed = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
21021 .expect("col");
21022 assert!(!mixed.all_missing());
21023 }
21024
21025 #[test]
21026 fn apply_bool_positive_predicate() {
21027 let col = Column::from_values(vec![
21028 Scalar::Int64(1),
21029 Scalar::Int64(2),
21030 Scalar::Int64(3),
21031 Scalar::Int64(4),
21032 ])
21033 .expect("col");
21034 let even = col
21035 .apply_bool(|v| v.to_f64().map(|f| f as i64 % 2 == 0).unwrap_or(false))
21036 .expect("apply_bool");
21037 assert_eq!(even.dtype(), DType::Bool);
21038 assert_eq!(even.values()[0], Scalar::Bool(false));
21039 assert_eq!(even.values()[1], Scalar::Bool(true));
21040 assert_eq!(even.values()[2], Scalar::Bool(false));
21041 assert_eq!(even.values()[3], Scalar::Bool(true));
21042 }
21043
21044 #[test]
21045 fn first_and_last_return_endpoints() {
21046 let col = Column::from_values(vec![
21047 Scalar::Int64(10),
21048 Scalar::Int64(20),
21049 Scalar::Int64(30),
21050 ])
21051 .expect("col");
21052 assert_eq!(col.first(), Some(&Scalar::Int64(10)));
21053 assert_eq!(col.last(), Some(&Scalar::Int64(30)));
21054
21055 let empty = Column::from_values(Vec::<Scalar>::new()).expect("col");
21056 assert_eq!(empty.first(), None);
21057 assert_eq!(empty.last(), None);
21058 }
21059
21060 #[test]
21061 fn count_matching_ignores_missing_and_mismatches() {
21062 let col = Column::from_values(vec![
21063 Scalar::Int64(1),
21064 Scalar::Int64(2),
21065 Scalar::Null(NullKind::NaN),
21066 Scalar::Int64(4),
21067 Scalar::Int64(6),
21068 ])
21069 .expect("col");
21070 let evens =
21071 col.count_matching(|v| v.to_f64().map(|f| f as i64 % 2 == 0).unwrap_or(false));
21072 assert_eq!(evens, 3); }
21074
21075 #[test]
21076 fn zip_with_elementwise_combine() {
21077 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21078 .expect("a");
21079 let b = Column::from_values(vec![
21080 Scalar::Int64(10),
21081 Scalar::Int64(20),
21082 Scalar::Int64(30),
21083 ])
21084 .expect("b");
21085 let sum = a
21086 .zip_with(&b, |l, r| match (l.to_f64(), r.to_f64()) {
21087 (Ok(lf), Ok(rf)) => Scalar::Float64(lf + rf),
21088 _ => Scalar::Null(NullKind::NaN),
21089 })
21090 .expect("zip_with");
21091 assert_eq!(sum.values()[0], Scalar::Float64(11.0));
21092 assert_eq!(sum.values()[1], Scalar::Float64(22.0));
21093 assert_eq!(sum.values()[2], Scalar::Float64(33.0));
21094 }
21095
21096 #[test]
21097 fn zip_with_length_mismatch_errors() {
21098 let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
21099 let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
21100 assert!(a.zip_with(&b, |l, _| l.clone()).is_err());
21101 }
21102
21103 #[test]
21104 fn iter_enumerate_yields_positions() {
21105 let col = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("col");
21106 let collected: Vec<_> = col.iter_enumerate().map(|(i, v)| (i, v.clone())).collect();
21107 assert_eq!(
21108 collected,
21109 vec![(0, Scalar::Int64(10)), (1, Scalar::Int64(20))]
21110 );
21111 }
21112
21113 #[test]
21114 fn apply_bool_missing_maps_to_false() {
21115 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
21116 .expect("col");
21117 let result = col.apply_bool(|_| true).expect("apply_bool");
21118 assert_eq!(result.values()[0], Scalar::Bool(true));
21119 assert_eq!(result.values()[1], Scalar::Bool(false));
21121 }
21122 }
21123
21124 mod take_slice_concat_repeat {
21125 use super::*;
21126
21127 #[test]
21128 fn take_reorders_rows() {
21129 let col = Column::from_values(vec![
21130 Scalar::Int64(10),
21131 Scalar::Int64(20),
21132 Scalar::Int64(30),
21133 ])
21134 .expect("col");
21135 let picked = col.take(&[2, 0, 1]).expect("take");
21136 assert_eq!(picked.values()[0], Scalar::Int64(30));
21137 assert_eq!(picked.values()[1], Scalar::Int64(10));
21138 assert_eq!(picked.values()[2], Scalar::Int64(20));
21139 }
21140
21141 #[test]
21142 fn take_out_of_bounds_errors() {
21143 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
21144 let err = col.take(&[5]).unwrap_err();
21145 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
21146 }
21147
21148 #[test]
21149 fn slice_returns_contiguous_range() {
21150 let col = Column::from_values(vec![
21151 Scalar::Int64(1),
21152 Scalar::Int64(2),
21153 Scalar::Int64(3),
21154 Scalar::Int64(4),
21155 ])
21156 .expect("col");
21157 let middle = col.slice(1, 2).expect("slice");
21158 assert_eq!(middle.len(), 2);
21159 assert_eq!(middle.values()[0], Scalar::Int64(2));
21160 assert_eq!(middle.values()[1], Scalar::Int64(3));
21161 }
21162
21163 #[test]
21164 fn slice_past_end_yields_empty() {
21165 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21166 let empty = col.slice(10, 5).expect("slice");
21167 assert!(empty.is_empty());
21168 assert_eq!(empty.dtype(), DType::Int64);
21169 }
21170
21171 #[test]
21172 fn slice_len_clamps_to_tail() {
21173 let col = Column::from_values(vec![
21174 Scalar::Float64(1.0),
21175 Scalar::Float64(2.0),
21176 Scalar::Float64(3.0),
21177 ])
21178 .expect("col");
21179 let tail = col.slice(2, 100).expect("slice");
21180 assert_eq!(tail.len(), 1);
21181 assert_eq!(tail.values()[0], Scalar::Float64(3.0));
21182 }
21183
21184 #[test]
21185 fn slice_huge_len_clamps_without_overflow() {
21186 let col =
21187 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21188 .expect("col");
21189 let tail = col.slice(1, usize::MAX).expect("slice");
21190 assert_eq!(tail.values(), &[Scalar::Int64(2), Scalar::Int64(3)]);
21191 }
21192
21193 #[test]
21194 fn head_returns_first_n_values() {
21195 let col = Column::from_values(vec![
21196 Scalar::Int64(10),
21197 Scalar::Int64(20),
21198 Scalar::Int64(30),
21199 Scalar::Int64(40),
21200 ])
21201 .expect("col");
21202 let out = col.head(2).expect("head");
21203 assert_eq!(out.values(), &[Scalar::Int64(10), Scalar::Int64(20)]);
21204 }
21205
21206 #[test]
21207 fn tail_returns_last_n_values() {
21208 let col = Column::from_values(vec![
21209 Scalar::Int64(10),
21210 Scalar::Int64(20),
21211 Scalar::Int64(30),
21212 Scalar::Int64(40),
21213 ])
21214 .expect("col");
21215 let out = col.tail(2).expect("tail");
21216 assert_eq!(out.values(), &[Scalar::Int64(30), Scalar::Int64(40)]);
21217 }
21218
21219 #[test]
21220 fn head_tail_negative_n_match_pandas_style() {
21221 let col = Column::from_values(vec![
21222 Scalar::Int64(10),
21223 Scalar::Int64(20),
21224 Scalar::Int64(30),
21225 Scalar::Int64(40),
21226 Scalar::Int64(50),
21227 ])
21228 .expect("col");
21229 let head = col.head(-2).expect("head");
21230 let tail = col.tail(-2).expect("tail");
21231 assert_eq!(
21232 head.values(),
21233 &[Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)]
21234 );
21235 assert_eq!(
21236 tail.values(),
21237 &[Scalar::Int64(30), Scalar::Int64(40), Scalar::Int64(50)]
21238 );
21239 }
21240
21241 #[test]
21242 fn head_tail_large_negative_n_saturate_to_empty() {
21243 let col = Column::from_values(vec![
21244 Scalar::Float64(1.0),
21245 Scalar::Float64(2.0),
21246 Scalar::Float64(3.0),
21247 ])
21248 .expect("col");
21249 let head = col.head(-10).expect("head");
21250 let tail = col.tail(-10).expect("tail");
21251 assert!(head.is_empty());
21252 assert!(tail.is_empty());
21253 assert_eq!(head.dtype(), DType::Float64);
21254 assert_eq!(tail.dtype(), DType::Float64);
21255 }
21256
21257 #[test]
21258 fn concat_appends_same_dtype() {
21259 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("a");
21260 let b = Column::from_values(vec![Scalar::Int64(3)]).expect("b");
21261 let combined = a.concat(&b).expect("concat");
21262 assert_eq!(combined.len(), 3);
21263 assert_eq!(combined.values()[2], Scalar::Int64(3));
21264 }
21265
21266 #[test]
21267 fn concat_different_dtypes_errors() {
21268 let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
21269 let b = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("b");
21270 let err = a.concat(&b).unwrap_err();
21271 assert!(matches!(err, crate::ColumnError::DTypeMismatch { .. }));
21272 }
21273
21274 #[test]
21275 fn repeat_duplicates_contiguously() {
21276 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21277 let out = col.repeat(3).expect("repeat");
21278 assert_eq!(out.len(), 6);
21279 assert_eq!(out.values()[0], Scalar::Int64(1));
21280 assert_eq!(out.values()[1], Scalar::Int64(1));
21281 assert_eq!(out.values()[2], Scalar::Int64(1));
21282 assert_eq!(out.values()[3], Scalar::Int64(2));
21283 }
21284
21285 #[test]
21286 fn repeat_zero_is_empty_same_dtype() {
21287 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
21288 let out = col.repeat(0).expect("repeat");
21289 assert!(out.is_empty());
21290 assert_eq!(out.dtype(), DType::Int64);
21291 }
21292
21293 #[test]
21294 fn repeat_one_is_clone() {
21295 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21296 let out = col.repeat(1).expect("repeat");
21297 assert_eq!(out.values(), col.values());
21298 }
21299 }
21300
21301 mod reverse_head_tail_cumulatives_unique {
21302 use fp_types::NullKind;
21303
21304 use super::*;
21305
21306 #[test]
21307 fn reverse_swaps_order_and_preserves_dtype() {
21308 let col =
21309 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21310 .expect("col");
21311 let r = col.reverse().expect("reverse");
21312 assert_eq!(r.values()[0], Scalar::Int64(3));
21313 assert_eq!(r.values()[2], Scalar::Int64(1));
21314 assert_eq!(r.dtype(), DType::Int64);
21315 }
21316
21317 #[test]
21318 fn head_positive_takes_first_n() {
21319 let col = Column::from_values(vec![
21320 Scalar::Int64(1),
21321 Scalar::Int64(2),
21322 Scalar::Int64(3),
21323 Scalar::Int64(4),
21324 ])
21325 .expect("col");
21326 let h = col.head(2).expect("head");
21327 assert_eq!(h.len(), 2);
21328 assert_eq!(h.values()[0], Scalar::Int64(1));
21329 assert_eq!(h.values()[1], Scalar::Int64(2));
21330 }
21331
21332 #[test]
21333 fn head_negative_drops_last_n() {
21334 let col =
21335 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21336 .expect("col");
21337 let h = col.head(-1).expect("head");
21338 assert_eq!(h.len(), 2);
21339 assert_eq!(h.values()[1], Scalar::Int64(2));
21340 }
21341
21342 #[test]
21343 fn tail_positive_takes_last_n() {
21344 let col = Column::from_values(vec![
21345 Scalar::Int64(1),
21346 Scalar::Int64(2),
21347 Scalar::Int64(3),
21348 Scalar::Int64(4),
21349 ])
21350 .expect("col");
21351 let t = col.tail(2).expect("tail");
21352 assert_eq!(t.len(), 2);
21353 assert_eq!(t.values()[0], Scalar::Int64(3));
21354 assert_eq!(t.values()[1], Scalar::Int64(4));
21355 }
21356
21357 #[test]
21358 fn tail_negative_drops_first_n() {
21359 let col =
21360 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21361 .expect("col");
21362 let t = col.tail(-1).expect("tail");
21363 assert_eq!(t.len(), 2);
21364 assert_eq!(t.values()[0], Scalar::Int64(2));
21365 }
21366
21367 #[test]
21368 fn head_tail_out_of_range_clamps() {
21369 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
21370 assert_eq!(col.head(10).expect("head").len(), 1);
21371 assert_eq!(col.tail(10).expect("tail").len(), 1);
21372 assert_eq!(col.head(-10).expect("head").len(), 0);
21373 assert_eq!(col.tail(-10).expect("tail").len(), 0);
21374 }
21375
21376 #[test]
21377 fn cumsum_produces_float64_running_sum() {
21378 let col = Column::from_values(vec![
21379 Scalar::Float64(1.0),
21380 Scalar::Null(NullKind::NaN),
21381 Scalar::Float64(3.0),
21382 ])
21383 .expect("col");
21384 let c = col.cumsum().expect("cumsum");
21385 assert_eq!(c.dtype(), DType::Float64);
21386 assert_eq!(c.values()[0], Scalar::Float64(1.0));
21387 assert!(c.values()[1].is_missing());
21388 assert_eq!(c.values()[2], Scalar::Float64(4.0));
21389 }
21390
21391 #[test]
21392 fn cumprod_running_product() {
21393 let col = Column::from_values(vec![
21394 Scalar::Float64(2.0),
21395 Scalar::Float64(3.0),
21396 Scalar::Float64(4.0),
21397 ])
21398 .expect("col");
21399 let c = col.cumprod().expect("cumprod");
21400 assert_eq!(c.values()[2], Scalar::Float64(24.0));
21401 }
21402
21403 #[test]
21404 fn cummax_cummin_running_extrema() {
21405 let col = Column::from_values(vec![
21406 Scalar::Float64(3.0),
21407 Scalar::Float64(1.0),
21408 Scalar::Float64(4.0),
21409 Scalar::Float64(1.0),
21410 Scalar::Float64(5.0),
21411 ])
21412 .expect("col");
21413 let mx = col.cummax().expect("cummax");
21414 assert_eq!(mx.values()[4], Scalar::Float64(5.0));
21415 let mn = col.cummin().expect("cummin");
21416 assert_eq!(mn.values()[4], Scalar::Float64(1.0));
21417 }
21418
21419 #[test]
21420 fn unique_preserves_first_seen_order() {
21421 let col = Column::from_values(vec![
21422 Scalar::Int64(3),
21423 Scalar::Int64(1),
21424 Scalar::Int64(3),
21425 Scalar::Int64(2),
21426 Scalar::Int64(1),
21427 ])
21428 .expect("col");
21429 let u = col.unique().expect("unique");
21430 assert_eq!(u.len(), 3);
21431 assert_eq!(u.values()[0], Scalar::Int64(3));
21432 assert_eq!(u.values()[1], Scalar::Int64(1));
21433 assert_eq!(u.values()[2], Scalar::Int64(2));
21434 }
21435
21436 #[test]
21437 fn unique_drops_nulls() {
21438 let col = Column::from_values(vec![
21439 Scalar::Int64(1),
21440 Scalar::Null(NullKind::NaN),
21441 Scalar::Int64(1),
21442 Scalar::Null(NullKind::NaN),
21443 ])
21444 .expect("col");
21445 let u = col.unique().expect("unique");
21446 assert_eq!(u.len(), 1);
21447 assert_eq!(u.values()[0], Scalar::Int64(1));
21448 }
21449 }
21450
21451 mod abs_shift_clip_round_isin {
21452 use fp_types::NullKind;
21453
21454 use super::*;
21455
21456 #[test]
21457 fn abs_int_and_float() {
21458 let int_col =
21459 Column::from_values(vec![Scalar::Int64(-3), Scalar::Int64(0), Scalar::Int64(5)])
21460 .expect("int");
21461 let a = int_col.abs().expect("abs");
21462 assert_eq!(a.values()[0], Scalar::Int64(3));
21463 assert_eq!(a.values()[1], Scalar::Int64(0));
21464
21465 let float_col =
21466 Column::from_values(vec![Scalar::Float64(-1.5), Scalar::Null(NullKind::NaN)])
21467 .expect("float");
21468 let b = float_col.abs().expect("abs");
21469 assert_eq!(b.values()[0], Scalar::Float64(1.5));
21470 assert!(b.values()[1].is_missing());
21471 }
21472
21473 #[test]
21474 fn abs_bool_preserves_dtype() {
21475 let bool_col =
21476 Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("bool");
21477 let result = bool_col.abs().expect("abs");
21478 assert_eq!(result.dtype(), DType::Bool);
21479 assert_eq!(result.values(), &[Scalar::Bool(true), Scalar::Bool(false)]);
21480 }
21481
21482 #[test]
21483 fn abs_utf8_errors() {
21484 let col = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("col");
21485 assert!(col.abs().is_err());
21486 }
21487
21488 #[test]
21489 fn shift_positive_pads_left_with_fill() {
21490 let col =
21491 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21492 .expect("col");
21493 let s = col.shift(1, Scalar::Null(NullKind::NaN)).expect("shift");
21494 assert!(s.values()[0].is_missing());
21495 assert_eq!(s.values()[1], Scalar::Int64(1));
21496 assert_eq!(s.values()[2], Scalar::Int64(2));
21497 }
21498
21499 #[test]
21500 fn shift_negative_pads_right() {
21501 let col =
21502 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
21503 .expect("col");
21504 let s = col.shift(-1, Scalar::Int64(0)).expect("shift");
21505 assert_eq!(s.values()[0], Scalar::Int64(2));
21506 assert_eq!(s.values()[1], Scalar::Int64(3));
21507 assert_eq!(s.values()[2], Scalar::Int64(0));
21508 }
21509
21510 #[test]
21511 fn shift_zero_is_clone() {
21512 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21513 let s = col.shift(0, Scalar::Int64(-1)).expect("shift");
21514 assert_eq!(s.values(), col.values());
21515 }
21516
21517 #[test]
21518 fn clip_both_bounds() {
21519 let col = Column::from_values(vec![
21520 Scalar::Float64(-5.0),
21521 Scalar::Float64(3.0),
21522 Scalar::Float64(10.0),
21523 ])
21524 .expect("col");
21525 let c = col.clip(Some(0.0), Some(5.0)).expect("clip");
21526 assert_eq!(c.values()[0], Scalar::Float64(0.0));
21527 assert_eq!(c.values()[1], Scalar::Float64(3.0));
21528 assert_eq!(c.values()[2], Scalar::Float64(5.0));
21529 }
21530
21531 #[test]
21532 fn clip_none_bounds_are_noop() {
21533 let col = Column::from_values(vec![Scalar::Float64(-5.0), Scalar::Float64(10.0)])
21534 .expect("col");
21535 let c = col.clip(None, None).expect("clip");
21536 assert_eq!(c.values()[0], Scalar::Float64(-5.0));
21537 assert_eq!(c.values()[1], Scalar::Float64(10.0));
21538 }
21539
21540 #[test]
21541 fn clip_scalar_bounds_match_clamp_oracle_t3idc() {
21542 fn next(seed: &mut u64) -> u64 {
21545 *seed = seed
21546 .wrapping_mul(1181783497276652981)
21547 .wrapping_add(1013904223);
21548 *seed
21549 }
21550
21551 fn bound(seed: &mut u64) -> Option<f64> {
21552 match next(seed) % 7 {
21553 0 => None,
21554 1 => Some(f64::NAN),
21555 _ => {
21556 let raw = (next(seed) % 20_001) as i64 - 10_000;
21557 Some(raw as f64 / 17.0)
21558 }
21559 }
21560 }
21561
21562 fn normalize(bound: Option<f64>) -> Option<f64> {
21563 bound.filter(|v| !v.is_nan())
21564 }
21565
21566 fn clamp_oracle(mut value: f64, lower: Option<f64>, upper: Option<f64>) -> f64 {
21567 if let Some(lo) = lower
21568 && value < lo
21569 {
21570 value = lo;
21571 }
21572 if let Some(hi) = upper
21573 && value > hi
21574 {
21575 value = hi;
21576 }
21577 value
21578 }
21579
21580 let mut seed = 0x0c11_f0b0_a7e5_d1dc_u64;
21581 for case in 0..220 {
21582 let len = (next(&mut seed) % 61 + 1) as usize;
21583 let mut lower = bound(&mut seed);
21584 let mut upper = bound(&mut seed);
21585 if let (Some(lo), Some(hi)) = (normalize(lower), normalize(upper))
21586 && lo > hi
21587 {
21588 lower = Some(hi);
21589 upper = Some(lo);
21590 }
21591 let expected_lower = normalize(lower);
21592 let expected_upper = normalize(upper);
21593
21594 let mut values = Vec::with_capacity(len);
21595 for _ in 0..len {
21596 let selector = next(&mut seed) % 43;
21597 let whole = (next(&mut seed) % 100_001) as i64 - 50_000;
21598 let frac = (next(&mut seed) % 1000) as f64 / 1000.0;
21599 values.push(match selector {
21600 0 => Scalar::Null(NullKind::NaN),
21601 1 => Scalar::Float64(f64::NAN),
21602 _ => Scalar::Float64(whole as f64 / 19.0 + frac),
21603 });
21604 }
21605
21606 let input = Column::from_values(values.clone()).expect("column");
21607 let clipped = input.clip(lower, upper).expect("clip");
21608 assert_eq!(clipped.dtype(), DType::Float64);
21609 assert_eq!(clipped.values().len(), values.len());
21610 for (pos, (before, after)) in values.iter().zip(clipped.values()).enumerate() {
21611 if before.is_missing() {
21612 assert!(
21613 after.is_missing(),
21614 "case={case} pos={pos}: missing became {after:?}"
21615 );
21616 continue;
21617 }
21618
21619 let expected = match before {
21620 Scalar::Float64(v) => clamp_oracle(*v, expected_lower, expected_upper),
21621 other => panic!("unexpected non-float value: {other:?}"),
21622 };
21623 match after {
21624 Scalar::Float64(got) => assert_eq!(
21625 *got, expected,
21626 "case={case} pos={pos}: got {got}, expected {expected}"
21627 ),
21628 other => panic!("case={case} pos={pos}: expected Float64, got {other:?}"),
21629 }
21630 }
21631 }
21632 }
21633
21634 #[test]
21635 fn round_rounds_floats() {
21636 let col = Column::from_values(vec![
21637 Scalar::Float64(1.234),
21638 Scalar::Float64(5.678),
21639 Scalar::Null(NullKind::NaN),
21640 ])
21641 .expect("col");
21642 let r = col.round(1).expect("round");
21643 assert_eq!(r.values()[0], Scalar::Float64(1.2));
21644 assert_eq!(r.values()[1], Scalar::Float64(5.7));
21645 assert!(r.values()[2].is_missing());
21646 }
21647
21648 #[test]
21649 fn round_int_nonnegative_decimals_is_noop() {
21650 let col = Column::from_values(vec![Scalar::Int64(12), Scalar::Int64(34)]).expect("col");
21651 let r = col.round(2).expect("round");
21652 assert_eq!(r.values(), col.values());
21653 assert_eq!(r.dtype(), DType::Int64);
21654 }
21655
21656 #[test]
21657 fn round_int_negative_decimals_preserves_dtype() {
21658 let col = Column::from_values(vec![
21659 Scalar::Int64(15),
21660 Scalar::Int64(25),
21661 Scalar::Int64(35),
21662 Scalar::Int64(-15),
21663 ])
21664 .expect("col");
21665 let r = col.round(-1).expect("round");
21666 assert_eq!(r.dtype(), DType::Int64);
21667 assert_eq!(
21668 r.values(),
21669 &[
21670 Scalar::Int64(20),
21671 Scalar::Int64(20),
21672 Scalar::Int64(40),
21673 Scalar::Int64(-20)
21674 ]
21675 );
21676 }
21677
21678 #[test]
21679 fn round_bool_is_noop() {
21680 let col =
21681 Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("col");
21682 let r = col.round(-2).expect("round");
21683 assert_eq!(r.dtype(), DType::Bool);
21684 assert_eq!(r.values(), col.values());
21685 }
21686
21687 #[test]
21688 fn round_negative_decimals_rounds_left() {
21689 let col = Column::from_values(vec![Scalar::Float64(1234.0)]).expect("col");
21690 let r = col.round(-2).expect("round");
21691 assert_eq!(r.values()[0], Scalar::Float64(1200.0));
21692 }
21693
21694 #[test]
21695 fn round_uses_pandas_half_even_ties() {
21696 let col = Column::from_values(vec![
21697 Scalar::Float64(1.5),
21698 Scalar::Float64(2.5),
21699 Scalar::Float64(-1.5),
21700 Scalar::Float64(3.5),
21701 ])
21702 .expect("col");
21703 let r = col.round(0).expect("round");
21704 assert_eq!(
21705 r.values(),
21706 &[
21707 Scalar::Float64(2.0),
21708 Scalar::Float64(2.0),
21709 Scalar::Float64(-2.0),
21710 Scalar::Float64(4.0)
21711 ]
21712 );
21713 }
21714
21715 #[test]
21716 fn round_negative_decimals_uses_half_even_ties() {
21717 let col = Column::from_values(vec![
21718 Scalar::Float64(15.0),
21719 Scalar::Float64(25.0),
21720 Scalar::Float64(35.0),
21721 Scalar::Float64(-15.0),
21722 ])
21723 .expect("col");
21724 let r = col.round(-1).expect("round");
21725 assert_eq!(
21726 r.values(),
21727 &[
21728 Scalar::Float64(20.0),
21729 Scalar::Float64(20.0),
21730 Scalar::Float64(40.0),
21731 Scalar::Float64(-20.0)
21732 ]
21733 );
21734 }
21735
21736 #[test]
21737 fn floor_ceil_trunc_match_scalar_oracle_61try() {
21738 fn next(seed: &mut u64) -> u64 {
21741 *seed = seed
21742 .wrapping_mul(3202034522624059733)
21743 .wrapping_add(4354685564936845319);
21744 *seed
21745 }
21746
21747 fn floor_oracle(v: f64) -> f64 {
21748 v.floor()
21749 }
21750
21751 fn ceil_oracle(v: f64) -> f64 {
21752 v.ceil()
21753 }
21754
21755 fn trunc_oracle(v: f64) -> f64 {
21756 v.trunc()
21757 }
21758
21759 let mut seed = 0x61d1_ff10_0ce1_cafe_u64;
21760 for case in 0..240 {
21761 let len = (next(&mut seed) % 59 + 1) as usize;
21762 let mut values = Vec::with_capacity(len);
21763 for _ in 0..len {
21764 let selector = next(&mut seed) % 37;
21765 let whole = (next(&mut seed) % 500_001) as i64 - 250_000;
21766 let frac = (next(&mut seed) % 100_000) as f64 / 100_000.0;
21767 let sign = if next(&mut seed) & 1 == 0 { 1.0 } else { -1.0 };
21768 let value = sign * (whole as f64 / 13.0 + frac);
21769 values.push(match selector {
21770 0 => Scalar::Null(NullKind::NaN),
21771 1 => Scalar::Float64(f64::NAN),
21772 _ => Scalar::Float64(value),
21773 });
21774 }
21775
21776 let input = Column::from_values(values.clone()).expect("column");
21777 type UnaryFloatOutput = (&'static str, Column, fn(f64) -> f64);
21778 let outputs: [UnaryFloatOutput; 3] = [
21779 ("floor", input.floor().expect("floor"), floor_oracle),
21780 ("ceil", input.ceil().expect("ceil"), ceil_oracle),
21781 ("trunc", input.trunc().expect("trunc"), trunc_oracle),
21782 ];
21783
21784 for (op, output, oracle) in outputs {
21785 assert_eq!(output.dtype(), DType::Float64, "{op} dtype drift");
21786 assert_eq!(output.values().len(), values.len(), "{op} length drift");
21787 for (pos, (before, after)) in values.iter().zip(output.values()).enumerate() {
21788 if before.is_missing() {
21789 assert!(
21790 after.is_missing(),
21791 "{op} case={case} pos={pos}: missing became {after:?}"
21792 );
21793 continue;
21794 }
21795
21796 let expected = match before {
21797 Scalar::Float64(v) => oracle(*v),
21798 other => panic!("{op} unexpected non-float value: {other:?}"),
21799 };
21800 match after {
21801 Scalar::Float64(got) => assert_eq!(
21802 *got, expected,
21803 "{op} case={case} pos={pos}: got {got}, expected {expected}"
21804 ),
21805 other => panic!(
21806 "{op} case={case} pos={pos}: expected Float64, got {other:?}"
21807 ),
21808 }
21809 }
21810 }
21811 }
21812 }
21813
21814 #[test]
21815 fn isin_returns_bool_column() {
21816 let col = Column::from_values(vec![
21817 Scalar::Int64(1),
21818 Scalar::Int64(2),
21819 Scalar::Int64(3),
21820 Scalar::Null(NullKind::NaN),
21821 ])
21822 .expect("col");
21823 let needles = vec![Scalar::Int64(1), Scalar::Int64(3)];
21824 let r = col.isin(&needles).expect("isin");
21825 assert_eq!(r.dtype(), DType::Bool);
21826 assert_eq!(r.values()[0], Scalar::Bool(true));
21827 assert_eq!(r.values()[1], Scalar::Bool(false));
21828 assert_eq!(r.values()[2], Scalar::Bool(true));
21829 assert_eq!(r.values()[3], Scalar::Bool(false));
21830 }
21831
21832 #[test]
21833 fn isin_empty_needles_yields_all_false() {
21834 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
21835 let r = col.isin(&[]).expect("isin");
21836 assert_eq!(r.values()[0], Scalar::Bool(false));
21837 assert_eq!(r.values()[1], Scalar::Bool(false));
21838 }
21839 }
21840
21841 mod sort_diff_duplicated_between {
21842 use fp_types::NullKind;
21843
21844 use super::*;
21845
21846 #[test]
21847 fn sort_values_ascending_puts_nulls_last() {
21848 let col = Column::from_values(vec![
21849 Scalar::Int64(3),
21850 Scalar::Null(NullKind::NaN),
21851 Scalar::Int64(1),
21852 Scalar::Int64(2),
21853 ])
21854 .expect("col");
21855 let s = col.sort_values(true).expect("sort");
21856 assert_eq!(s.values()[0], Scalar::Int64(1));
21857 assert_eq!(s.values()[1], Scalar::Int64(2));
21858 assert_eq!(s.values()[2], Scalar::Int64(3));
21859 assert!(s.values()[3].is_missing());
21860 }
21861
21862 #[test]
21863 fn sort_values_descending_keeps_nulls_last() {
21864 let col = Column::from_values(vec![
21865 Scalar::Int64(1),
21866 Scalar::Null(NullKind::NaN),
21867 Scalar::Int64(3),
21868 Scalar::Int64(2),
21869 ])
21870 .expect("col");
21871 let s = col.sort_values(false).expect("sort");
21872 assert_eq!(s.values()[0], Scalar::Int64(3));
21873 assert_eq!(s.values()[1], Scalar::Int64(2));
21874 assert_eq!(s.values()[2], Scalar::Int64(1));
21875 assert!(s.values()[3].is_missing());
21876 }
21877
21878 #[test]
21879 fn argsort_matches_take_sort_values() {
21880 let col =
21881 Column::from_values(vec![Scalar::Int64(3), Scalar::Int64(1), Scalar::Int64(2)])
21882 .expect("col");
21883 let positions = col.argsort();
21884 assert_eq!(positions, vec![1, 2, 0]);
21885 let via_take = col.take(&positions).expect("take");
21886 let via_sort = col.sort_values(true).expect("sort");
21887 assert_eq!(via_take.values(), via_sort.values());
21888 }
21889
21890 fn scalar_sort_reference(values: &[Scalar], ascending: bool) -> Vec<Scalar> {
21893 let mut indexed: Vec<(usize, &Scalar)> = values.iter().enumerate().collect();
21894 indexed.sort_by(|a, b| crate::compare_scalars_na_last(a.1, b.1, ascending));
21895 indexed.into_iter().map(|(_, v)| v.clone()).collect()
21896 }
21897
21898 #[test]
21899 fn radix_sort_matches_scalar_reference_i64_and_f64() {
21900 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
21904 let mut next = || {
21905 state = state
21906 .wrapping_mul(6364136223846793005)
21907 .wrapping_add(1442695040888963407);
21908 state
21909 };
21910 for trial in 0..200 {
21911 let n = (next() % 400) as usize + 1;
21912 let i64_vals: Vec<Scalar> = (0..n)
21913 .map(|_| {
21914 let r = next();
21916 let v = if r % 7 == 0 {
21917 r as i64 } else {
21919 (r % 11) as i64 - 5
21920 };
21921 Scalar::Int64(v)
21922 })
21923 .collect();
21924 let f64_vals: Vec<Scalar> = i64_vals
21925 .iter()
21926 .map(|s| match s {
21927 Scalar::Int64(v) => {
21928 let f = (*v as f64) / 4.0;
21930 Scalar::Float64(if f == 0.0 { 0.0 } else { f })
21931 }
21932 _ => unreachable!(),
21933 })
21934 .collect();
21935 for (vals, label) in [(&i64_vals, "i64"), (&f64_vals, "f64")] {
21936 let col = Column::from_values(vals.clone()).expect("col");
21937 assert!(
21939 col.validity.all(),
21940 "{label} trial {trial}: unexpected missing"
21941 );
21942 for ascending in [true, false] {
21943 let got = col.sort_values(ascending).expect("sort").values().to_vec();
21944 let want = scalar_sort_reference(vals, ascending);
21945 assert_eq!(
21946 got, want,
21947 "{label} trial {trial} asc={ascending} sort mismatch"
21948 );
21949 }
21950 let perm = col.argsort();
21952 let via_perm: Vec<Scalar> = perm.iter().map(|&i| vals[i].clone()).collect();
21953 assert_eq!(
21954 via_perm,
21955 scalar_sort_reference(vals, true),
21956 "{label} trial {trial} argsort mismatch"
21957 );
21958 }
21959 }
21960 }
21961
21962 #[test]
21963 fn contiguous_utf8_argsort_matches_scalar_reference() {
21964 let raw = ["bee", "alpha", "bee", "alphabet", "", "zulu"];
21965 let scalars: Vec<Scalar> = raw
21966 .iter()
21967 .map(|value| Scalar::Utf8((*value).to_owned()))
21968 .collect();
21969 let scalar_col = Column::from_values(scalars.clone()).expect("scalar col");
21970 let mut bytes = Vec::new();
21971 let mut offsets = Vec::with_capacity(raw.len() + 1);
21972 offsets.push(0);
21973 for value in raw {
21974 bytes.extend_from_slice(value.as_bytes());
21975 offsets.push(bytes.len());
21976 }
21977 let contiguous_col = Column::from_utf8_contiguous(bytes, offsets);
21978
21979 assert_eq!(contiguous_col.argsort_with(true), vec![4, 1, 3, 0, 2, 5]);
21980 assert_eq!(contiguous_col.argsort_with(false), vec![5, 0, 2, 3, 1, 4]);
21981 for ascending in [true, false] {
21982 let got = contiguous_col
21983 .sort_values(ascending)
21984 .expect("contiguous sort")
21985 .values()
21986 .to_vec();
21987 let want = scalar_col
21988 .sort_values(ascending)
21989 .expect("scalar sort")
21990 .values()
21991 .to_vec();
21992 assert_eq!(got, want, "ascending={ascending}");
21993 }
21994 }
21995
21996 #[test]
21997 fn parallel_msd_radix_matches_serial_reference_qdrp7() {
21998 let n = 40_000usize;
22002 let strings: Vec<String> = (0..n)
22003 .map(|i| {
22004 let mixed = (i as u64)
22005 .wrapping_mul(0x9E37_79B9_7F4A_7C15)
22006 .rotate_left(17)
22007 ^ (i as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);
22008 format!("key_{mixed:016x}_{:04}", i % 97)
22009 })
22010 .collect();
22011 let spans: Vec<&[u8]> = strings.iter().map(|s| s.as_bytes()).collect();
22012 for ascending in [true, false] {
22013 let got = crate::utf8_msd_argsort_bytes(&spans, ascending);
22014 let mut want: Vec<usize> = (0..n).collect();
22015 want.sort_by(|&a, &b| {
22016 let ord = spans[a].cmp(spans[b]);
22017 if ascending { ord } else { ord.reverse() }
22018 });
22019 assert_eq!(
22020 got, want,
22021 "parallel radix != stable byte sort (asc={ascending})"
22022 );
22023 }
22024 }
22025
22026 #[test]
22027 fn contiguous_utf8_strict_witness_matches_byte_order_483i5() {
22028 fn contiguous(values: &[&str]) -> Column {
22029 let mut bytes = Vec::new();
22030 let mut offsets = Vec::with_capacity(values.len() + 1);
22031 offsets.push(0);
22032 for value in values {
22033 bytes.extend_from_slice(value.as_bytes());
22034 offsets.push(bytes.len());
22035 }
22036 Column::from_utf8_contiguous(bytes, offsets)
22037 }
22038
22039 assert!(
22040 contiguous(&["a", "b", "c"])
22041 .as_strictly_increasing_utf8_contiguous()
22042 .is_some()
22043 );
22044 assert!(
22045 contiguous(&[])
22046 .as_strictly_increasing_utf8_contiguous()
22047 .is_some()
22048 );
22049 assert!(
22050 contiguous(&["only"])
22051 .as_strictly_increasing_utf8_contiguous()
22052 .is_some()
22053 );
22054 assert!(
22055 contiguous(&["a", "a"])
22056 .as_strictly_increasing_utf8_contiguous()
22057 .is_none()
22058 );
22059 assert!(
22060 contiguous(&["b", "a"])
22061 .as_strictly_increasing_utf8_contiguous()
22062 .is_none()
22063 );
22064
22065 let scalar_backed = Column::from_values(vec![
22066 Scalar::Utf8("a".to_owned()),
22067 Scalar::Utf8("b".to_owned()),
22068 ])
22069 .expect("scalar-backed utf8");
22070 assert!(
22071 scalar_backed
22072 .as_strictly_increasing_utf8_contiguous()
22073 .is_none()
22074 );
22075 }
22076
22077 #[test]
22078 fn contiguous_utf8_lower_hex_sequence_certificate_jbyuc111111() {
22079 fn contiguous(values: &[&str]) -> Column {
22080 let mut bytes = Vec::new();
22081 let mut offsets = Vec::with_capacity(values.len() + 1);
22082 offsets.push(0);
22083 for value in values {
22084 bytes.extend_from_slice(value.as_bytes());
22085 offsets.push(bytes.len());
22086 }
22087 Column::from_utf8_contiguous(bytes, offsets)
22088 }
22089
22090 let certified = contiguous(&["id_0000000a", "id_0000000b", "id_0000000c"]);
22091 let (_, _, certificate) = certified
22092 .as_lower_hex_sequence_utf8_contiguous()
22093 .expect("lower-hex sequence certificate");
22094 assert_eq!(certificate.prefix_len(), 3);
22095 assert_eq!(certificate.hex_width(), 8);
22096 assert_eq!(certificate.width(), 11);
22097 assert_eq!(certificate.start(), 10);
22098 assert_eq!(certificate.value_at(2), Some(12));
22099
22100 assert!(
22101 contiguous(&["id_0000000a", "id_0000000c"])
22102 .as_lower_hex_sequence_utf8_contiguous()
22103 .is_none(),
22104 "gapped sequences are not certified"
22105 );
22106 assert!(
22107 contiguous(&["id_0000000a", "id_0000000B"])
22108 .as_lower_hex_sequence_utf8_contiguous()
22109 .is_none(),
22110 "uppercase hex is not certified by the lowercase witness"
22111 );
22112 assert!(
22113 contiguous(&["0000000a", "0000000b"])
22114 .as_lower_hex_sequence_utf8_contiguous()
22115 .is_none(),
22116 "a prefix is required so arbitrary all-hex strings fall back"
22117 );
22118 }
22119
22120 #[test]
22121 fn lower_hex_sequence_constructor_matches_contiguous_utf8_3wo1d() {
22122 let seeded =
22123 Column::from_lower_hex_sequence_utf8(b"id_", 0x0a, 3, 8).expect("seeded column");
22124 let manual = {
22125 let values = ["id_0000000a", "id_0000000b", "id_0000000c"];
22126 let mut bytes = Vec::new();
22127 let mut offsets = Vec::with_capacity(values.len() + 1);
22128 offsets.push(0);
22129 for value in values {
22130 bytes.extend_from_slice(value.as_bytes());
22131 offsets.push(bytes.len());
22132 }
22133 Column::from_utf8_contiguous(bytes, offsets)
22134 };
22135
22136 assert_eq!(seeded.values(), manual.values());
22137 let (_, _, certificate) = seeded
22138 .as_lower_hex_sequence_utf8_contiguous()
22139 .expect("seeded certificate");
22140 assert_eq!(certificate.prefix_len(), 3);
22141 assert_eq!(certificate.hex_width(), 8);
22142 assert_eq!(certificate.width(), 11);
22143 assert_eq!(certificate.start(), 10);
22144 assert_eq!(certificate.value_at(2), Some(12));
22145
22146 let empty =
22147 Column::from_lower_hex_sequence_utf8(b"id_", 0x0a, 0, 8).expect("empty column");
22148 assert!(empty.values().is_empty());
22149 assert!(empty.as_lower_hex_sequence_utf8_contiguous().is_none());
22150 let (empty_prefix, empty_certificate, empty_len) = empty
22151 .as_lower_hex_sequence_utf8()
22152 .expect("empty direct witness");
22153 assert_eq!(empty_prefix, b"id_");
22154 assert_eq!(empty_certificate.start(), 10);
22155 assert_eq!(empty_len, 0);
22156
22157 assert!(Column::from_lower_hex_sequence_utf8(b"id_", 0x0e, 3, 1).is_none());
22158 assert!(Column::from_lower_hex_sequence_utf8(b"", 0x0a, 3, 8).is_none());
22159 }
22160
22161 #[test]
22162 fn lower_hex_sequence_witness_stays_lazy_uza0447() {
22163 let column =
22164 Column::from_lower_hex_sequence_utf8(b"id_", 0x0a, 3, 8).expect("seeded column");
22165 assert!(matches!(
22166 &column.values,
22167 ScalarValues::LazyLowerHexSequenceUtf8 { .. }
22168 ));
22169 let ScalarValues::LazyLowerHexSequenceUtf8 { buffers, .. } = &column.values else {
22170 return;
22171 };
22172 assert!(buffers.get().is_none());
22173
22174 let (prefix, certificate, len) =
22175 column.as_lower_hex_sequence_utf8().expect("direct witness");
22176 assert_eq!(prefix, b"id_");
22177 assert_eq!(certificate.prefix_len(), 3);
22178 assert_eq!(certificate.hex_width(), 8);
22179 assert_eq!(certificate.start(), 10);
22180 assert_eq!(len, 3);
22181 assert!(
22182 buffers.get().is_none(),
22183 "direct witness must not materialize bytes"
22184 );
22185
22186 let (_, _, contiguous_certificate) = column
22187 .as_lower_hex_sequence_utf8_contiguous()
22188 .expect("contiguous materialization");
22189 assert_eq!(contiguous_certificate, certificate);
22190 assert!(
22191 buffers.get().is_some(),
22192 "contiguous accessor materializes exact old byte layout"
22193 );
22194 }
22195
22196 #[test]
22197 fn lower_hex_sequence_constructor_preserves_carry_uza0446() {
22198 let seeded =
22199 Column::from_lower_hex_sequence_utf8(b"id_", 0x0e, 4, 2).expect("seeded column");
22200 let manual = {
22201 let values = ["id_0e", "id_0f", "id_10", "id_11"];
22202 let mut bytes = Vec::new();
22203 let mut offsets = Vec::with_capacity(values.len() + 1);
22204 offsets.push(0);
22205 for value in values {
22206 bytes.extend_from_slice(value.as_bytes());
22207 offsets.push(bytes.len());
22208 }
22209 Column::from_utf8_contiguous(bytes, offsets)
22210 };
22211
22212 assert_eq!(seeded.values(), manual.values());
22213 let (_, _, certificate) = seeded
22214 .as_lower_hex_sequence_utf8_contiguous()
22215 .expect("seeded certificate");
22216 assert_eq!(certificate.prefix_len(), 3);
22217 assert_eq!(certificate.hex_width(), 2);
22218 assert_eq!(certificate.width(), 5);
22219 assert_eq!(certificate.start(), 14);
22220 assert_eq!(certificate.value_at(3), Some(17));
22221 }
22222
22223 #[test]
22224 fn abs_typed_matches_scalar_reference() {
22225 let mut state: u64 = 0x2545_F491_4F6C_DD1D;
22229 let mut next = || {
22230 state = state
22231 .wrapping_mul(6364136223846793005)
22232 .wrapping_add(1442695040888963407);
22233 state
22234 };
22235 for trial in 0..150 {
22236 let n = (next() % 300) as usize + 1;
22237 let i64_vals: Vec<Scalar> = (0..n)
22238 .map(|_| {
22239 let r = next();
22240 if r % 50 == 0 {
22241 Scalar::Int64(i64::MIN)
22242 } else {
22243 Scalar::Int64((r % 2000) as i64 - 1000)
22244 }
22245 })
22246 .collect();
22247 let f64_vals: Vec<Scalar> = i64_vals
22248 .iter()
22249 .map(|s| match s {
22250 Scalar::Int64(v) => {
22251 let f = if *v == i64::MIN {
22252 -0.0
22253 } else {
22254 *v as f64 / 4.0
22255 };
22256 Scalar::Float64(f)
22257 }
22258 _ => unreachable!(),
22259 })
22260 .collect();
22261 for vals in [&i64_vals, &f64_vals] {
22262 let col = Column::from_values(vals.clone()).expect("col");
22263 let got = col.abs().expect("abs").values().to_vec();
22264 let want: Vec<Scalar> = vals
22265 .iter()
22266 .map(|v| match v {
22267 Scalar::Int64(x) => Scalar::Int64(x.wrapping_abs()),
22268 Scalar::Float64(x) => Scalar::Float64(x.abs()),
22269 other => other.clone(),
22270 })
22271 .collect();
22272 for (g, w) in got.iter().zip(&want) {
22274 match (g, w) {
22275 (Scalar::Float64(a), Scalar::Float64(b)) => {
22276 assert_eq!(a.to_bits(), b.to_bits(), "trial {trial} float abs")
22277 }
22278 _ => assert_eq!(g, w, "trial {trial} abs"),
22279 }
22280 }
22281 }
22282 }
22283 }
22284
22285 #[test]
22286 #[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
22287 fn abs_typed_timing_vs_scalar() {
22288 use std::time::Instant;
22289 let n = 5_000_000usize;
22290 let iters = 10;
22291 let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
22292 let mut next = || {
22293 state = state
22294 .wrapping_mul(6364136223846793005)
22295 .wrapping_add(1442695040888963407);
22296 state
22297 };
22298 let data: Vec<f64> = (0..n)
22299 .map(|_| (next() % 2_000_000) as f64 - 1_000_000.0)
22300 .collect();
22301 let mk = || Column::from_f64_values(data.clone());
22302
22303 let t0 = Instant::now();
22304 let mut chk = 0usize;
22305 for _ in 0..iters {
22306 chk ^= mk().abs().unwrap().len();
22307 }
22308 let typed = t0.elapsed();
22309
22310 let t1 = Instant::now();
22311 let mut chk2 = 0usize;
22312 for _ in 0..iters {
22313 let col = mk();
22314 let out: Vec<Scalar> = col
22315 .values()
22316 .iter()
22317 .map(|v| match v {
22318 Scalar::Float64(x) => Scalar::Float64(x.abs()),
22319 other => other.clone(),
22320 })
22321 .collect();
22322 chk2 ^= Column::new(DType::Float64, out).unwrap().len();
22323 }
22324 let scalar = t1.elapsed();
22325 let t2 = Instant::now();
22326 let mut sink = 0usize;
22327 for _ in 0..iters {
22328 sink ^= mk().len();
22329 }
22330 let build = t2.elapsed();
22331 let typed_op = typed.saturating_sub(build).as_secs_f64();
22332 let scalar_op = scalar.saturating_sub(build).as_secs_f64();
22333 eprintln!(
22334 "abs 5M f64 x{iters}: typed={typed:?} scalar={scalar:?} build={build:?} \
22335 op-only ratio={:.2}x (full {:.2}x, chk {chk}/{chk2}/{sink})",
22336 scalar_op / typed_op,
22337 scalar.as_secs_f64() / typed.as_secs_f64()
22338 );
22339 }
22340
22341 #[test]
22342 fn factorize_direct_address_matches_reference() {
22343 let mut state: u64 = 0x51A4_3C29_7E10_BB67;
22348 let mut next = || {
22349 state = state
22350 .wrapping_mul(6364136223846793005)
22351 .wrapping_add(1442695040888963407);
22352 state
22353 };
22354 for trial in 0..150 {
22355 let n = (next() % 300) as usize + 1;
22356 let data: Vec<i64> = (0..n).map(|_| (next() % 13) as i64 - 6).collect();
22357
22358 for sort in [false, true] {
22359 let mut uniques: Vec<i64> = Vec::new();
22362 let mut codes: Vec<i64> = Vec::with_capacity(n);
22363 for &v in &data {
22364 match uniques.iter().position(|&u| u == v) {
22365 Some(p) => codes.push(p as i64),
22366 None => {
22367 codes.push(uniques.len() as i64);
22368 uniques.push(v);
22369 }
22370 }
22371 }
22372 if sort {
22373 let mut order: Vec<usize> = (0..uniques.len()).collect();
22374 order.sort_by(|&a, &b| uniques[a].cmp(&uniques[b]));
22375 let mut remap = vec![0i64; uniques.len()];
22376 let sorted: Vec<i64> = order
22377 .iter()
22378 .enumerate()
22379 .map(|(new_pos, &orig)| {
22380 remap[orig] = new_pos as i64;
22381 uniques[orig]
22382 })
22383 .collect();
22384 for c in &mut codes {
22385 *c = remap[*c as usize];
22386 }
22387 uniques = sorted;
22388 }
22389
22390 let col = Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
22391 .expect("col");
22392 let (code_col, uniq_col) =
22393 col.factorize_with_options(sort, true).expect("factorize");
22394 let got_codes: Vec<i64> = code_col
22395 .values()
22396 .iter()
22397 .filter_map(|v| match v {
22398 Scalar::Int64(c) => Some(*c),
22399 _ => None,
22400 })
22401 .collect();
22402 let got_uniques: Vec<i64> = uniq_col
22403 .values()
22404 .iter()
22405 .filter_map(|v| match v {
22406 Scalar::Int64(c) => Some(*c),
22407 _ => None,
22408 })
22409 .collect();
22410 assert_eq!(got_codes.len(), code_col.len(), "non-int code");
22411 assert_eq!(got_uniques.len(), uniq_col.len(), "non-int unique");
22412 assert_eq!(got_codes, codes, "trial {trial} sort={sort} codes");
22413 assert_eq!(got_uniques, uniques, "trial {trial} sort={sort} uniques");
22414 }
22415 }
22416 }
22417
22418 #[test]
22419 #[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
22420 fn factorize_direct_address_timing_vs_hashmap() {
22421 use std::{collections::HashMap, time::Instant};
22422 let n = 5_000_000usize;
22423 let iters = 10;
22424 for cardinality in [1_000u64, 2_000_000u64] {
22425 let mut state: u64 = 0x2468_ACE0_1357_9BDF ^ cardinality;
22426 let mut next = || {
22427 state = state
22428 .wrapping_mul(6364136223846793005)
22429 .wrapping_add(1442695040888963407);
22430 state
22431 };
22432 let data: Vec<i64> = (0..n).map(|_| (next() % cardinality) as i64).collect();
22433
22434 let col = Column::from_i64_values(data.clone());
22435 let t0 = Instant::now();
22436 let mut chk = 0i64;
22437 for _ in 0..iters {
22438 let (codes, _u) = col.factorize_with_options(false, true).expect("da");
22439 if let Scalar::Int64(c) = &codes.values()[n - 1] {
22440 chk ^= *c;
22441 }
22442 }
22443 let direct = t0.elapsed();
22444
22445 let scalar_col =
22447 Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
22448 .expect("col");
22449 let t1 = Instant::now();
22450 let mut chk2 = 0i64;
22451 for _ in 0..iters {
22452 let mut map: HashMap<i64, i64> = HashMap::new();
22453 let mut uniques = 0i64;
22454 let mut last = 0i64;
22455 for v in scalar_col.values() {
22456 if let Scalar::Int64(i) = v {
22457 let code = *map.entry(*i).or_insert_with(|| {
22458 let c = uniques;
22459 uniques += 1;
22460 c
22461 });
22462 last = code;
22463 }
22464 }
22465 chk2 ^= last;
22466 }
22467 let scalar = t1.elapsed();
22468 eprintln!(
22469 "factorize 5M i64 card={cardinality} x{iters}: direct={direct:?} hashmap={scalar:?} ratio={:.2}x (chk {chk}/{chk2})",
22470 scalar.as_secs_f64() / direct.as_secs_f64()
22471 );
22472 }
22473 }
22474
22475 #[test]
22476 fn duplicated_typed_matches_bruteforce_reference() {
22477 let mut state: u64 = 0xD1B5_4A32_D192_ED03;
22483 let mut next = || {
22484 state = state
22485 .wrapping_mul(6364136223846793005)
22486 .wrapping_add(1442695040888963407);
22487 state
22488 };
22489 let fbits = |f: f64| (if f == 0.0 { 0.0 } else { f }).to_bits();
22490 for trial in 0..150 {
22491 let n = (next() % 300) as usize + 1;
22492 let raw: Vec<i64> = (0..n).map(|_| (next() % 9) as i64 - 4).collect();
22494 let i64_vals: Vec<Scalar> = raw.iter().map(|&v| Scalar::Int64(v)).collect();
22495 let f64_vals: Vec<Scalar> = raw
22496 .iter()
22497 .map(|&v| Scalar::Float64(v as f64 / 2.0))
22498 .collect();
22499 let i64_keys: Vec<i64> = raw.clone();
22500 let f64_keys: Vec<u64> = raw.iter().map(|&v| fbits(v as f64 / 2.0)).collect();
22501
22502 for keep in ["first", "last", "false"] {
22503 let bf = |eq_keys: &dyn Fn(usize, usize) -> bool| -> Vec<bool> {
22505 (0..n)
22506 .map(|i| match keep {
22507 "first" => (0..i).any(|j| eq_keys(i, j)),
22508 "last" => (i + 1..n).any(|j| eq_keys(i, j)),
22509 _ => (0..n).any(|j| j != i && eq_keys(i, j)),
22510 })
22511 .collect()
22512 };
22513 let want_i = bf(&|a, b| i64_keys[a] == i64_keys[b]);
22514 let want_f = bf(&|a, b| f64_keys[a] == f64_keys[b]);
22515
22516 let col_i = Column::from_values(i64_vals.clone()).expect("i64 col");
22517 let got_i: Vec<bool> = col_i
22518 .duplicated_keep(keep)
22519 .expect("dup i64")
22520 .values()
22521 .iter()
22522 .map(|v| matches!(v, Scalar::Bool(true)))
22523 .collect();
22524 assert_eq!(got_i, want_i, "i64 trial {trial} keep={keep}");
22525
22526 let col_f = Column::from_values(f64_vals.clone()).expect("f64 col");
22527 let got_f: Vec<bool> = col_f
22528 .duplicated_keep(keep)
22529 .expect("dup f64")
22530 .values()
22531 .iter()
22532 .map(|v| matches!(v, Scalar::Bool(true)))
22533 .collect();
22534 assert_eq!(got_f, want_f, "f64 trial {trial} keep={keep}");
22535 }
22536 }
22537 }
22538
22539 #[test]
22540 #[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
22541 fn duplicated_typed_timing_vs_scalar() {
22542 use std::{collections::HashSet, time::Instant};
22543 let n = 5_000_000usize;
22544 let iters = 10;
22545 #[derive(Hash, PartialEq, Eq)]
22548 enum OldKey {
22549 Int64(i64),
22550 Null,
22551 }
22552 for cardinality in [1_000u64, 2_000_000u64] {
22553 let mut state: u64 = 0x0FED_CBA9_8765_4321 ^ cardinality;
22554 let mut next = || {
22555 state = state
22556 .wrapping_mul(6364136223846793005)
22557 .wrapping_add(1442695040888963407);
22558 state
22559 };
22560 let data: Vec<i64> = (0..n).map(|_| (next() % cardinality) as i64).collect();
22561
22562 let col = Column::from_i64_values(data.clone());
22563 let t0 = Instant::now();
22564 let mut chk = 0usize;
22565 for _ in 0..iters {
22566 let d = col.duplicated_keep("first").expect("typed");
22567 chk ^= d
22568 .values()
22569 .iter()
22570 .filter(|v| matches!(v, Scalar::Bool(true)))
22571 .count();
22572 }
22573 let typed = t0.elapsed();
22574
22575 let scalar_col =
22576 Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
22577 .expect("col");
22578 let t1 = Instant::now();
22579 let mut chk2 = 0usize;
22580 for _ in 0..iters {
22581 let mut seen: HashSet<OldKey> = HashSet::new();
22582 let mut count = 0usize;
22583 for v in scalar_col.values() {
22584 let key = if v.is_missing() {
22585 OldKey::Null
22586 } else if let Scalar::Int64(i) = v {
22587 OldKey::Int64(*i)
22588 } else {
22589 OldKey::Null
22590 };
22591 if !seen.insert(key) {
22592 count += 1;
22593 }
22594 }
22595 chk2 ^= count;
22596 }
22597 let scalar = t1.elapsed();
22598 eprintln!(
22599 "duplicated 5M i64 card={cardinality} x{iters}: typed={typed:?} old_keyenum_siphash={scalar:?} ratio={:.2}x (chk {chk}/{chk2})",
22600 scalar.as_secs_f64() / typed.as_secs_f64()
22601 );
22602 }
22603 }
22604
22605 #[test]
22606 #[ignore = "timing benchmark; run with --ignored --nocapture on the rch VM"]
22607 fn radix_sort_timing_vs_scalar() {
22608 use std::time::Instant;
22609 let n = 5_000_000usize;
22610 let mut state: u64 = 0x1234_5678_9ABC_DEF0;
22611 let mut next = || {
22612 state = state
22613 .wrapping_mul(6364136223846793005)
22614 .wrapping_add(1442695040888963407);
22615 state
22616 };
22617 let data: Vec<i64> = (0..n).map(|_| next() as i64).collect();
22618 let col = Column::from_i64_values(data.clone());
22619
22620 let iters = 10;
22621 let t0 = Instant::now();
22622 let mut checksum = 0i64;
22623 for _ in 0..iters {
22624 let sorted = col.sort_values(true).expect("radix");
22625 checksum ^= match &sorted.values()[0] {
22626 Scalar::Int64(v) => *v,
22627 _ => 0,
22628 };
22629 }
22630 let radix = t0.elapsed();
22631
22632 let scalar_col = Column::from_values(data.iter().map(|&v| Scalar::Int64(v)).collect())
22634 .expect("scalar col");
22635 let t1 = Instant::now();
22636 let mut checksum2 = 0i64;
22637 for _ in 0..iters {
22638 let mut indexed: Vec<(usize, &Scalar)> =
22639 scalar_col.values().iter().enumerate().collect();
22640 indexed.sort_by(|a, b| crate::compare_scalars_na_last(a.1, b.1, true));
22641 if let Scalar::Int64(v) = indexed[0].1 {
22642 checksum2 ^= *v;
22643 }
22644 }
22645 let scalar = t1.elapsed();
22646 eprintln!(
22647 "sort_single 5M i64 x{iters}: radix={radix:?} scalar={scalar:?} ratio={:.2}x (chk {checksum}/{checksum2})",
22648 scalar.as_secs_f64() / radix.as_secs_f64()
22649 );
22650 }
22651
22652 #[test]
22653 fn diff_periods_one_subtracts_prev() {
22654 let col =
22655 Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(8), Scalar::Int64(10)])
22656 .expect("col");
22657 let d = col.diff(1).expect("diff");
22658 assert!(d.values()[0].is_missing());
22659 assert_eq!(d.values()[1], Scalar::Float64(3.0));
22660 assert_eq!(d.values()[2], Scalar::Float64(2.0));
22661 assert_eq!(d.dtype(), DType::Float64);
22662 }
22663
22664 #[test]
22665 fn diff_negative_period_looks_ahead() {
22666 let col =
22667 Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(8), Scalar::Int64(10)])
22668 .expect("col");
22669 let d = col.diff(-1).expect("diff");
22670 assert_eq!(d.values()[0], Scalar::Float64(-3.0));
22671 assert_eq!(d.values()[1], Scalar::Float64(-2.0));
22672 assert!(d.values()[2].is_missing());
22673 }
22674
22675 #[test]
22676 fn diff_timedelta64_returns_timedelta_e607u() {
22677 let one_hour = 3_600 * 1_000_000_000_i64;
22680 let col = Column::from_values(vec![
22681 Scalar::Timedelta64(one_hour),
22682 Scalar::Timedelta64(3 * one_hour),
22683 Scalar::Timedelta64(2 * one_hour),
22684 ])
22685 .expect("col");
22686 let d = col.diff(1).expect("diff");
22687 assert_eq!(d.dtype(), DType::Timedelta64);
22688 assert!(d.values()[0].is_missing()); assert_eq!(d.values()[1], Scalar::Timedelta64(2 * one_hour));
22690 assert_eq!(d.values()[2], Scalar::Timedelta64(-one_hour));
22691 }
22692
22693 #[test]
22694 fn diff_timedelta64_nat_propagates_e607u() {
22695 use fp_types::Timedelta;
22696 let one_hour = 3_600 * 1_000_000_000_i64;
22697 let col = Column::from_values(vec![
22698 Scalar::Timedelta64(one_hour),
22699 Scalar::Timedelta64(Timedelta::NAT),
22700 Scalar::Timedelta64(2 * one_hour),
22701 ])
22702 .expect("col");
22703 let d = col.diff(1).expect("diff");
22704 assert_eq!(d.dtype(), DType::Timedelta64);
22705 assert!(d.values()[0].is_missing());
22706 assert!(d.values()[1].is_missing()); assert!(d.values()[2].is_missing()); }
22709
22710 #[test]
22711 fn duplicated_keep_first() {
22712 let col = Column::from_values(vec![
22713 Scalar::Int64(1),
22714 Scalar::Int64(2),
22715 Scalar::Int64(1),
22716 Scalar::Int64(3),
22717 Scalar::Int64(2),
22718 ])
22719 .expect("col");
22720 let d = col.duplicated().expect("duplicated");
22721 assert_eq!(d.values()[0], Scalar::Bool(false));
22722 assert_eq!(d.values()[1], Scalar::Bool(false));
22723 assert_eq!(d.values()[2], Scalar::Bool(true));
22724 assert_eq!(d.values()[3], Scalar::Bool(false));
22725 assert_eq!(d.values()[4], Scalar::Bool(true));
22726 }
22727
22728 #[test]
22729 fn duplicated_treats_nulls_as_one_bucket() {
22730 let col = Column::from_values(vec![
22731 Scalar::Null(NullKind::NaN),
22732 Scalar::Null(NullKind::NaN),
22733 Scalar::Int64(1),
22734 ])
22735 .expect("col");
22736 let d = col.duplicated().expect("duplicated");
22737 assert_eq!(d.values()[0], Scalar::Bool(false));
22738 assert_eq!(d.values()[1], Scalar::Bool(true));
22739 assert_eq!(d.values()[2], Scalar::Bool(false));
22740 }
22741
22742 #[test]
22743 fn duplicated_keep_variants_match_pandas() {
22744 let col = Column::from_values(vec![
22745 Scalar::Int64(1),
22746 Scalar::Int64(2),
22747 Scalar::Int64(1),
22748 Scalar::Int64(1),
22749 Scalar::Int64(3),
22750 Scalar::Int64(2),
22751 Scalar::Null(NullKind::NaN),
22752 Scalar::Null(NullKind::NaN),
22753 ])
22754 .expect("col");
22755
22756 let last = col.duplicated_keep("last").expect("duplicated last");
22757 assert_eq!(
22758 last.values(),
22759 &[
22760 Scalar::Bool(true),
22761 Scalar::Bool(true),
22762 Scalar::Bool(true),
22763 Scalar::Bool(false),
22764 Scalar::Bool(false),
22765 Scalar::Bool(false),
22766 Scalar::Bool(true),
22767 Scalar::Bool(false),
22768 ]
22769 );
22770
22771 let none = col.duplicated_keep("false").expect("duplicated none");
22772 assert_eq!(
22773 none.values(),
22774 &[
22775 Scalar::Bool(true),
22776 Scalar::Bool(true),
22777 Scalar::Bool(true),
22778 Scalar::Bool(true),
22779 Scalar::Bool(false),
22780 Scalar::Bool(true),
22781 Scalar::Bool(true),
22782 Scalar::Bool(true),
22783 ]
22784 );
22785 }
22786
22787 #[test]
22788 fn between_inclusive_both() {
22789 let col = Column::from_values(vec![
22790 Scalar::Float64(0.5),
22791 Scalar::Float64(1.0),
22792 Scalar::Float64(5.0),
22793 Scalar::Float64(6.0),
22794 ])
22795 .expect("col");
22796 let b = col.between(1.0, 5.0, true).expect("between");
22797 assert_eq!(b.values()[0], Scalar::Bool(false));
22798 assert_eq!(b.values()[1], Scalar::Bool(true));
22799 assert_eq!(b.values()[2], Scalar::Bool(true));
22800 assert_eq!(b.values()[3], Scalar::Bool(false));
22801 }
22802
22803 #[test]
22804 fn between_exclusive() {
22805 let col = Column::from_values(vec![
22806 Scalar::Float64(1.0),
22807 Scalar::Float64(3.0),
22808 Scalar::Float64(5.0),
22809 ])
22810 .expect("col");
22811 let b = col.between(1.0, 5.0, false).expect("between");
22812 assert_eq!(b.values()[0], Scalar::Bool(false));
22813 assert_eq!(b.values()[1], Scalar::Bool(true));
22814 assert_eq!(b.values()[2], Scalar::Bool(false));
22815 }
22816
22817 #[test]
22818 fn between_left_and_right_inclusive_edges() {
22819 let col = Column::from_values(vec![
22820 Scalar::Float64(1.0),
22821 Scalar::Float64(3.0),
22822 Scalar::Float64(5.0),
22823 ])
22824 .expect("col");
22825
22826 let left = col
22827 .between_inclusive(1.0, 5.0, "left")
22828 .expect("between left");
22829 assert_eq!(
22830 left.values(),
22831 &[Scalar::Bool(true), Scalar::Bool(true), Scalar::Bool(false),]
22832 );
22833
22834 let right = col
22835 .between_inclusive(1.0, 5.0, "right")
22836 .expect("between right");
22837 assert_eq!(
22838 right.values(),
22839 &[Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(true),]
22840 );
22841 }
22842
22843 #[test]
22844 fn between_missing_maps_to_false() {
22845 let col = Column::from_values(vec![Scalar::Null(NullKind::NaN), Scalar::Float64(3.0)])
22846 .expect("col");
22847 let b = col.between(1.0, 5.0, true).expect("between");
22848 assert_eq!(b.values()[0], Scalar::Bool(false));
22849 assert_eq!(b.values()[1], Scalar::Bool(true));
22850 }
22851 }
22852
22853 mod factorize {
22854 use fp_types::NullKind;
22855
22856 use super::*;
22857
22858 #[test]
22859 fn factorize_preserves_first_seen_order() {
22860 let col = Column::from_values(vec![
22861 Scalar::Utf8("b".into()),
22862 Scalar::Utf8("a".into()),
22863 Scalar::Utf8("b".into()),
22864 Scalar::Utf8("c".into()),
22865 Scalar::Utf8("a".into()),
22866 ])
22867 .expect("col");
22868
22869 let (codes, uniques) = col.factorize().expect("factorize");
22870 assert_eq!(codes.dtype(), DType::Int64);
22871 assert_eq!(
22872 codes.values(),
22873 &[
22874 Scalar::Int64(0),
22875 Scalar::Int64(1),
22876 Scalar::Int64(0),
22877 Scalar::Int64(2),
22878 Scalar::Int64(1),
22879 ]
22880 );
22881 assert_eq!(
22882 uniques.values(),
22883 &[
22884 Scalar::Utf8("b".into()),
22885 Scalar::Utf8("a".into()),
22886 Scalar::Utf8("c".into()),
22887 ]
22888 );
22889 }
22890
22891 #[test]
22892 fn factorize_lazy_contiguous_utf8_default_witness_preserves_order() {
22893 let col = Column {
22894 dtype: DType::Utf8,
22895 values: ScalarValues::lazy_contiguous_utf8_arc(
22896 Arc::from(&b"baacaab"[..]),
22897 Arc::from([0_usize, 1, 3, 4, 6, 7]),
22898 ),
22899 validity: ValidityMask::all_valid(5),
22900 data: None,
22901 };
22902
22903 let (codes, uniques) = col.factorize().expect("factorize");
22904 assert_eq!(
22905 codes.values(),
22906 &[
22907 Scalar::Int64(0),
22908 Scalar::Int64(1),
22909 Scalar::Int64(2),
22910 Scalar::Int64(1),
22911 Scalar::Int64(0),
22912 ]
22913 );
22914 assert_eq!(
22915 uniques.values(),
22916 &[
22917 Scalar::Utf8("b".into()),
22918 Scalar::Utf8("aa".into()),
22919 Scalar::Utf8("c".into()),
22920 ]
22921 );
22922
22923 let (sorted_codes, sorted_uniques) =
22924 col.factorize_with_options(true, true).expect("factorize");
22925 assert_eq!(
22926 sorted_codes.values(),
22927 &[
22928 Scalar::Int64(1),
22929 Scalar::Int64(0),
22930 Scalar::Int64(2),
22931 Scalar::Int64(0),
22932 Scalar::Int64(1),
22933 ]
22934 );
22935 assert_eq!(
22936 sorted_uniques.values(),
22937 &[
22938 Scalar::Utf8("aa".into()),
22939 Scalar::Utf8("b".into()),
22940 Scalar::Utf8("c".into()),
22941 ]
22942 );
22943 }
22944
22945 #[test]
22946 fn factorize_missing_values_map_to_negative_one() {
22947 let col = Column::from_values(vec![
22948 Scalar::Float64(1.5),
22949 Scalar::Null(NullKind::NaN),
22950 Scalar::Float64(2.5),
22951 Scalar::Null(NullKind::Null),
22952 Scalar::Float64(1.5),
22953 ])
22954 .expect("col");
22955
22956 let (codes, uniques) = col.factorize().expect("factorize");
22957 assert_eq!(
22958 codes.values(),
22959 &[
22960 Scalar::Int64(0),
22961 Scalar::Int64(-1),
22962 Scalar::Int64(1),
22963 Scalar::Int64(-1),
22964 Scalar::Int64(0),
22965 ]
22966 );
22967 assert_eq!(uniques.dtype(), DType::Float64);
22968 assert_eq!(
22969 uniques.values(),
22970 &[Scalar::Float64(1.5), Scalar::Float64(2.5)]
22971 );
22972 }
22973
22974 #[test]
22975 fn factorize_empty_column_returns_empty_outputs() {
22976 let col = Column::new(DType::Int64, Vec::new()).expect("col");
22977 let (codes, uniques) = col.factorize().expect("factorize");
22978 assert!(codes.is_empty());
22979 assert!(uniques.is_empty());
22980 assert_eq!(codes.dtype(), DType::Int64);
22981 assert_eq!(uniques.dtype(), DType::Int64);
22982 }
22983
22984 #[test]
22985 fn factorize_with_sort_sorts_uniques_and_relabels_codes() {
22986 let col = Column::from_values(vec![
22987 Scalar::Utf8("b".into()),
22988 Scalar::Utf8("a".into()),
22989 Scalar::Utf8("b".into()),
22990 Scalar::Utf8("c".into()),
22991 Scalar::Utf8("a".into()),
22992 ])
22993 .expect("col");
22994
22995 let (codes, uniques) = col.factorize_with_options(true, true).expect("factorize");
22996 assert_eq!(
22997 codes.values(),
22998 &[
22999 Scalar::Int64(1),
23000 Scalar::Int64(0),
23001 Scalar::Int64(1),
23002 Scalar::Int64(2),
23003 Scalar::Int64(0),
23004 ]
23005 );
23006 assert_eq!(
23007 uniques.values(),
23008 &[
23009 Scalar::Utf8("a".into()),
23010 Scalar::Utf8("b".into()),
23011 Scalar::Utf8("c".into()),
23012 ]
23013 );
23014 }
23015
23016 #[test]
23017 fn factorize_with_use_na_sentinel_false_keeps_missing_in_uniques() {
23018 let col = Column::from_values(vec![
23019 Scalar::Float64(1.5),
23020 Scalar::Null(NullKind::NaN),
23021 Scalar::Float64(2.5),
23022 Scalar::Null(NullKind::Null),
23023 Scalar::Float64(1.5),
23024 ])
23025 .expect("col");
23026
23027 let (codes, uniques) = col.factorize_with_options(false, false).expect("factorize");
23028 assert_eq!(
23029 codes.values(),
23030 &[
23031 Scalar::Int64(0),
23032 Scalar::Int64(1),
23033 Scalar::Int64(2),
23034 Scalar::Int64(1),
23035 Scalar::Int64(0),
23036 ]
23037 );
23038 assert_eq!(uniques.dtype(), DType::Float64);
23039 assert_eq!(
23040 uniques.values(),
23041 &[
23042 Scalar::Float64(1.5),
23043 Scalar::Null(NullKind::NaN),
23044 Scalar::Float64(2.5),
23045 ]
23046 );
23047 }
23048
23049 #[test]
23050 fn factorize_with_sort_and_use_na_sentinel_false_sorts_missing_last() {
23051 let col = Column::from_values(vec![
23052 Scalar::Utf8("b".into()),
23053 Scalar::Null(NullKind::Null),
23054 Scalar::Utf8("a".into()),
23055 Scalar::Utf8("b".into()),
23056 Scalar::Null(NullKind::NaN),
23057 ])
23058 .expect("col");
23059
23060 let (codes, uniques) = col.factorize_with_options(true, false).expect("factorize");
23061 assert_eq!(
23062 codes.values(),
23063 &[
23064 Scalar::Int64(1),
23065 Scalar::Int64(2),
23066 Scalar::Int64(0),
23067 Scalar::Int64(1),
23068 Scalar::Int64(2),
23069 ]
23070 );
23071 assert_eq!(
23072 uniques.values(),
23073 &[
23074 Scalar::Utf8("a".into()),
23075 Scalar::Utf8("b".into()),
23076 Scalar::Null(NullKind::Null),
23077 ]
23078 );
23079 }
23080 }
23081
23082 mod aggregation_helpers {
23083 use fp_types::{NullKind, Timedelta};
23084
23085 use super::*;
23086
23087 fn assert_float_nan(value: Scalar) {
23088 assert!(
23089 matches!(value, Scalar::Float64(v) if v.is_nan()),
23090 "expected Float64(NaN), got {value:?}"
23091 );
23092 }
23093
23094 #[test]
23095 fn sum_skips_nulls() {
23096 let col = Column::from_values(vec![
23097 Scalar::Float64(1.0),
23098 Scalar::Null(NullKind::NaN),
23099 Scalar::Float64(2.0),
23100 Scalar::Float64(3.0),
23101 ])
23102 .expect("col");
23103 let sum = col.sum();
23104 assert!(matches!(sum, Scalar::Float64(_)), "expected Float64 result");
23105 if let Scalar::Float64(v) = sum {
23106 assert!((v - 6.0).abs() < 1e-9);
23107 }
23108 }
23109
23110 #[test]
23111 fn sum_empty_is_zero() {
23112 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23113 assert_eq!(col.sum(), Scalar::Float64(0.0));
23114 }
23115
23116 #[test]
23117 fn mean_matches_sum_over_count() {
23118 let col = Column::from_values(vec![
23119 Scalar::Float64(2.0),
23120 Scalar::Float64(4.0),
23121 Scalar::Float64(6.0),
23122 ])
23123 .expect("col");
23124 let mean = col.mean();
23125 assert!(
23126 matches!(mean, Scalar::Float64(_)),
23127 "expected Float64 result"
23128 );
23129 if let Scalar::Float64(v) = mean {
23130 assert!((v - 4.0).abs() < 1e-9);
23131 }
23132 }
23133
23134 #[test]
23135 fn mean_empty_is_null() {
23136 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23137 assert!(col.mean().is_missing());
23138 }
23139
23140 #[test]
23141 fn min_max_extrema_skip_nulls() {
23142 let col = Column::from_values(vec![
23143 Scalar::Int64(3),
23144 Scalar::Null(NullKind::NaN),
23145 Scalar::Int64(1),
23146 Scalar::Int64(5),
23147 Scalar::Int64(2),
23148 ])
23149 .expect("col");
23150 assert_eq!(col.min(), Scalar::Int64(1));
23151 assert_eq!(col.max(), Scalar::Int64(5));
23152 }
23153
23154 #[test]
23155 fn median_of_odd_count() {
23156 let col = Column::from_values(vec![
23157 Scalar::Float64(1.0),
23158 Scalar::Float64(5.0),
23159 Scalar::Float64(3.0),
23160 ])
23161 .expect("col");
23162 let median = col.median();
23163 assert!(
23164 matches!(median, Scalar::Float64(_)),
23165 "expected Float64 result"
23166 );
23167 if let Scalar::Float64(v) = median {
23168 assert!((v - 3.0).abs() < 1e-9);
23169 }
23170 }
23171
23172 #[test]
23173 fn prod_multiplies_non_nulls() {
23174 let col = Column::from_values(vec![
23175 Scalar::Float64(2.0),
23176 Scalar::Null(NullKind::NaN),
23177 Scalar::Float64(3.0),
23178 Scalar::Float64(4.0),
23179 ])
23180 .expect("col");
23181 let prod = col.prod();
23182 assert!(
23183 matches!(prod, Scalar::Float64(_)),
23184 "expected Float64 result"
23185 );
23186 if let Scalar::Float64(v) = prod {
23187 assert!((v - 24.0).abs() < 1e-9);
23188 }
23189 }
23190
23191 #[test]
23192 fn prod_empty_is_one() {
23193 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23194 assert_eq!(col.prod(), Scalar::Float64(1.0));
23195 }
23196
23197 #[test]
23198 fn product_alias_matches_prod() {
23199 let col = Column::from_values(vec![
23200 Scalar::Float64(2.0),
23201 Scalar::Null(NullKind::NaN),
23202 Scalar::Float64(3.0),
23203 ])
23204 .expect("col");
23205 assert_eq!(col.product(), col.prod());
23206 }
23207
23208 #[test]
23209 fn skipna_false_aggregate_variants_propagate_nan() {
23210 let col = Column::from_values(vec![
23211 Scalar::Float64(2.0),
23212 Scalar::Null(NullKind::NaN),
23213 Scalar::Float64(4.0),
23214 ])
23215 .expect("col");
23216
23217 assert_eq!(col.sum_skipna(true), col.sum());
23218 assert_float_nan(col.sum_skipna(false));
23219 assert_float_nan(col.mean_skipna(false));
23220 assert_float_nan(col.min_skipna(false));
23221 assert_float_nan(col.max_skipna(false));
23222 assert_float_nan(col.median_skipna(false));
23223 assert_float_nan(col.prod_skipna(false));
23224 assert_float_nan(col.var_skipna(1, false));
23225 assert_float_nan(col.std_skipna(1, false));
23226 assert_float_nan(col.sem_skipna(1, false));
23227 }
23228
23229 #[test]
23230 fn skipna_false_timedelta_aggregate_variants_propagate_nat() {
23231 let col = Column::from_values(vec![
23232 Scalar::Timedelta64(Timedelta::NANOS_PER_SEC),
23233 Scalar::Timedelta64(Timedelta::NAT),
23234 ])
23235 .expect("col");
23236
23237 assert_eq!(col.sum_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
23238 assert_eq!(col.mean_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
23239 assert_eq!(col.min_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
23240 assert_eq!(col.max_skipna(false), Scalar::Timedelta64(Timedelta::NAT));
23241 }
23242
23243 #[test]
23244 fn quantile_median_of_sorted_values() {
23245 let col = Column::from_values(vec![
23246 Scalar::Float64(1.0),
23247 Scalar::Float64(2.0),
23248 Scalar::Float64(3.0),
23249 Scalar::Float64(4.0),
23250 Scalar::Float64(5.0),
23251 ])
23252 .expect("col");
23253 let quantile = col.quantile(0.5);
23254 assert!(
23255 matches!(quantile, Scalar::Float64(v) if (v - 3.0).abs() < 1e-9),
23256 "expected Float64 median, got {quantile:?}"
23257 );
23258 }
23259
23260 #[test]
23261 fn quantile_empty_is_null() {
23262 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23263 assert!(col.quantile(0.5).is_missing());
23264 }
23265
23266 #[test]
23267 fn quantile_out_of_range_is_null() {
23268 let col = Column::from_values(vec![Scalar::Float64(1.0)]).expect("col");
23269 assert!(col.quantile(1.5).is_missing());
23270 assert!(col.quantile(-0.1).is_missing());
23271 }
23272
23273 #[test]
23274 fn mode_returns_tied_max_frequency() {
23275 let col = Column::from_values(vec![
23276 Scalar::Int64(1),
23277 Scalar::Int64(2),
23278 Scalar::Int64(2),
23279 Scalar::Int64(3),
23280 Scalar::Int64(3),
23281 ])
23282 .expect("col");
23283 let m = col.mode().expect("mode");
23284 assert_eq!(m.values(), &[Scalar::Int64(2), Scalar::Int64(3)]);
23285 }
23286
23287 #[test]
23288 fn mode_ignores_missing_values() {
23289 let col = Column::from_values(vec![
23290 Scalar::Int64(1),
23291 Scalar::Null(NullKind::NaN),
23292 Scalar::Int64(1),
23293 Scalar::Null(NullKind::NaN),
23294 ])
23295 .expect("col");
23296 let m = col.mode().expect("mode");
23297 assert_eq!(m.values(), &[Scalar::Int64(1)]);
23298 }
23299
23300 #[test]
23301 fn mode_empty_is_empty_same_dtype() {
23302 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23303 let m = col.mode().expect("mode");
23304 assert!(m.is_empty());
23305 }
23306
23307 #[test]
23308 fn memory_usage_fixed_width_for_numeric() {
23309 let col =
23310 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
23311 .expect("col");
23312 let usage = col.memory_usage(false);
23313 assert_eq!(usage, 25);
23315 }
23316
23317 #[test]
23318 fn memory_usage_deep_counts_utf8_bytes() {
23319 let col = Column::from_values(vec![
23320 Scalar::Utf8("hi".into()),
23321 Scalar::Utf8("world".into()),
23322 ])
23323 .expect("col");
23324 let shallow = col.memory_usage(false);
23325 let deep = col.memory_usage(true);
23326 assert!(deep > shallow);
23327 assert_eq!(deep - shallow, 7);
23329 }
23330
23331 #[test]
23332 fn interpolate_fills_interior_gaps() {
23333 let col = Column::from_values(vec![
23334 Scalar::Float64(1.0),
23335 Scalar::Null(NullKind::NaN),
23336 Scalar::Null(NullKind::NaN),
23337 Scalar::Float64(4.0),
23338 ])
23339 .expect("col");
23340 let r = col.interpolate_linear().expect("interpolate");
23341 assert_eq!(r.values()[0], Scalar::Float64(1.0));
23342 assert!(
23343 matches!(&r.values()[1], Scalar::Float64(v) if (*v - 2.0).abs() < 1e-9),
23344 "expected Float64, got {:?}",
23345 r.values()[1]
23346 );
23347 assert!(
23348 matches!(&r.values()[2], Scalar::Float64(v) if (*v - 3.0).abs() < 1e-9),
23349 "expected Float64, got {:?}",
23350 r.values()[2]
23351 );
23352 assert_eq!(r.values()[3], Scalar::Float64(4.0));
23353 }
23354
23355 #[test]
23356 fn interpolate_leading_null_stays_null_trailing_forward_fills() {
23357 let col = Column::from_values(vec![
23363 Scalar::Null(NullKind::NaN),
23364 Scalar::Float64(2.0),
23365 Scalar::Null(NullKind::NaN),
23366 Scalar::Float64(4.0),
23367 Scalar::Null(NullKind::NaN),
23368 ])
23369 .expect("col");
23370 let r = col.interpolate_linear().expect("interpolate");
23371 assert!(r.values()[0].is_missing());
23372 assert_eq!(r.values()[1], Scalar::Float64(2.0));
23373 assert!(
23374 matches!(&r.values()[2], Scalar::Float64(v) if (*v - 3.0).abs() < 1e-9),
23375 "expected Float64, got {:?}",
23376 r.values()[2]
23377 );
23378 assert_eq!(r.values()[3], Scalar::Float64(4.0));
23379 assert_eq!(r.values()[4], Scalar::Float64(4.0));
23381 }
23382
23383 #[test]
23384 fn interpolate_trailing_run_forward_fills_without_extrapolating() {
23385 let col = Column::from_values(vec![
23387 Scalar::Float64(2.0),
23388 Scalar::Float64(4.0),
23389 Scalar::Null(NullKind::NaN),
23390 Scalar::Null(NullKind::NaN),
23391 ])
23392 .expect("col");
23393 let r = col.interpolate_linear().expect("interpolate");
23394 assert_eq!(
23395 r.values(),
23396 &[
23397 Scalar::Float64(2.0),
23398 Scalar::Float64(4.0),
23399 Scalar::Float64(4.0),
23400 Scalar::Float64(4.0),
23401 ]
23402 );
23403 }
23404
23405 #[test]
23406 fn interpolate_empty_is_empty_float64() {
23407 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23408 let r = col.interpolate_linear().expect("interpolate");
23409 assert!(r.is_empty());
23410 assert_eq!(r.dtype(), DType::Float64);
23411 }
23412
23413 #[test]
23414 fn interpolate_alias_matches_default_linear_interpolation() {
23415 let col = Column::from_values(vec![
23416 Scalar::Float64(1.0),
23417 Scalar::Null(NullKind::NaN),
23418 Scalar::Float64(3.0),
23419 ])
23420 .expect("col");
23421
23422 assert_eq!(
23423 col.interpolate().expect("interpolate"),
23424 col.interpolate_linear().expect("interpolate_linear")
23425 );
23426 }
23427
23428 #[test]
23429 fn drop_duplicates_keeps_first_occurrence() {
23430 let col = Column::from_values(vec![
23431 Scalar::Int64(1),
23432 Scalar::Int64(2),
23433 Scalar::Int64(1),
23434 Scalar::Int64(3),
23435 Scalar::Int64(2),
23436 ])
23437 .expect("col");
23438 let d = col.drop_duplicates().expect("drop_duplicates");
23439 assert_eq!(
23440 d.values(),
23441 &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
23442 );
23443 }
23444
23445 #[test]
23446 fn drop_duplicates_treats_nulls_as_one_bucket() {
23447 let col = Column::from_values(vec![
23448 Scalar::Null(NullKind::NaN),
23449 Scalar::Int64(1),
23450 Scalar::Null(NullKind::NaN),
23451 ])
23452 .expect("col");
23453 let d = col.drop_duplicates().expect("drop_duplicates");
23454 assert_eq!(d.len(), 2);
23456 assert!(d.values()[0].is_missing());
23457 assert_eq!(d.values()[1], Scalar::Int64(1));
23458 }
23459
23460 #[test]
23461 fn drop_duplicates_keep_variants_match_pandas() {
23462 let col = Column::from_values(vec![
23463 Scalar::Int64(1),
23464 Scalar::Int64(2),
23465 Scalar::Int64(1),
23466 Scalar::Int64(1),
23467 Scalar::Int64(3),
23468 Scalar::Int64(2),
23469 Scalar::Null(NullKind::NaN),
23470 Scalar::Null(NullKind::NaN),
23471 ])
23472 .expect("col");
23473
23474 let last = col.drop_duplicates_keep("last").expect("drop last");
23475 assert_eq!(last.len(), 4);
23476 assert_eq!(last.values()[0], Scalar::Int64(1));
23477 assert_eq!(last.values()[1], Scalar::Int64(3));
23478 assert_eq!(last.values()[2], Scalar::Int64(2));
23479 assert!(last.values()[3].is_missing());
23480
23481 let none = col.drop_duplicates_keep("false").expect("drop none");
23482 assert_eq!(none.values(), &[Scalar::Int64(3)]);
23483 }
23484
23485 #[test]
23486 fn compare_returns_only_differences() {
23487 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
23488 .expect("a");
23489 let b =
23490 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(20), Scalar::Int64(3)])
23491 .expect("b");
23492 let (left, right) = a.compare(&b).expect("compare");
23493 assert_eq!(left.values(), &[Scalar::Int64(2)]);
23494 assert_eq!(right.values(), &[Scalar::Int64(20)]);
23495 }
23496
23497 #[test]
23498 fn compare_treats_matching_nulls_as_equal() {
23499 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
23500 .expect("a");
23501 let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
23502 .expect("b");
23503 let (left, right) = a.compare(&b).expect("compare");
23504 assert!(left.is_empty());
23505 assert!(right.is_empty());
23506 }
23507
23508 #[test]
23509 fn compare_length_mismatch_errors() {
23510 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("a");
23511 let b = Column::from_values(vec![Scalar::Int64(1)]).expect("b");
23512 let err = a.compare(&b).unwrap_err();
23513 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
23514 }
23515
23516 #[test]
23517 fn map_applies_unary_function() {
23518 let col =
23519 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
23520 .expect("col");
23521 let doubled = col
23522 .map(|v| match v {
23523 Scalar::Int64(i) => Scalar::Int64(i * 2),
23524 other => other.clone(),
23525 })
23526 .expect("map");
23527 assert_eq!(doubled.values()[0], Scalar::Int64(2));
23528 assert_eq!(doubled.values()[1], Scalar::Int64(4));
23529 assert_eq!(doubled.values()[2], Scalar::Int64(6));
23530 }
23531
23532 #[test]
23533 fn map_can_change_dtype() {
23534 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
23535 let as_str = col
23536 .map(|v| match v {
23537 Scalar::Int64(i) => Scalar::Utf8(i.to_string()),
23538 other => other.clone(),
23539 })
23540 .expect("map");
23541 assert_eq!(as_str.dtype(), DType::Utf8);
23542 assert_eq!(as_str.values()[0], Scalar::Utf8("1".into()));
23543 }
23544
23545 #[test]
23546 fn argmin_argmax_skip_missing() {
23547 let col = Column::from_values(vec![
23548 Scalar::Int64(3),
23549 Scalar::Null(NullKind::NaN),
23550 Scalar::Int64(1),
23551 Scalar::Int64(5),
23552 Scalar::Int64(2),
23553 ])
23554 .expect("col");
23555 assert_eq!(col.argmin(), Some(2));
23556 assert_eq!(col.argmax(), Some(3));
23557 assert_eq!(col.idxmin(), Some(2));
23558 assert_eq!(col.idxmax(), Some(3));
23559 }
23560
23561 #[test]
23562 fn argmin_argmax_all_missing_returns_none() {
23563 let col = Column::from_values(vec![
23564 Scalar::Null(NullKind::NaN),
23565 Scalar::Null(NullKind::Null),
23566 ])
23567 .expect("col");
23568 assert!(col.argmin().is_none());
23569 assert!(col.argmax().is_none());
23570 assert!(col.idxmin().is_none());
23571 assert!(col.idxmax().is_none());
23572 }
23573
23574 #[test]
23575 fn is_monotonic_increasing_detects_ascending() {
23576 let col = Column::from_values(vec![
23577 Scalar::Int64(1),
23578 Scalar::Int64(2),
23579 Scalar::Int64(2),
23580 Scalar::Int64(5),
23581 ])
23582 .expect("col");
23583 assert!(col.is_monotonic_increasing());
23584 assert!(!col.is_monotonic_decreasing());
23585 }
23586
23587 #[test]
23588 fn is_monotonic_decreasing_detects_descending() {
23589 let col =
23590 Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(3), Scalar::Int64(1)])
23591 .expect("col");
23592 assert!(col.is_monotonic_decreasing());
23593 assert!(!col.is_monotonic_increasing());
23594 }
23595
23596 #[test]
23597 fn is_monotonic_skips_missing_values() {
23598 let col = Column::from_values(vec![
23599 Scalar::Int64(1),
23600 Scalar::Null(NullKind::NaN),
23601 Scalar::Int64(3),
23602 Scalar::Int64(5),
23603 ])
23604 .expect("col");
23605 assert!(col.is_monotonic_increasing());
23606 }
23607
23608 #[test]
23609 fn is_monotonic_empty_is_true() {
23610 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
23611 assert!(col.is_monotonic_increasing());
23612 assert!(col.is_monotonic_decreasing());
23613 }
23614
23615 #[test]
23616 fn combine_first_fills_missing_from_other() {
23617 let a = Column::from_values(vec![
23618 Scalar::Int64(1),
23619 Scalar::Null(NullKind::NaN),
23620 Scalar::Int64(3),
23621 ])
23622 .expect("a");
23623 let b = Column::from_values(vec![
23624 Scalar::Int64(10),
23625 Scalar::Int64(20),
23626 Scalar::Int64(30),
23627 ])
23628 .expect("b");
23629 let c = a.combine_first(&b).expect("combine_first");
23630 assert_eq!(c.values()[0], Scalar::Int64(1));
23631 assert_eq!(c.values()[1], Scalar::Int64(20));
23632 assert_eq!(c.values()[2], Scalar::Int64(3));
23633 }
23634
23635 #[test]
23636 fn combine_first_length_mismatch_errors() {
23637 let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
23638 let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
23639 let err = a.combine_first(&b).unwrap_err();
23640 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
23641 }
23642
23643 #[test]
23644 fn clip_lower_only() {
23645 let col = Column::from_values(vec![
23646 Scalar::Float64(-2.0),
23647 Scalar::Float64(0.0),
23648 Scalar::Float64(5.0),
23649 ])
23650 .expect("col");
23651 let c = col.clip_lower(0.0).expect("clip_lower");
23652 assert_eq!(c.values()[0], Scalar::Float64(0.0));
23653 assert_eq!(c.values()[1], Scalar::Float64(0.0));
23654 assert_eq!(c.values()[2], Scalar::Float64(5.0));
23655 }
23656
23657 #[test]
23658 fn clip_upper_only() {
23659 let col = Column::from_values(vec![
23660 Scalar::Float64(-2.0),
23661 Scalar::Float64(0.0),
23662 Scalar::Float64(5.0),
23663 ])
23664 .expect("col");
23665 let c = col.clip_upper(1.0).expect("clip_upper");
23666 assert_eq!(c.values()[0], Scalar::Float64(-2.0));
23667 assert_eq!(c.values()[1], Scalar::Float64(0.0));
23668 assert_eq!(c.values()[2], Scalar::Float64(1.0));
23669 }
23670
23671 #[test]
23672 fn describe_returns_pandas_order() {
23673 let col = Column::from_values(vec![
23674 Scalar::Float64(1.0),
23675 Scalar::Float64(2.0),
23676 Scalar::Float64(3.0),
23677 Scalar::Float64(4.0),
23678 Scalar::Float64(5.0),
23679 ])
23680 .expect("col");
23681 let stats = col.describe().expect("describe");
23682 let names: Vec<&str> = stats.iter().map(|(k, _)| *k).collect();
23683 assert_eq!(
23684 names,
23685 vec!["count", "mean", "std", "min", "25%", "50%", "75%", "max"]
23686 );
23687 assert_eq!(stats[0].1, Scalar::Int64(5));
23688 assert!(
23689 matches!(&stats[1].1, Scalar::Float64(v) if (*v - 3.0).abs() < 1e-9),
23690 "expected Float64, got {:?}",
23691 stats[1].1
23692 );
23693 assert_eq!(stats[3].1, Scalar::Float64(1.0));
23694 assert_eq!(stats[7].1, Scalar::Float64(5.0));
23695 }
23696
23697 #[test]
23698 fn describe_rejects_utf8_column() {
23699 let col = Column::from_values(vec![Scalar::Utf8("a".into())]).expect("col");
23700 assert!(col.describe().is_err());
23701 }
23702
23703 #[test]
23704 fn combine_uses_fill_for_missing() {
23705 let a = Column::from_values(vec![
23706 Scalar::Int64(1),
23707 Scalar::Null(NullKind::NaN),
23708 Scalar::Int64(3),
23709 ])
23710 .expect("a");
23711 let b = Column::from_values(vec![
23712 Scalar::Int64(10),
23713 Scalar::Int64(20),
23714 Scalar::Null(NullKind::NaN),
23715 ])
23716 .expect("b");
23717 let out = a
23718 .combine(
23719 &b,
23720 |l, r| {
23721 if let (Ok(lf), Ok(rf)) = (l.to_f64(), r.to_f64()) {
23722 Scalar::Float64(lf + rf)
23723 } else {
23724 Scalar::Null(NullKind::NaN)
23725 }
23726 },
23727 Some(Scalar::Int64(0)),
23728 )
23729 .expect("combine");
23730 assert_eq!(out.values()[0], Scalar::Float64(11.0));
23731 assert_eq!(out.values()[1], Scalar::Float64(20.0));
23732 assert_eq!(out.values()[2], Scalar::Float64(3.0));
23733 }
23734
23735 #[test]
23736 fn combine_length_mismatch_errors() {
23737 let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
23738 let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
23739 let err = a
23740 .combine(&b, |l, _| l.clone(), Some(Scalar::Int64(0)))
23741 .unwrap_err();
23742 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
23743 }
23744
23745 #[test]
23746 fn combine_fill_none_propagates_nulls_without_invoking_func() {
23747 let a = Column::from_values(vec![
23748 Scalar::Float64(1.0),
23749 Scalar::Null(NullKind::NaN),
23750 Scalar::Float64(3.0),
23751 ])
23752 .expect("a");
23753 let b = Column::from_values(vec![
23754 Scalar::Float64(10.0),
23755 Scalar::Float64(20.0),
23756 Scalar::Null(NullKind::NaN),
23757 ])
23758 .expect("b");
23759 let mut calls = 0usize;
23760 let out = a
23761 .combine(
23762 &b,
23763 |l, r| {
23764 calls += 1;
23765 Scalar::Float64(l.to_f64().unwrap() + r.to_f64().unwrap())
23766 },
23767 None,
23768 )
23769 .expect("combine");
23770 assert_eq!(calls, 1);
23772 assert_eq!(out.values()[0], Scalar::Float64(11.0));
23773 assert!(out.values()[1].is_missing());
23774 assert!(out.values()[2].is_missing());
23775 }
23776
23777 #[test]
23778 fn combine_fill_none_all_present_matches_elementwise_apply() {
23779 let a = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("a");
23780 let b = Column::from_values(vec![Scalar::Int64(10), Scalar::Int64(20)]).expect("b");
23781 let out = a
23782 .combine(
23783 &b,
23784 |l, r| Scalar::Int64(l.to_f64().unwrap() as i64 + r.to_f64().unwrap() as i64),
23785 None,
23786 )
23787 .expect("combine");
23788 assert_eq!(out.values()[0], Scalar::Int64(11));
23789 assert_eq!(out.values()[1], Scalar::Int64(22));
23790 }
23791
23792 #[test]
23793 fn apply_float_applies_numeric_fn() {
23794 let col = Column::from_values(vec![
23795 Scalar::Float64(1.0),
23796 Scalar::Null(NullKind::NaN),
23797 Scalar::Float64(4.0),
23798 ])
23799 .expect("col");
23800 let out = col.apply_float(|x| x.sqrt()).expect("apply_float");
23801 assert_eq!(out.values()[0], Scalar::Float64(1.0));
23802 assert!(out.values()[1].is_missing());
23803 assert_eq!(out.values()[2], Scalar::Float64(2.0));
23804 assert_eq!(out.dtype(), DType::Float64);
23805 }
23806
23807 #[test]
23808 fn apply_float_rejects_non_numeric() {
23809 let col = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("col");
23810 assert!(col.apply_float(|x| x + 1.0).is_err());
23811 }
23812
23813 #[test]
23814 fn hist_counts_equal_width_bins() {
23815 let col = Column::from_values(vec![
23816 Scalar::Float64(0.0),
23817 Scalar::Float64(1.0),
23818 Scalar::Float64(2.0),
23819 Scalar::Float64(3.0),
23820 Scalar::Float64(9.0),
23821 ])
23822 .expect("col");
23823 let counts = col.hist_counts(3);
23824 assert_eq!(counts.len(), 3);
23826 assert_eq!(counts[0], 3); assert_eq!(counts[1], 1); assert_eq!(counts[2], 1); }
23830
23831 #[test]
23832 fn hist_counts_zero_bins_is_empty() {
23833 let col = Column::from_values(vec![Scalar::Float64(1.0)]).expect("col");
23834 assert!(col.hist_counts(0).is_empty());
23835 }
23836
23837 #[test]
23838 fn hist_counts_constant_column_puts_all_in_first_bin() {
23839 let col = Column::from_values(vec![
23840 Scalar::Float64(5.0),
23841 Scalar::Float64(5.0),
23842 Scalar::Float64(5.0),
23843 ])
23844 .expect("col");
23845 let counts = col.hist_counts(3);
23846 assert_eq!(counts[0], 3);
23847 assert_eq!(counts[1], 0);
23848 assert_eq!(counts[2], 0);
23849 }
23850
23851 #[test]
23852 fn nunique_drops_nulls() {
23853 let col = Column::from_values(vec![
23854 Scalar::Int64(1),
23855 Scalar::Int64(2),
23856 Scalar::Int64(1),
23857 Scalar::Null(NullKind::NaN),
23858 ])
23859 .expect("col");
23860 assert_eq!(col.nunique(), Scalar::Int64(2));
23861 }
23862
23863 #[test]
23864 fn nunique_with_dropna_false_counts_missing_once() {
23865 let col = Column::from_values(vec![
23866 Scalar::Int64(1),
23867 Scalar::Int64(2),
23868 Scalar::Int64(1),
23869 Scalar::Null(NullKind::NaN),
23870 Scalar::Null(NullKind::Null),
23871 ])
23872 .expect("col");
23873 assert_eq!(col.nunique_with_dropna(false), Scalar::Int64(3));
23874 }
23875
23876 #[test]
23877 fn nunique_with_dropna_false_all_missing_is_one() {
23878 let col = Column::from_values(vec![
23879 Scalar::Null(NullKind::NaN),
23880 Scalar::Null(NullKind::Null),
23881 Scalar::Null(NullKind::NaN),
23882 ])
23883 .expect("col");
23884 assert_eq!(col.nunique(), Scalar::Int64(0));
23885 assert_eq!(col.nunique_with_dropna(false), Scalar::Int64(1));
23886 }
23887
23888 #[test]
23889 fn any_all_reductions() {
23890 let col = Column::from_values(vec![Scalar::Int64(0), Scalar::Int64(0)]).expect("col");
23891 assert_eq!(col.any(), Scalar::Bool(false));
23892 assert_eq!(col.all(), Scalar::Bool(false));
23893
23894 let mixed = Column::from_values(vec![Scalar::Int64(0), Scalar::Int64(1)]).expect("col");
23895 assert_eq!(mixed.any(), Scalar::Bool(true));
23896 assert_eq!(mixed.all(), Scalar::Bool(false));
23897
23898 let all_true =
23899 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
23900 assert_eq!(all_true.all(), Scalar::Bool(true));
23901 }
23902
23903 #[test]
23904 fn is_unique_true_when_no_repeats() {
23905 let col =
23906 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
23907 .expect("col");
23908 assert!(col.is_unique());
23909 assert!(!col.has_duplicates());
23910 }
23911
23912 #[test]
23913 fn has_duplicates_true_when_repeats_present() {
23914 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(1)]).expect("col");
23915 assert!(col.has_duplicates());
23916 assert!(!col.is_unique());
23917 }
23918
23919 #[test]
23920 fn is_unique_ignores_nulls() {
23921 let col = Column::from_values(vec![
23922 Scalar::Int64(1),
23923 Scalar::Null(NullKind::NaN),
23924 Scalar::Null(NullKind::NaN),
23925 ])
23926 .expect("col");
23927 assert!(col.is_unique());
23928 }
23929
23930 #[test]
23931 fn pct_change_periods_one() {
23932 let col = Column::from_values(vec![
23933 Scalar::Float64(10.0),
23934 Scalar::Float64(12.0),
23935 Scalar::Float64(9.0),
23936 ])
23937 .expect("col");
23938 let r = col.pct_change(1).expect("pct_change");
23939 assert!(r.values()[0].is_missing());
23940 assert!(
23941 matches!(&r.values()[1], Scalar::Float64(v) if (*v - 0.2).abs() < 1e-9),
23942 "expected Float64, got {:?}",
23943 r.values()[1]
23944 );
23945 assert!(
23946 matches!(&r.values()[2], Scalar::Float64(v) if (*v + 0.25).abs() < 1e-9),
23947 "expected Float64, got {:?}",
23948 r.values()[2]
23949 );
23950 }
23951
23952 #[test]
23953 fn pct_change_zero_prev_yields_null() {
23954 let col =
23955 Column::from_values(vec![Scalar::Float64(0.0), Scalar::Float64(5.0)]).expect("col");
23956 let r = col.pct_change(1).expect("pct_change");
23957 assert!(r.values()[1].is_missing());
23958 }
23959
23960 #[test]
23961 fn pct_change_timedelta64_matches_pandas_mcu90() {
23962 let one_hour = 3_600 * 1_000_000_000_i64;
23966 let col = Column::from_values(vec![
23967 Scalar::Timedelta64(one_hour),
23968 Scalar::Timedelta64(2 * one_hour),
23969 Scalar::Timedelta64(4 * one_hour),
23970 ])
23971 .expect("col");
23972 let r = col.pct_change(1).expect("pct_change");
23973 assert!(r.values()[0].is_missing());
23974 assert!(
23975 matches!(&r.values()[1], Scalar::Float64(v) if (*v - 1.0).abs() < 1e-10),
23976 "expected Float64(1.0), got {:?}",
23977 r.values()[1]
23978 );
23979 assert!(
23980 matches!(&r.values()[2], Scalar::Float64(v) if (*v - 1.0).abs() < 1e-10),
23981 "expected Float64(1.0), got {:?}",
23982 r.values()[2]
23983 );
23984 }
23985
23986 #[test]
23987 fn pct_change_timedelta64_nat_propagates_mcu90() {
23988 use fp_types::Timedelta;
23989 let one_hour = 3_600 * 1_000_000_000_i64;
23990 let col = Column::from_values(vec![
23991 Scalar::Timedelta64(one_hour),
23992 Scalar::Timedelta64(Timedelta::NAT),
23993 Scalar::Timedelta64(2 * one_hour),
23994 ])
23995 .expect("col");
23996 let r = col.pct_change(1).expect("pct_change");
23997 assert!(r.values()[0].is_missing());
23998 assert!(r.values()[1].is_missing()); assert!(r.values()[2].is_missing()); }
24001
24002 #[test]
24003 fn pct_change_with_fill_ffill_uses_filled_previous_value() {
24004 let col = Column::from_values(vec![
24005 Scalar::Float64(10.0),
24006 Scalar::Null(NullKind::NaN),
24007 Scalar::Float64(12.0),
24008 ])
24009 .expect("col");
24010 let r = col
24011 .pct_change_with_fill(1, Some("ffill"), None)
24012 .expect("pct_change_with_fill");
24013 assert!(r.values()[0].is_missing());
24014 assert!(
24015 matches!(&r.values()[1], Scalar::Float64(v) if v.abs() < 1e-9),
24016 "expected Float64, got {:?}",
24017 r.values()[1]
24018 );
24019 assert!(
24020 matches!(&r.values()[2], Scalar::Float64(v) if (*v - 0.2).abs() < 1e-9),
24021 "expected Float64, got {:?}",
24022 r.values()[2]
24023 );
24024 }
24025
24026 #[test]
24027 fn pct_change_with_fill_limit_caps_forward_fill_runs() {
24028 let col = Column::from_values(vec![
24029 Scalar::Float64(10.0),
24030 Scalar::Null(NullKind::NaN),
24031 Scalar::Null(NullKind::NaN),
24032 Scalar::Float64(20.0),
24033 ])
24034 .expect("col");
24035 let r = col
24036 .pct_change_with_fill(1, Some("ffill"), Some(1))
24037 .expect("pct_change_with_fill");
24038 assert!(r.values()[0].is_missing());
24039 assert!(
24040 matches!(&r.values()[1], Scalar::Float64(v) if v.abs() < 1e-9),
24041 "expected Float64, got {:?}",
24042 r.values()[1]
24043 );
24044 assert!(r.values()[2].is_missing());
24045 assert!(r.values()[3].is_missing());
24046 }
24047
24048 #[test]
24049 fn pct_change_with_fill_bfill_aliases_backward_fill() {
24050 let col = Column::from_values(vec![
24051 Scalar::Float64(10.0),
24052 Scalar::Null(NullKind::NaN),
24053 Scalar::Float64(20.0),
24054 ])
24055 .expect("col");
24056 let r = col
24057 .pct_change_with_fill(1, Some("backfill"), None)
24058 .expect("pct_change_with_fill");
24059 assert!(r.values()[0].is_missing());
24060 assert!(
24061 matches!(&r.values()[1], Scalar::Float64(v) if (*v - 1.0).abs() < 1e-9),
24062 "expected Float64, got {:?}",
24063 r.values()[1]
24064 );
24065 assert!(
24066 matches!(&r.values()[2], Scalar::Float64(v) if v.abs() < 1e-9),
24067 "expected Float64, got {:?}",
24068 r.values()[2]
24069 );
24070 }
24071
24072 #[test]
24073 fn pct_change_with_fill_rejects_invalid_method() {
24074 let col =
24075 Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("col");
24076 let err = col
24077 .pct_change_with_fill(1, Some("nearest"), None)
24078 .expect_err("invalid fill_method should error");
24079 assert!(matches!(
24080 err,
24081 crate::ColumnError::Type(fp_types::TypeError::NonNumericValue { .. })
24082 ));
24083 }
24084
24085 #[test]
24086 fn ffill_fills_trailing_missing_runs() {
24087 let col = Column::from_values(vec![
24088 Scalar::Null(NullKind::NaN),
24089 Scalar::Int64(1),
24090 Scalar::Null(NullKind::NaN),
24091 Scalar::Null(NullKind::NaN),
24092 Scalar::Int64(5),
24093 ])
24094 .expect("col");
24095 let r = col.ffill(None).expect("ffill");
24096 assert!(r.values()[0].is_missing());
24097 assert_eq!(r.values()[1], Scalar::Int64(1));
24098 assert_eq!(r.values()[2], Scalar::Int64(1));
24099 assert_eq!(r.values()[3], Scalar::Int64(1));
24100 assert_eq!(r.values()[4], Scalar::Int64(5));
24101 }
24102
24103 #[test]
24104 fn ffill_respects_limit_per_run() {
24105 let col = Column::from_values(vec![
24106 Scalar::Int64(1),
24107 Scalar::Null(NullKind::NaN),
24108 Scalar::Null(NullKind::NaN),
24109 Scalar::Null(NullKind::NaN),
24110 Scalar::Int64(9),
24111 ])
24112 .expect("col");
24113 let r = col.ffill(Some(2)).expect("ffill");
24114 assert_eq!(r.values()[0], Scalar::Int64(1));
24115 assert_eq!(r.values()[1], Scalar::Int64(1));
24116 assert_eq!(r.values()[2], Scalar::Int64(1));
24117 assert!(r.values()[3].is_missing());
24118 assert_eq!(r.values()[4], Scalar::Int64(9));
24119 assert_eq!(col.pad(Some(2)), col.ffill(Some(2)));
24120 }
24121
24122 #[test]
24123 fn bfill_fills_leading_missing_runs() {
24124 let col = Column::from_values(vec![
24125 Scalar::Null(NullKind::NaN),
24126 Scalar::Null(NullKind::NaN),
24127 Scalar::Int64(3),
24128 Scalar::Null(NullKind::NaN),
24129 ])
24130 .expect("col");
24131 let r = col.bfill(None).expect("bfill");
24132 assert_eq!(r.values()[0], Scalar::Int64(3));
24133 assert_eq!(r.values()[1], Scalar::Int64(3));
24134 assert_eq!(r.values()[2], Scalar::Int64(3));
24135 assert!(r.values()[3].is_missing());
24137 }
24138
24139 #[test]
24140 fn bfill_respects_limit_per_run() {
24141 let col = Column::from_values(vec![
24142 Scalar::Null(NullKind::NaN),
24143 Scalar::Null(NullKind::NaN),
24144 Scalar::Null(NullKind::NaN),
24145 Scalar::Int64(7),
24146 ])
24147 .expect("col");
24148 let r = col.bfill(Some(1)).expect("bfill");
24149 assert!(r.values()[0].is_missing());
24150 assert!(r.values()[1].is_missing());
24151 assert_eq!(r.values()[2], Scalar::Int64(7));
24152 assert_eq!(r.values()[3], Scalar::Int64(7));
24153 assert_eq!(col.backfill(Some(1)), col.bfill(Some(1)));
24154 }
24155
24156 #[test]
24157 fn ffill_empty_is_empty_same_dtype() {
24158 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
24159 let r = col.ffill(None).expect("ffill");
24160 assert!(r.is_empty());
24161 assert_eq!(r.dtype(), DType::Null);
24162 }
24163
24164 #[test]
24165 fn pandas_metadata_and_materialization_aliases_match_core_methods()
24166 -> Result<(), crate::ColumnError> {
24167 let col = Column::from_values(vec![
24168 Scalar::Int64(1),
24169 Scalar::Null(NullKind::NaN),
24170 Scalar::Int64(2),
24171 ])?;
24172
24173 assert_eq!(col.size(), col.len());
24174 assert_eq!(col.shape(), (col.len(),));
24175 assert_eq!(col.ndim(), 1);
24176 assert_eq!(col.empty(), col.is_empty());
24177 assert_eq!(col.to_list(), col.to_vec());
24178 assert_eq!(col.tolist(), col.to_vec());
24179 assert_eq!(col.to_numpy(), col.to_vec());
24180 assert_eq!(col.ravel(), col.to_numpy());
24181 assert_eq!(col.array(), col.to_vec());
24182 Ok(())
24183 }
24184
24185 #[test]
24186 fn isnull_notnull_flag_missing_positions() {
24187 let col = Column::from_values(vec![
24188 Scalar::Int64(1),
24189 Scalar::Null(NullKind::NaN),
24190 Scalar::Int64(2),
24191 ])
24192 .expect("col");
24193 let is_null = col.isnull().expect("isnull");
24194 let not_null = col.notnull().expect("notnull");
24195 assert_eq!(is_null.dtype(), DType::Bool);
24196 assert_eq!(
24197 is_null.values(),
24198 &[Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(false),]
24199 );
24200 assert_eq!(col.isna(), col.isnull());
24201 assert_eq!(
24202 not_null.values(),
24203 &[Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true),]
24204 );
24205 assert_eq!(col.notna(), col.notnull());
24206 }
24207
24208 #[test]
24209 fn null_predicates_match_scalar_oracle_zvykt() {
24210 fn next(seed: &mut u64) -> u64 {
24213 *seed = seed
24214 .wrapping_mul(6364136223846793005)
24215 .wrapping_add(1442695040888963407);
24216 *seed
24217 }
24218
24219 let mut seed = 0x5a17_1e55_0b5e_7a11_u64;
24220 for case in 0..260 {
24221 let len = (next(&mut seed) % 73 + 1) as usize;
24222 let mut values = Vec::with_capacity(len);
24223 for pos in 0..len {
24224 let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
24225 let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
24226 values.push(match next(&mut seed) % 10 {
24227 0 => Scalar::Null(NullKind::Null),
24228 1 => Scalar::Null(NullKind::NaN),
24229 2 => Scalar::Float64(f64::NAN),
24230 3 => Scalar::Float64(f64::INFINITY),
24231 4 => Scalar::Float64(f64::NEG_INFINITY),
24232 5 => Scalar::Float64(raw as f64 / 41.0 + frac),
24233 6 => Scalar::Int64(raw),
24234 7 => Scalar::Bool(raw & 1 == 0),
24235 8 => Scalar::Utf8(format!("v{case}_{pos}")),
24236 _ => Scalar::Timedelta64(raw),
24237 });
24238 }
24239
24240 let input = Column::from_values(values.clone()).expect("column");
24241 let is_null = input.isnull().expect("isnull");
24242 let is_na = input.isna().expect("isna");
24243 let not_null = input.notnull().expect("notnull");
24244 let not_na = input.notna().expect("notna");
24245
24246 assert_eq!(is_null.dtype(), DType::Bool);
24247 assert_eq!(is_na.values(), is_null.values());
24248 assert_eq!(not_na.values(), not_null.values());
24249 assert_eq!(is_null.values().len(), values.len());
24250 assert_eq!(not_null.values().len(), values.len());
24251
24252 for (pos, value) in values.iter().enumerate() {
24253 let missing = value.is_missing();
24254 assert_eq!(
24255 is_null.values()[pos],
24256 Scalar::Bool(missing),
24257 "case={case} pos={pos}: isnull mismatch for {value:?}"
24258 );
24259 assert_eq!(
24260 not_null.values()[pos],
24261 Scalar::Bool(!missing),
24262 "case={case} pos={pos}: notnull mismatch for {value:?}"
24263 );
24264 }
24265 }
24266 }
24267
24268 #[test]
24269 fn missing_reducers_match_scalar_oracle_8n9cp() {
24270 fn next(seed: &mut u64) -> u64 {
24273 *seed = seed
24274 .wrapping_mul(2862933555777941757)
24275 .wrapping_add(3037000493);
24276 *seed
24277 }
24278
24279 let empty = Column::new(DType::Float64, Vec::new()).expect("empty");
24280 assert!(!empty.has_any_missing());
24281 assert!(!empty.hasnans());
24282 assert!(empty.all_missing());
24283
24284 let mut seed = 0x8a11_a115_1d5d_0a7a_u64;
24285 for case in 0..260 {
24286 let len = (next(&mut seed) % 79 + 1) as usize;
24287 let mut values = Vec::with_capacity(len);
24288 for pos in 0..len {
24289 let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
24290 let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
24291 values.push(match next(&mut seed) % 10 {
24292 0 => Scalar::Null(NullKind::Null),
24293 1 => Scalar::Null(NullKind::NaN),
24294 2 => Scalar::Float64(f64::NAN),
24295 3 => Scalar::Float64(f64::INFINITY),
24296 4 => Scalar::Float64(f64::NEG_INFINITY),
24297 5 => Scalar::Float64(raw as f64 / 43.0 + frac),
24298 6 => Scalar::Int64(raw),
24299 7 => Scalar::Bool(raw & 1 == 0),
24300 8 => Scalar::Utf8(format!("m{case}_{pos}")),
24301 _ => Scalar::Timedelta64(raw),
24302 });
24303 }
24304
24305 let input = Column::from_values(values.clone()).expect("column");
24306 let any_missing = values.iter().any(Scalar::is_missing);
24307 let all_missing = values.iter().all(Scalar::is_missing);
24308
24309 assert_eq!(
24310 input.has_any_missing(),
24311 any_missing,
24312 "case={case}: has_any_missing mismatch for {values:?}"
24313 );
24314 assert_eq!(
24315 input.hasnans(),
24316 any_missing,
24317 "case={case}: hasnans mismatch for {values:?}"
24318 );
24319 assert_eq!(
24320 input.all_missing(),
24321 all_missing,
24322 "case={case}: all_missing mismatch for {values:?}"
24323 );
24324 }
24325 }
24326
24327 #[test]
24328 fn isnull_notnull_use_nullable_int64_validity_without_scalar_materialization_nakgb() {
24329 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2), (5, 1)]), 6);
24330 let col = Column::from_i64_values_with_validity((0_i64..6).collect(), validity);
24331
24332 let is_null = col.isnull().expect("isnull");
24333 let not_null = col.notnull().expect("notnull");
24334
24335 assert_eq!(
24336 is_null.values(),
24337 &[
24338 Scalar::Bool(false),
24339 Scalar::Bool(true),
24340 Scalar::Bool(true),
24341 Scalar::Bool(false),
24342 Scalar::Bool(false),
24343 Scalar::Bool(true),
24344 ]
24345 );
24346 assert_eq!(
24347 not_null.values(),
24348 &[
24349 Scalar::Bool(true),
24350 Scalar::Bool(false),
24351 Scalar::Bool(false),
24352 Scalar::Bool(true),
24353 Scalar::Bool(true),
24354 Scalar::Bool(false),
24355 ]
24356 );
24357 assert!(matches!(
24358 &col.values,
24359 ScalarValues::LazyNullableInt64 { .. }
24360 ));
24361 if let ScalarValues::LazyNullableInt64 { values, .. } = &col.values {
24362 assert!(values.get().is_none());
24363 }
24364 }
24365
24366 #[test]
24367 fn isnull_notnull_float64_raw_path_checks_nan_without_scalar_materialization_nakgb() {
24368 let col = Column {
24369 dtype: DType::Float64,
24370 values: ScalarValues::lazy_all_valid_float64(vec![1.0, f64::NAN, f64::INFINITY]),
24371 validity: ValidityMask::all_valid(3),
24372 data: None,
24373 };
24374
24375 let is_null = col.isnull().expect("isnull");
24376 let not_null = col.notnull().expect("notnull");
24377
24378 assert_eq!(
24379 is_null.values(),
24380 &[Scalar::Bool(false), Scalar::Bool(true), Scalar::Bool(false),]
24381 );
24382 assert_eq!(
24383 not_null.values(),
24384 &[Scalar::Bool(true), Scalar::Bool(false), Scalar::Bool(true),]
24385 );
24386 assert!(matches!(
24387 &col.values,
24388 ScalarValues::LazyAllValidFloat64 { .. }
24389 ));
24390 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &col.values {
24391 assert!(values.get().is_none());
24392 }
24393 }
24394
24395 #[test]
24396 fn float64_predicate_masks_use_raw_validity_without_scalar_materialization_ti9f1() {
24397 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 1)]), 4);
24398 let col = Column::from_f64_values_with_validity(
24399 vec![1.0, 0.0, f64::NAN, f64::INFINITY],
24400 validity,
24401 );
24402
24403 assert_eq!(
24404 col.isfinite().expect("isfinite").values(),
24405 &[
24406 Scalar::Bool(true),
24407 Scalar::Bool(false),
24408 Scalar::Bool(false),
24409 Scalar::Bool(false),
24410 ]
24411 );
24412 assert_eq!(
24413 col.isinf().expect("isinf").values(),
24414 &[
24415 Scalar::Bool(false),
24416 Scalar::Bool(false),
24417 Scalar::Bool(false),
24418 Scalar::Bool(true),
24419 ]
24420 );
24421 assert_eq!(
24422 col.isnan().expect("isnan").values(),
24423 &[
24424 Scalar::Bool(false),
24425 Scalar::Bool(true),
24426 Scalar::Bool(true),
24427 Scalar::Bool(false),
24428 ]
24429 );
24430 assert!(matches!(
24431 &col.values,
24432 ScalarValues::LazyNullableFloat64 { .. }
24433 ));
24434 if let ScalarValues::LazyNullableFloat64 { values, .. } = &col.values {
24435 assert!(values.get().is_none());
24436 }
24437 }
24438
24439 #[test]
24440 fn finite_predicates_match_scalar_oracle_dknku() {
24441 fn next(seed: &mut u64) -> u64 {
24444 *seed = seed
24445 .wrapping_mul(1442695040888963407)
24446 .wrapping_add(6364136223846793005);
24447 *seed
24448 }
24449
24450 fn oracle(value: &Scalar) -> (bool, bool, bool) {
24451 let isfinite = match value {
24452 Scalar::Float64(v) => v.is_finite(),
24453 Scalar::Int64(_) => true,
24454 _ if value.is_missing() => false,
24455 _ => true,
24456 };
24457 let isinf = matches!(value, Scalar::Float64(v) if v.is_infinite());
24458 let isnan = match value {
24459 Scalar::Float64(v) => v.is_nan(),
24460 Scalar::Null(NullKind::NaN) => true,
24461 _ => false,
24462 };
24463 (isfinite, isinf, isnan)
24464 }
24465
24466 let mut seed = 0xd1ff_1e5d_f1a7_00c5_u64;
24467 for case in 0..240 {
24468 let len = (next(&mut seed) % 71 + 1) as usize;
24469 let mut values = Vec::with_capacity(len);
24470 for pos in 0..len {
24471 let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
24472 let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
24473 values.push(match next(&mut seed) % 9 {
24474 0 => Scalar::Null(NullKind::Null),
24475 1 => Scalar::Null(NullKind::NaN),
24476 2 => Scalar::Float64(f64::NAN),
24477 3 => Scalar::Float64(f64::INFINITY),
24478 4 => Scalar::Float64(f64::NEG_INFINITY),
24479 5 => Scalar::Int64(raw),
24480 6 => Scalar::Utf8(format!("s{case}_{pos}")),
24481 _ => Scalar::Float64(raw as f64 / 37.0 + frac),
24482 });
24483 }
24484
24485 let input = Column::from_values(values.clone()).expect("column");
24486 let finite = input.isfinite().expect("isfinite");
24487 let infinite = input.isinf().expect("isinf");
24488 let nan = input.isnan().expect("isnan");
24489
24490 assert_eq!(finite.dtype(), DType::Bool);
24491 assert_eq!(infinite.dtype(), DType::Bool);
24492 assert_eq!(nan.dtype(), DType::Bool);
24493 assert_eq!(finite.values().len(), values.len());
24494 assert_eq!(infinite.values().len(), values.len());
24495 assert_eq!(nan.values().len(), values.len());
24496
24497 for (pos, value) in values.iter().enumerate() {
24498 let (expected_finite, expected_inf, expected_nan) = oracle(value);
24499 assert_eq!(
24500 finite.values()[pos],
24501 Scalar::Bool(expected_finite),
24502 "case={case} pos={pos}: isfinite mismatch for {value:?}"
24503 );
24504 assert_eq!(
24505 infinite.values()[pos],
24506 Scalar::Bool(expected_inf),
24507 "case={case} pos={pos}: isinf mismatch for {value:?}"
24508 );
24509 assert_eq!(
24510 nan.values()[pos],
24511 Scalar::Bool(expected_nan),
24512 "case={case} pos={pos}: isnan mismatch for {value:?}"
24513 );
24514 }
24515 }
24516 }
24517
24518 #[test]
24519 fn logical_bool_ops_use_raw_buffers_without_scalar_materialization_el0g2() {
24520 let left = Column {
24521 dtype: DType::Bool,
24522 values: ScalarValues::lazy_all_valid_bool(vec![true, false, true, false]),
24523 validity: ValidityMask::all_valid(4),
24524 data: None,
24525 };
24526 let right = Column {
24527 dtype: DType::Bool,
24528 values: ScalarValues::lazy_all_valid_bool(vec![true, true, false, false]),
24529 validity: ValidityMask::all_valid(4),
24530 data: None,
24531 };
24532
24533 assert_eq!(
24534 left.logical_and(&right).expect("and").values(),
24535 &[
24536 Scalar::Bool(true),
24537 Scalar::Bool(false),
24538 Scalar::Bool(false),
24539 Scalar::Bool(false),
24540 ]
24541 );
24542 assert_eq!(
24543 left.logical_or(&right).expect("or").values(),
24544 &[
24545 Scalar::Bool(true),
24546 Scalar::Bool(true),
24547 Scalar::Bool(true),
24548 Scalar::Bool(false),
24549 ]
24550 );
24551 assert_eq!(
24552 left.logical_xor(&right).expect("xor").values(),
24553 &[
24554 Scalar::Bool(false),
24555 Scalar::Bool(true),
24556 Scalar::Bool(true),
24557 Scalar::Bool(false),
24558 ]
24559 );
24560 assert_eq!(
24561 left.logical_not().expect("not").values(),
24562 &[
24563 Scalar::Bool(false),
24564 Scalar::Bool(true),
24565 Scalar::Bool(false),
24566 Scalar::Bool(true),
24567 ]
24568 );
24569
24570 assert!(matches!(
24571 &left.values,
24572 ScalarValues::LazyAllValidBool { .. }
24573 ));
24574 assert!(matches!(
24575 &right.values,
24576 ScalarValues::LazyAllValidBool { .. }
24577 ));
24578 if let ScalarValues::LazyAllValidBool { values, .. } = &left.values {
24579 assert!(values.get().is_none());
24580 }
24581 if let ScalarValues::LazyAllValidBool { values, .. } = &right.values {
24582 assert!(values.get().is_none());
24583 }
24584 }
24585
24586 #[test]
24587 fn bitwise_bool_ops_use_raw_buffers_without_scalar_materialization_ffoy7() {
24588 let left = Column {
24589 dtype: DType::Bool,
24590 values: ScalarValues::lazy_all_valid_bool(vec![true, false, true, false]),
24591 validity: ValidityMask::all_valid(4),
24592 data: None,
24593 };
24594 let right = Column {
24595 dtype: DType::Bool,
24596 values: ScalarValues::lazy_all_valid_bool(vec![false, false, true, true]),
24597 validity: ValidityMask::all_valid(4),
24598 data: None,
24599 };
24600
24601 assert_eq!(
24602 left.bitwise_and(&right).expect("and").values(),
24603 &[
24604 Scalar::Bool(false),
24605 Scalar::Bool(false),
24606 Scalar::Bool(true),
24607 Scalar::Bool(false),
24608 ]
24609 );
24610 assert_eq!(
24611 left.bitwise_or(&right).expect("or").values(),
24612 &[
24613 Scalar::Bool(true),
24614 Scalar::Bool(false),
24615 Scalar::Bool(true),
24616 Scalar::Bool(true),
24617 ]
24618 );
24619 assert_eq!(
24620 left.bitwise_xor(&right).expect("xor").values(),
24621 &[
24622 Scalar::Bool(true),
24623 Scalar::Bool(false),
24624 Scalar::Bool(false),
24625 Scalar::Bool(true),
24626 ]
24627 );
24628 assert_eq!(
24629 left.bitwise_not().expect("not").values(),
24630 &[
24631 Scalar::Bool(false),
24632 Scalar::Bool(true),
24633 Scalar::Bool(false),
24634 Scalar::Bool(true),
24635 ]
24636 );
24637
24638 assert!(matches!(
24639 &left.values,
24640 ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
24641 ));
24642 assert!(matches!(
24643 &right.values,
24644 ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
24645 ));
24646 }
24647
24648 #[test]
24649 fn bool_comparison_ops_use_raw_buffers_without_scalar_materialization_v7rko() {
24650 let left = Column {
24651 dtype: DType::Bool,
24652 values: ScalarValues::lazy_all_valid_bool(vec![false, false, true, true]),
24653 validity: ValidityMask::all_valid(4),
24654 data: None,
24655 };
24656 let right = Column {
24657 dtype: DType::Bool,
24658 values: ScalarValues::lazy_all_valid_bool(vec![false, true, false, true]),
24659 validity: ValidityMask::all_valid(4),
24660 data: None,
24661 };
24662
24663 assert_eq!(
24664 left.eq(&right).expect("eq").values(),
24665 &[
24666 Scalar::Bool(true),
24667 Scalar::Bool(false),
24668 Scalar::Bool(false),
24669 Scalar::Bool(true),
24670 ]
24671 );
24672 assert_eq!(
24673 left.ne(&right).expect("ne").values(),
24674 &[
24675 Scalar::Bool(false),
24676 Scalar::Bool(true),
24677 Scalar::Bool(true),
24678 Scalar::Bool(false),
24679 ]
24680 );
24681 assert_eq!(
24682 left.gt(&right).expect("gt").values(),
24683 &[
24684 Scalar::Bool(false),
24685 Scalar::Bool(false),
24686 Scalar::Bool(true),
24687 Scalar::Bool(false),
24688 ]
24689 );
24690 assert_eq!(
24691 left.lt(&right).expect("lt").values(),
24692 &[
24693 Scalar::Bool(false),
24694 Scalar::Bool(true),
24695 Scalar::Bool(false),
24696 Scalar::Bool(false),
24697 ]
24698 );
24699 assert_eq!(
24700 left.ge(&right).expect("ge").values(),
24701 &[
24702 Scalar::Bool(true),
24703 Scalar::Bool(false),
24704 Scalar::Bool(true),
24705 Scalar::Bool(true),
24706 ]
24707 );
24708 assert_eq!(
24709 left.le(&right).expect("le").values(),
24710 &[
24711 Scalar::Bool(true),
24712 Scalar::Bool(true),
24713 Scalar::Bool(false),
24714 Scalar::Bool(true),
24715 ]
24716 );
24717
24718 assert!(matches!(
24719 &left.values,
24720 ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
24721 ));
24722 assert!(matches!(
24723 &right.values,
24724 ScalarValues::LazyAllValidBool { values, .. } if values.get().is_none()
24725 ));
24726 }
24727
24728 #[test]
24729 fn var_std_sem_ddof_one() {
24730 let col = Column::from_values(vec![
24731 Scalar::Float64(2.0),
24732 Scalar::Float64(4.0),
24733 Scalar::Float64(4.0),
24734 Scalar::Float64(4.0),
24735 Scalar::Float64(5.0),
24736 Scalar::Float64(5.0),
24737 Scalar::Float64(7.0),
24738 Scalar::Float64(9.0),
24739 ])
24740 .expect("col");
24741 match col.var(1) {
24742 Scalar::Float64(v) => assert!((v - 4.571428571428571).abs() < 1e-9),
24743 other => unreachable!("expected Float64, got {other:?}"),
24744 }
24745 match col.std(1) {
24746 Scalar::Float64(v) => assert!((v - 2.138089935299395).abs() < 1e-9),
24747 other => unreachable!("expected Float64, got {other:?}"),
24748 }
24749 match col.sem(1) {
24750 Scalar::Float64(v) => assert!((v - 0.7559289460184544).abs() < 1e-9),
24751 other => unreachable!("expected Float64, got {other:?}"),
24752 }
24753 }
24754
24755 #[test]
24756 fn skew_symmetric_is_zero() {
24757 let col = Column::from_values(vec![
24758 Scalar::Float64(1.0),
24759 Scalar::Float64(2.0),
24760 Scalar::Float64(3.0),
24761 Scalar::Float64(4.0),
24762 Scalar::Float64(5.0),
24763 ])
24764 .expect("col");
24765 match col.skew() {
24766 Scalar::Float64(v) => assert!(v.abs() < 1e-9),
24767 other => unreachable!("expected Float64, got {other:?}"),
24768 }
24769 }
24770
24771 #[test]
24772 fn kurt_uniform_five_values_is_minus_one_point_two() {
24773 let col = Column::from_values(vec![
24774 Scalar::Float64(1.0),
24775 Scalar::Float64(2.0),
24776 Scalar::Float64(3.0),
24777 Scalar::Float64(4.0),
24778 Scalar::Float64(5.0),
24779 ])
24780 .expect("col");
24781 match col.kurt() {
24782 Scalar::Float64(v) => assert!((v + 1.2).abs() < 1e-9),
24783 other => unreachable!("expected Float64, got {other:?}"),
24784 }
24785 }
24786
24787 #[test]
24788 fn kurtosis_alias_matches_kurt() {
24789 let col = Column::from_values(vec![
24790 Scalar::Float64(1.0),
24791 Scalar::Float64(2.0),
24792 Scalar::Float64(3.0),
24793 Scalar::Float64(4.0),
24794 Scalar::Float64(5.0),
24795 ])
24796 .expect("col");
24797 assert_eq!(col.kurtosis(), col.kurt());
24798 }
24799
24800 #[test]
24801 fn ptp_returns_max_minus_min() {
24802 let col = Column::from_values(vec![
24803 Scalar::Float64(3.0),
24804 Scalar::Null(NullKind::NaN),
24805 Scalar::Float64(7.0),
24806 Scalar::Float64(1.0),
24807 ])
24808 .expect("col");
24809 assert_eq!(col.ptp(), Scalar::Float64(6.0));
24810 }
24811
24812 #[test]
24813 fn ptp_empty_is_null() {
24814 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
24815 assert!(col.ptp().is_missing());
24816 }
24817
24818 #[test]
24819 fn skew_too_few_values_returns_null() {
24820 let col =
24821 Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("col");
24822 assert!(col.skew().is_missing());
24823 }
24824
24825 #[test]
24826 fn rolling_window_sum_full_window() {
24827 let col = Column::from_values(vec![
24828 Scalar::Float64(1.0),
24829 Scalar::Float64(2.0),
24830 Scalar::Float64(3.0),
24831 Scalar::Float64(4.0),
24832 Scalar::Float64(5.0),
24833 ])
24834 .expect("col");
24835 let r = col.rolling_window_sum(3, 3).expect("rolling");
24837 assert!(r.values()[0].is_missing());
24838 assert!(r.values()[1].is_missing());
24839 assert_eq!(r.values()[2], Scalar::Float64(6.0));
24840 assert_eq!(r.values()[3], Scalar::Float64(9.0));
24841 assert_eq!(r.values()[4], Scalar::Float64(12.0));
24842 }
24843
24844 #[test]
24845 fn rolling_window_sum_min_periods_relaxed() {
24846 let col = Column::from_values(vec![
24847 Scalar::Float64(1.0),
24848 Scalar::Float64(2.0),
24849 Scalar::Float64(3.0),
24850 ])
24851 .expect("col");
24852 let r = col.rolling_window_sum(3, 1).expect("rolling");
24854 assert_eq!(r.values()[0], Scalar::Float64(1.0));
24855 assert_eq!(r.values()[1], Scalar::Float64(3.0));
24856 assert_eq!(r.values()[2], Scalar::Float64(6.0));
24857 }
24858
24859 #[test]
24860 fn rolling_window_sum_skips_missing() {
24861 let col = Column::from_values(vec![
24862 Scalar::Float64(1.0),
24863 Scalar::Null(NullKind::NaN),
24864 Scalar::Float64(3.0),
24865 Scalar::Float64(4.0),
24866 ])
24867 .expect("col");
24868 let r = col.rolling_window_sum(3, 2).expect("rolling");
24874 assert!(r.values()[0].is_missing());
24875 assert!(r.values()[1].is_missing());
24876 assert_eq!(r.values()[2], Scalar::Float64(4.0));
24877 assert_eq!(r.values()[3], Scalar::Float64(7.0));
24878 }
24879
24880 #[test]
24881 fn rolling_window_sum_window_zero_is_all_null() {
24882 let col =
24883 Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(2.0)]).expect("col");
24884 let r = col.rolling_window_sum(0, 0).expect("rolling");
24885 assert!(r.values()[0].is_missing());
24886 assert!(r.values()[1].is_missing());
24887 assert_eq!(r.dtype(), DType::Float64);
24888 }
24889
24890 #[test]
24891 fn diff_valid_skips_missing_predecessors() {
24892 let col = Column::from_values(vec![
24893 Scalar::Null(NullKind::NaN),
24894 Scalar::Float64(1.0),
24895 Scalar::Null(NullKind::NaN),
24896 Scalar::Float64(4.0),
24897 Scalar::Float64(7.0),
24898 ])
24899 .expect("col");
24900 let r = col.diff_valid().expect("diff_valid");
24901 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)); }
24907
24908 #[test]
24909 fn diff_valid_empty_column() {
24910 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
24911 let r = col.diff_valid().expect("diff_valid");
24912 assert!(r.is_empty());
24913 assert_eq!(r.dtype(), DType::Float64);
24914 }
24915
24916 #[test]
24917 fn sample_without_replacement_deterministic_by_seed() {
24918 let col =
24919 Column::from_values((0..10).map(Scalar::Int64).collect::<Vec<_>>()).expect("col");
24920 let a = col.sample(3, 42).expect("sample");
24921 let b = col.sample(3, 42).expect("sample");
24922 assert_eq!(a.values(), b.values());
24924 assert_eq!(a.len(), 3);
24925 for v in a.values() {
24927 match v {
24928 Scalar::Int64(x) => assert!((0..10).contains(x)),
24929 other => unreachable!("unexpected value {other:?}"),
24930 }
24931 }
24932 }
24933
24934 #[test]
24935 fn sample_different_seeds_likely_differ() {
24936 let col =
24937 Column::from_values((0..100).map(Scalar::Int64).collect::<Vec<_>>()).expect("col");
24938 let a = col.sample(5, 1).expect("sample");
24939 let b = col.sample(5, 2).expect("sample");
24940 assert_ne!(a.values(), b.values());
24943 }
24944
24945 #[test]
24946 fn sample_n_at_or_above_len_returns_clone() {
24947 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
24948 let r = col.sample(10, 42).expect("sample");
24949 assert_eq!(r.values(), col.values());
24950 }
24951
24952 #[test]
24953 fn first_valid_last_valid_skip_nulls() {
24954 let col = Column::from_values(vec![
24955 Scalar::Null(NullKind::NaN),
24956 Scalar::Null(NullKind::NaN),
24957 Scalar::Int64(5),
24958 Scalar::Int64(7),
24959 Scalar::Null(NullKind::NaN),
24960 ])
24961 .expect("col");
24962 assert_eq!(col.first_valid(), Some(2));
24963 assert_eq!(col.last_valid(), Some(3));
24964 assert_eq!(col.first_valid_index(), Some(2));
24965 assert_eq!(col.last_valid_index(), Some(3));
24966 }
24967
24968 #[test]
24969 fn nsmallest_keep_first_breaks_ties_by_earlier_position() {
24970 let col = Column::from_values(vec![
24971 Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(1), Scalar::Int64(3), Scalar::Int64(1), ])
24977 .expect("col");
24978 let r = col.nsmallest_keep(2, "first").expect("nsmallest_keep");
24979 assert_eq!(r.len(), 2);
24981 assert_eq!(r.values()[0], Scalar::Int64(1));
24982 assert_eq!(r.values()[1], Scalar::Int64(1));
24983 }
24984
24985 #[test]
24986 fn nsmallest_keep_last_breaks_ties_by_later_position() {
24987 let col = Column::from_values(vec![
24988 Scalar::Int64(1), Scalar::Int64(2),
24990 Scalar::Int64(1), Scalar::Int64(3),
24992 Scalar::Int64(1), ])
24994 .expect("col");
24995 let r = col.nsmallest_keep(2, "last").expect("nsmallest_keep");
24997 assert_eq!(r.len(), 2);
24998 assert_eq!(r.values()[0], Scalar::Int64(1));
24999 assert_eq!(r.values()[1], Scalar::Int64(1));
25000 }
25001
25002 #[test]
25003 fn nsmallest_keep_all_expands_beyond_n_on_ties() {
25004 let col = Column::from_values(vec![
25005 Scalar::Int64(1),
25006 Scalar::Int64(1),
25007 Scalar::Int64(1),
25008 Scalar::Int64(2),
25009 ])
25010 .expect("col");
25011 let r = col.nsmallest_keep(1, "all").expect("nsmallest_keep");
25013 assert_eq!(r.len(), 3);
25014 assert_eq!(r.values()[0], Scalar::Int64(1));
25015 assert_eq!(r.values()[1], Scalar::Int64(1));
25016 assert_eq!(r.values()[2], Scalar::Int64(1));
25017 }
25018
25019 #[test]
25020 fn nlargest_keep_mirror_symmetry() {
25021 let col = Column::from_values(vec![
25022 Scalar::Int64(1),
25023 Scalar::Int64(3),
25024 Scalar::Int64(3),
25025 Scalar::Int64(2),
25026 ])
25027 .expect("col");
25028 let r = col.nlargest_keep(1, "all").expect("nlargest_keep");
25029 assert_eq!(r.len(), 2);
25030 assert_eq!(r.values()[0], Scalar::Int64(3));
25031 assert_eq!(r.values()[1], Scalar::Int64(3));
25032 }
25033
25034 #[test]
25035 fn nkeep_invalid_keep_errors() {
25036 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25037 assert!(col.nsmallest_keep(1, "middle").is_err());
25038 assert!(col.nlargest_keep(1, "middle").is_err());
25039 }
25040
25041 #[test]
25042 fn nkeep_zero_is_empty_same_dtype() {
25043 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25044 let r = col.nsmallest_keep(0, "first").expect("nsmallest_keep");
25045 assert!(r.is_empty());
25046 assert_eq!(r.dtype(), DType::Int64);
25047 }
25048
25049 #[test]
25050 fn first_valid_last_valid_all_missing_is_none() {
25051 let col = Column::from_values(vec![
25052 Scalar::Null(NullKind::NaN),
25053 Scalar::Null(NullKind::Null),
25054 ])
25055 .expect("col");
25056 assert_eq!(col.first_valid(), None);
25057 assert_eq!(col.last_valid(), None);
25058 assert_eq!(col.first_valid_index(), None);
25059 assert_eq!(col.last_valid_index(), None);
25060 }
25061
25062 #[test]
25063 fn rolling_window_sum_empty_column() {
25064 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
25065 let r = col.rolling_window_sum(3, 1).expect("rolling");
25066 assert!(r.is_empty());
25067 assert_eq!(r.dtype(), DType::Float64);
25068 }
25069
25070 #[test]
25071 fn pct_change_negative_periods() {
25072 let col = Column::from_values(vec![Scalar::Float64(10.0), Scalar::Float64(15.0)])
25073 .expect("col");
25074 let r = col.pct_change(-1).expect("pct_change");
25075 assert!(
25077 matches!(&r.values()[0], Scalar::Float64(v) if (*v + 1.0 / 3.0).abs() < 1e-9),
25078 "expected Float64, got {:?}",
25079 r.values()[0]
25080 );
25081 assert!(r.values()[1].is_missing());
25082 }
25083
25084 #[test]
25085 fn count_excludes_nulls() {
25086 let col = Column::from_values(vec![
25087 Scalar::Int64(1),
25088 Scalar::Null(NullKind::NaN),
25089 Scalar::Int64(2),
25090 Scalar::Null(NullKind::Null),
25091 ])
25092 .expect("col");
25093 assert_eq!(col.count(), 2);
25094 }
25095
25096 #[test]
25097 fn count_and_nunique_match_scalar_oracle_05112() {
25098 fn next(seed: &mut u64) -> u64 {
25101 *seed = seed
25102 .wrapping_mul(6364136223846793005)
25103 .wrapping_add(1442695040888963407);
25104 *seed
25105 }
25106
25107 fn same_unique_bucket(left: &Scalar, right: &Scalar) -> bool {
25108 match (left, right) {
25109 (Scalar::Float64(left), Scalar::Float64(right)) => {
25110 let left = if *left == 0.0 { 0.0 } else { *left };
25111 let right = if *right == 0.0 { 0.0 } else { *right };
25112 left.to_bits() == right.to_bits()
25113 }
25114 _ => left == right,
25115 }
25116 }
25117
25118 fn expected_nunique(values: &[Scalar], dropna: bool) -> i64 {
25119 let mut seen = Vec::<Scalar>::new();
25120 let mut saw_missing = false;
25121 for value in values {
25122 if value.is_missing() {
25123 saw_missing = true;
25124 continue;
25125 }
25126 if !seen
25127 .iter()
25128 .any(|existing| same_unique_bucket(existing, value))
25129 {
25130 seen.push(value.clone());
25131 }
25132 }
25133 let missing_bucket = i64::from(!dropna && saw_missing);
25134 seen.len() as i64 + missing_bucket
25135 }
25136
25137 fn assert_reducers(case: usize, family: &str, values: Vec<Scalar>) {
25138 let input = Column::from_values(values.clone()).expect("column");
25139 let expected_count = values.iter().filter(|value| !value.is_missing()).count();
25140 assert_eq!(
25141 input.count(),
25142 expected_count,
25143 "case={case} family={family}: count mismatch for {values:?}"
25144 );
25145 assert_eq!(
25146 input.nunique(),
25147 Scalar::Int64(expected_nunique(&values, true)),
25148 "case={case} family={family}: nunique(dropna=true) mismatch for {values:?}"
25149 );
25150 assert_eq!(
25151 input.nunique_with_dropna(false),
25152 Scalar::Int64(expected_nunique(&values, false)),
25153 "case={case} family={family}: nunique(dropna=false) mismatch for {values:?}"
25154 );
25155 }
25156
25157 let all_missing = vec![
25158 Scalar::Null(NullKind::Null),
25159 Scalar::Null(NullKind::NaN),
25160 Scalar::Float64(f64::NAN),
25161 Scalar::Timedelta64(i64::MIN),
25162 ];
25163 assert_reducers(usize::MAX, "all_missing", all_missing);
25164
25165 let mut seed = 0x0511_2c0a_1e5c_a1a5_u64;
25166 for case in 0..180 {
25167 let len = (next(&mut seed) % 67 + 1) as usize;
25168
25169 let mut floats = Vec::with_capacity(len);
25170 floats.push(Scalar::Float64(0.0));
25171 for _ in 1..len {
25172 let raw = (next(&mut seed) % 10_001) as i64 - 5_000;
25173 let value = match next(&mut seed) % 9 {
25174 0 => f64::NAN,
25175 1 => f64::INFINITY,
25176 2 => f64::NEG_INFINITY,
25177 3 => -0.0,
25178 4 => 0.0,
25179 _ => raw as f64 / 17.0,
25180 };
25181 floats.push(Scalar::Float64(value));
25182 }
25183 assert_reducers(case, "float", floats);
25184
25185 let mut ints = Vec::with_capacity(len);
25186 ints.push(Scalar::Int64(case as i64 % 11 - 5));
25187 for _ in 1..len {
25188 let raw = (next(&mut seed) % 41) as i64 - 20;
25189 ints.push(match next(&mut seed) % 6 {
25190 0 => Scalar::Null(NullKind::Null),
25191 1 => Scalar::Null(NullKind::NaN),
25192 _ => Scalar::Int64(raw),
25193 });
25194 }
25195 assert_reducers(case, "int", ints);
25196
25197 let mut bools = Vec::with_capacity(len);
25198 bools.push(Scalar::Bool(case & 1 == 0));
25199 for _ in 1..len {
25200 bools.push(match next(&mut seed) % 5 {
25201 0 => Scalar::Null(NullKind::Null),
25202 1 => Scalar::Null(NullKind::NaN),
25203 raw => Scalar::Bool(raw & 1 == 0),
25204 });
25205 }
25206 assert_reducers(case, "bool", bools);
25207
25208 let mut utf8 = Vec::with_capacity(len);
25209 utf8.push(Scalar::Utf8(format!("s{}", case % 13)));
25210 for pos in 1..len {
25211 utf8.push(match next(&mut seed) % 7 {
25212 0 => Scalar::Null(NullKind::Null),
25213 1 => Scalar::Null(NullKind::NaN),
25214 raw => Scalar::Utf8(format!("s{}_{}", raw, pos % 5)),
25215 });
25216 }
25217 assert_reducers(case, "utf8", utf8);
25218
25219 let mut timedeltas = Vec::with_capacity(len);
25220 timedeltas.push(Scalar::Timedelta64(case as i64));
25221 for _ in 1..len {
25222 let raw = (next(&mut seed) % 97) as i64 - 48;
25223 timedeltas.push(match next(&mut seed) % 7 {
25224 0 => Scalar::Null(NullKind::Null),
25225 1 => Scalar::Timedelta64(i64::MIN),
25226 _ => Scalar::Timedelta64(raw),
25227 });
25228 }
25229 assert_reducers(case, "timedelta", timedeltas);
25230 }
25231 }
25232
25233 #[test]
25234 fn count_uses_nullable_int64_validity_without_scalar_materialization_aed6d() {
25235 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 3), (7, 1)]), 10);
25236 let col = Column::from_i64_values_with_validity((0_i64..10).collect(), validity);
25237
25238 assert_eq!(col.count(), 6);
25239 assert!(matches!(
25240 &col.values,
25241 ScalarValues::LazyNullableInt64 { .. }
25242 ));
25243 if let ScalarValues::LazyNullableInt64 { values, .. } = &col.values {
25244 assert!(values.get().is_none());
25245 }
25246 }
25247
25248 #[test]
25249 fn count_float64_raw_path_still_excludes_nan_aed6d() {
25250 let col = Column {
25251 dtype: DType::Float64,
25252 values: ScalarValues::lazy_all_valid_float64(vec![
25253 1.0,
25254 f64::NAN,
25255 f64::INFINITY,
25256 -0.0,
25257 ]),
25258 validity: ValidityMask::all_valid(4),
25259 data: None,
25260 };
25261
25262 assert_eq!(col.count(), 3);
25263 assert!(matches!(
25264 &col.values,
25265 ScalarValues::LazyAllValidFloat64 { .. }
25266 ));
25267 if let ScalarValues::LazyAllValidFloat64 { values, .. } = &col.values {
25268 assert!(values.get().is_none());
25269 }
25270 }
25271 }
25272
25273 mod where_mask {
25274 use fp_types::NullKind;
25275
25276 use super::*;
25277
25278 #[test]
25279 fn where_cond_keeps_true_positions() {
25280 let col =
25281 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
25282 .expect("col");
25283 let cond = Column::from_values(vec![
25284 Scalar::Bool(true),
25285 Scalar::Bool(false),
25286 Scalar::Bool(true),
25287 ])
25288 .expect("cond");
25289 let fill = Scalar::Int64(-1);
25290 let out = col.where_cond(&cond, &fill).expect("where");
25291 assert_eq!(col.r#where(&cond, &fill).expect("where"), out);
25292 assert_eq!(out.values()[0], Scalar::Int64(1));
25293 assert_eq!(out.values()[1], Scalar::Int64(-1));
25294 assert_eq!(out.values()[2], Scalar::Int64(3));
25295 }
25296
25297 #[test]
25298 fn mask_inverts_where_cond() {
25299 let col =
25300 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
25301 .expect("col");
25302 let cond = Column::from_values(vec![
25303 Scalar::Bool(true),
25304 Scalar::Bool(false),
25305 Scalar::Bool(true),
25306 ])
25307 .expect("cond");
25308 let fill = Scalar::Int64(0);
25309 let out = col.mask(&cond, &fill).expect("mask");
25310 assert_eq!(out.values()[0], Scalar::Int64(0));
25311 assert_eq!(out.values()[1], Scalar::Int64(2));
25312 assert_eq!(out.values()[2], Scalar::Int64(0));
25313 }
25314
25315 #[test]
25316 fn where_missing_cond_propagates_null() {
25317 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25318 let cond = Column::from_values(vec![Scalar::Bool(true), Scalar::Null(NullKind::NaN)])
25319 .expect("cond");
25320 let fill = Scalar::Int64(-1);
25321 let out = col.where_cond(&cond, &fill).expect("where");
25322 assert_eq!(out.values()[0], Scalar::Int64(1));
25323 assert!(out.values()[1].is_missing());
25324 }
25325
25326 #[test]
25327 fn where_rejects_non_bool_cond() {
25328 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25329 let cond = Column::from_values(vec![Scalar::Int64(1)]).expect("cond");
25330 let err = col.where_cond(&cond, &Scalar::Int64(0)).unwrap_err();
25331 assert!(matches!(err, crate::ColumnError::InvalidMaskType { .. }));
25332 }
25333
25334 #[test]
25335 fn equals_elementwise_matches_semantic_eq() {
25336 let a = Column::from_values(vec![
25337 Scalar::Int64(1),
25338 Scalar::Int64(2),
25339 Scalar::Null(NullKind::NaN),
25340 ])
25341 .expect("a");
25342 let b = Column::from_values(vec![
25343 Scalar::Int64(1),
25344 Scalar::Int64(3),
25345 Scalar::Null(NullKind::NaN),
25346 ])
25347 .expect("b");
25348 let r = a.equals(&b).expect("equals");
25349 assert_eq!(r.dtype(), DType::Bool);
25350 assert_eq!(r.values()[0], Scalar::Bool(true));
25351 assert_eq!(r.values()[1], Scalar::Bool(false));
25352 assert_eq!(r.values()[2], Scalar::Bool(false));
25354 }
25355
25356 #[test]
25357 fn equals_length_mismatch_errors() {
25358 let a = Column::from_values(vec![Scalar::Int64(1)]).expect("a");
25359 let b = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("b");
25360 assert!(a.equals(&b).is_err());
25361 }
25362
25363 #[test]
25364 fn dot_ignores_missing() {
25365 let a = Column::from_values(vec![
25366 Scalar::Float64(1.0),
25367 Scalar::Null(NullKind::NaN),
25368 Scalar::Float64(3.0),
25369 ])
25370 .expect("a");
25371 let b = Column::from_values(vec![
25372 Scalar::Float64(2.0),
25373 Scalar::Float64(4.0),
25374 Scalar::Float64(5.0),
25375 ])
25376 .expect("b");
25377 let r = a.dot(&b).expect("dot");
25378 assert!((r - 17.0).abs() < 1e-9);
25380 }
25381
25382 #[test]
25383 fn dot_non_numeric_errors() {
25384 let a = Column::from_values(vec![Scalar::Utf8("x".into())]).expect("a");
25385 let b = Column::from_values(vec![Scalar::Float64(1.0)]).expect("b");
25386 assert!(a.dot(&b).is_err());
25387 }
25388
25389 #[test]
25390 fn fillna_with_column_fills_missing_positions() {
25391 let a = Column::from_values(vec![
25392 Scalar::Int64(1),
25393 Scalar::Null(NullKind::NaN),
25394 Scalar::Int64(3),
25395 ])
25396 .expect("a");
25397 let b = Column::from_values(vec![
25398 Scalar::Int64(10),
25399 Scalar::Int64(20),
25400 Scalar::Int64(30),
25401 ])
25402 .expect("b");
25403 let r = a.fillna_with_column(&b).expect("fillna_with_column");
25404 assert_eq!(r.values()[0], Scalar::Int64(1));
25405 assert_eq!(r.values()[1], Scalar::Int64(20));
25406 assert_eq!(r.values()[2], Scalar::Int64(3));
25407 }
25408
25409 #[test]
25410 fn divmod_returns_quotient_and_remainder() {
25411 let a = Column::from_values(vec![
25412 Scalar::Float64(10.0),
25413 Scalar::Float64(7.0),
25414 Scalar::Float64(-5.0),
25415 ])
25416 .expect("a");
25417 let b = Column::from_values(vec![
25418 Scalar::Float64(3.0),
25419 Scalar::Float64(2.0),
25420 Scalar::Float64(3.0),
25421 ])
25422 .expect("b");
25423 let (q, r) = a.divmod(&b).expect("divmod");
25424 match (&q.values()[0], &r.values()[0]) {
25426 (Scalar::Float64(qv), Scalar::Float64(rv)) => {
25427 assert!((qv - 3.0).abs() < 1e-9);
25428 assert!((rv - 1.0).abs() < 1e-9);
25429 }
25430 other => unreachable!("unexpected {other:?}"),
25431 }
25432 match (&q.values()[1], &r.values()[1]) {
25434 (Scalar::Float64(qv), Scalar::Float64(rv)) => {
25435 assert!((qv - 3.0).abs() < 1e-9);
25436 assert!((rv - 1.0).abs() < 1e-9);
25437 }
25438 other => unreachable!("unexpected {other:?}"),
25439 }
25440 match (&q.values()[2], &r.values()[2]) {
25442 (Scalar::Float64(qv), Scalar::Float64(rv)) => {
25443 assert!((qv + 2.0).abs() < 1e-9);
25444 assert!((rv - 1.0).abs() < 1e-9);
25445 }
25446 other => unreachable!("unexpected {other:?}"),
25447 }
25448 }
25449
25450 #[test]
25451 fn divmod_zero_divisor_yields_null() {
25452 let a = Column::from_values(vec![Scalar::Float64(10.0)]).expect("a");
25453 let b = Column::from_values(vec![Scalar::Float64(0.0)]).expect("b");
25454 let (q, r) = a.divmod(&b).expect("divmod");
25455 assert!(q.values()[0].is_missing());
25456 assert!(r.values()[0].is_missing());
25457 }
25458
25459 #[test]
25460 fn divmod_infinite_operands_match_pandas_float_semantics() {
25461 let a = Column::from_values(vec![
25462 Scalar::Float64(f64::INFINITY),
25463 Scalar::Float64(f64::NEG_INFINITY),
25464 Scalar::Float64(5.0),
25465 Scalar::Float64(-5.0),
25466 Scalar::Float64(f64::INFINITY),
25467 ])
25468 .expect("a");
25469 let b = Column::from_values(vec![
25470 Scalar::Float64(2.0),
25471 Scalar::Float64(-2.0),
25472 Scalar::Float64(f64::INFINITY),
25473 Scalar::Float64(f64::INFINITY),
25474 Scalar::Float64(f64::INFINITY),
25475 ])
25476 .expect("b");
25477
25478 let (q, r) = a.divmod(&b).expect("divmod");
25479 assert!(matches!(q.values()[0], Scalar::Float64(v) if v.is_nan()));
25480 assert!(matches!(r.values()[0], Scalar::Float64(v) if v.is_nan()));
25481 assert!(matches!(q.values()[1], Scalar::Float64(v) if v.is_nan()));
25482 assert!(matches!(r.values()[1], Scalar::Float64(v) if v.is_nan()));
25483 assert_eq!(q.values()[2], Scalar::Float64(0.0));
25484 assert_eq!(r.values()[2], Scalar::Float64(5.0));
25485 assert_eq!(q.values()[3], Scalar::Float64(-1.0));
25486 assert_eq!(r.values()[3], Scalar::Float64(f64::INFINITY));
25487 assert!(matches!(q.values()[4], Scalar::Float64(v) if v.is_nan()));
25488 assert!(matches!(r.values()[4], Scalar::Float64(v) if v.is_nan()));
25489 }
25490
25491 #[test]
25492 fn where_cond_series_fills_from_other_column() {
25493 let col =
25494 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
25495 .expect("col");
25496 let cond = Column::from_values(vec![
25497 Scalar::Bool(true),
25498 Scalar::Bool(false),
25499 Scalar::Bool(true),
25500 ])
25501 .expect("cond");
25502 let other = Column::from_values(vec![
25503 Scalar::Int64(10),
25504 Scalar::Int64(20),
25505 Scalar::Int64(30),
25506 ])
25507 .expect("other");
25508 let out = col.where_cond_series(&cond, &other).expect("where_series");
25509 assert_eq!(out.values()[0], Scalar::Int64(1));
25510 assert_eq!(out.values()[1], Scalar::Int64(20));
25511 assert_eq!(out.values()[2], Scalar::Int64(3));
25512 }
25513
25514 #[test]
25515 fn mask_series_fills_from_other_column() {
25516 let col =
25517 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
25518 .expect("col");
25519 let cond = Column::from_values(vec![
25520 Scalar::Bool(true),
25521 Scalar::Bool(false),
25522 Scalar::Bool(true),
25523 ])
25524 .expect("cond");
25525 let other =
25526 Column::from_values(vec![Scalar::Int64(0), Scalar::Int64(0), Scalar::Int64(0)])
25527 .expect("other");
25528 let out = col.mask_series(&cond, &other).expect("mask_series");
25529 assert_eq!(out.values()[0], Scalar::Int64(0));
25530 assert_eq!(out.values()[1], Scalar::Int64(2));
25531 assert_eq!(out.values()[2], Scalar::Int64(0));
25532 }
25533
25534 #[test]
25535 fn where_cond_series_rejects_non_bool_cond() {
25536 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25537 let cond = Column::from_values(vec![Scalar::Int64(1)]).expect("cond");
25538 let other = Column::from_values(vec![Scalar::Int64(0)]).expect("other");
25539 let err = col.where_cond_series(&cond, &other).unwrap_err();
25540 assert!(matches!(err, crate::ColumnError::InvalidMaskType { .. }));
25541 }
25542
25543 #[test]
25544 fn replace_values_applies_first_match() {
25545 let col = Column::from_values(vec![
25546 Scalar::Int64(1),
25547 Scalar::Int64(2),
25548 Scalar::Int64(3),
25549 Scalar::Int64(2),
25550 ])
25551 .expect("col");
25552 let to_replace = vec![Scalar::Int64(2), Scalar::Int64(3)];
25553 let replacement = vec![Scalar::Int64(20), Scalar::Int64(30)];
25554 let out = col
25555 .replace_values(&to_replace, &replacement)
25556 .expect("replace");
25557 let alias = col
25558 .replace(&to_replace, &replacement)
25559 .expect("replace alias");
25560 assert_eq!(alias, out);
25561 assert_eq!(out.values()[0], Scalar::Int64(1));
25562 assert_eq!(out.values()[1], Scalar::Int64(20));
25563 assert_eq!(out.values()[2], Scalar::Int64(30));
25564 assert_eq!(out.values()[3], Scalar::Int64(20));
25565 }
25566
25567 #[test]
25568 fn replace_values_can_replace_nulls() {
25569 let col = Column::from_values(vec![
25570 Scalar::Int64(1),
25571 Scalar::Null(NullKind::NaN),
25572 Scalar::Int64(2),
25573 ])
25574 .expect("col");
25575 let to_replace = vec![Scalar::Null(NullKind::NaN)];
25576 let replacement = vec![Scalar::Int64(-1)];
25577 let out = col
25578 .replace_values(&to_replace, &replacement)
25579 .expect("replace");
25580 assert_eq!(out.values()[0], Scalar::Int64(1));
25581 assert_eq!(out.values()[1], Scalar::Int64(-1));
25582 assert_eq!(out.values()[2], Scalar::Int64(2));
25583 }
25584
25585 #[test]
25586 fn replace_values_length_mismatch_errors() {
25587 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25588 let err = col
25589 .replace_values(&[Scalar::Int64(1)], &[Scalar::Int64(2), Scalar::Int64(3)])
25590 .unwrap_err();
25591 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
25592 }
25593
25594 #[test]
25595 fn nonzero_returns_truthy_positions() {
25596 let col = Column::from_values(vec![
25597 Scalar::Int64(0),
25598 Scalar::Int64(5),
25599 Scalar::Null(NullKind::NaN),
25600 Scalar::Int64(-3),
25601 Scalar::Int64(0),
25602 ])
25603 .expect("col");
25604 assert_eq!(col.nonzero(), vec![1, 3]);
25605 }
25606
25607 #[test]
25608 fn nonzero_empty_column_is_empty() {
25609 let col = Column::from_values(Vec::<Scalar>::new()).expect("col");
25610 assert!(col.nonzero().is_empty());
25611 }
25612
25613 #[test]
25614 fn where_rejects_length_mismatch() {
25615 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25616 let cond = Column::from_values(vec![Scalar::Bool(true)]).expect("cond");
25617 let err = col.where_cond(&cond, &Scalar::Int64(0)).unwrap_err();
25618 assert!(matches!(err, crate::ColumnError::LengthMismatch { .. }));
25619 }
25620 }
25621
25622 mod nlargest_nsmallest {
25623 use fp_types::NullKind;
25624
25625 use super::*;
25626
25627 #[test]
25628 fn nlargest_returns_top_n_descending() {
25629 let col = Column::from_values(vec![
25630 Scalar::Int64(3),
25631 Scalar::Int64(1),
25632 Scalar::Int64(5),
25633 Scalar::Int64(2),
25634 Scalar::Int64(4),
25635 ])
25636 .expect("col");
25637 let top = col.nlargest(3).expect("nlargest");
25638 assert_eq!(top.len(), 3);
25639 assert_eq!(top.values()[0], Scalar::Int64(5));
25640 assert_eq!(top.values()[1], Scalar::Int64(4));
25641 assert_eq!(top.values()[2], Scalar::Int64(3));
25642 }
25643
25644 #[test]
25645 fn nsmallest_returns_bottom_n_ascending() {
25646 let col = Column::from_values(vec![
25647 Scalar::Int64(3),
25648 Scalar::Int64(1),
25649 Scalar::Int64(5),
25650 Scalar::Int64(2),
25651 Scalar::Int64(4),
25652 ])
25653 .expect("col");
25654 let bot = col.nsmallest(2).expect("nsmallest");
25655 assert_eq!(bot.len(), 2);
25656 assert_eq!(bot.values()[0], Scalar::Int64(1));
25657 assert_eq!(bot.values()[1], Scalar::Int64(2));
25658 }
25659
25660 #[test]
25661 fn nlargest_excludes_missing_when_n_fits() {
25662 let col = Column::from_values(vec![
25663 Scalar::Int64(5),
25664 Scalar::Null(NullKind::NaN),
25665 Scalar::Int64(3),
25666 Scalar::Int64(7),
25667 ])
25668 .expect("col");
25669 let top = col.nlargest(2).expect("nlargest");
25670 assert_eq!(top.len(), 2);
25671 assert_eq!(top.values()[0], Scalar::Int64(7));
25672 assert_eq!(top.values()[1], Scalar::Int64(5));
25673 }
25674
25675 #[test]
25676 fn nlargest_n_larger_than_length_clamps() {
25677 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25678 let top = col.nlargest(100).expect("nlargest");
25679 assert_eq!(top.len(), 2);
25680 }
25681
25682 #[test]
25683 fn nlargest_zero_is_empty_same_dtype() {
25684 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25685 let top = col.nlargest(0).expect("nlargest");
25686 assert!(top.is_empty());
25687 assert_eq!(top.dtype(), DType::Int64);
25688 }
25689 }
25690
25691 mod astype {
25692 use fp_types::NullKind;
25693
25694 use super::*;
25695
25696 #[test]
25697 fn astype_int_to_float_preserves_values() {
25698 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
25699 let out = col.astype(DType::Float64).expect("astype");
25700 assert_eq!(out.dtype(), DType::Float64);
25701 assert_eq!(out.values()[0], Scalar::Float64(1.0));
25702 assert_eq!(out.values()[1], Scalar::Float64(2.0));
25703 }
25704
25705 #[test]
25706 fn astype_same_dtype_is_noop_clone() {
25707 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25708 let out = col.astype(DType::Int64).expect("astype");
25709 assert_eq!(out.values(), col.values());
25710 }
25711
25712 #[test]
25713 fn astype_bool_to_int() {
25714 let col =
25715 Column::from_values(vec![Scalar::Bool(true), Scalar::Bool(false)]).expect("col");
25716 let out = col.astype(DType::Int64).expect("astype");
25717 assert_eq!(out.dtype(), DType::Int64);
25718 assert_eq!(out.values()[0], Scalar::Int64(1));
25719 assert_eq!(out.values()[1], Scalar::Int64(0));
25720 }
25721
25722 #[test]
25723 fn astype_to_utf8_uses_pandas_string_spellings() {
25724 let bool_col = Column::new(DType::Bool, vec![Scalar::Bool(true), Scalar::Bool(false)])
25725 .expect("bool col");
25726 let int_col = Column::new(DType::Int64, vec![Scalar::Int64(-7)]).expect("int col");
25727 let float_col = Column::new(
25728 DType::Float64,
25729 vec![Scalar::Float64(1.0), Scalar::Null(NullKind::NaN)],
25730 )
25731 .expect("float col");
25732
25733 let bool_out = bool_col.astype(DType::Utf8).expect("astype bool");
25734 let int_out = int_col.astype(DType::Utf8).expect("astype int");
25735 let float_out = float_col.astype(DType::Utf8).expect("astype float");
25736
25737 assert_eq!(bool_out.dtype(), DType::Utf8);
25738 assert_eq!(
25739 bool_out.values(),
25740 &[
25741 Scalar::Utf8("True".to_owned()),
25742 Scalar::Utf8("False".to_owned()),
25743 ]
25744 );
25745 assert_eq!(int_out.values(), &[Scalar::Utf8("-7".to_owned())]);
25746 assert_eq!(
25747 float_out.values(),
25748 &[
25749 Scalar::Utf8("1.0".to_owned()),
25750 Scalar::Utf8("nan".to_owned()),
25751 ]
25752 );
25753 }
25754
25755 #[test]
25756 fn astype_propagates_missing() {
25757 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Null(NullKind::NaN)])
25758 .expect("col");
25759 let out = col.astype(DType::Float64).expect("astype");
25760 assert_eq!(out.values()[0], Scalar::Float64(1.0));
25761 assert!(out.values()[1].is_missing());
25762 }
25763
25764 #[test]
25765 fn astype_finite_float_to_int_truncates_toward_zero() {
25766 let col = Column::from_values(vec![
25769 Scalar::Float64(1.5),
25770 Scalar::Float64(2.9),
25771 Scalar::Float64(-1.5),
25772 Scalar::Float64(-2.9),
25773 Scalar::Float64(0.4),
25774 ])
25775 .expect("col");
25776 let out = col.astype(DType::Int64).expect("truncating cast");
25777 assert_eq!(
25778 out.values(),
25779 &[
25780 Scalar::Int64(1),
25781 Scalar::Int64(2),
25782 Scalar::Int64(-1),
25783 Scalar::Int64(-2),
25784 Scalar::Int64(0),
25785 ]
25786 );
25787 let inf = Column::from_values(vec![Scalar::Float64(f64::INFINITY)]).expect("col");
25789 assert!(matches!(
25790 inf.astype(DType::Int64).unwrap_err(),
25791 crate::ColumnError::Type(_)
25792 ));
25793 }
25794
25795 #[test]
25796 fn new_int64_from_lossy_float_errors_unlike_astype() {
25797 let err = Column::new(DType::Int64, vec![Scalar::Float64(1.5)]).unwrap_err();
25801 assert!(matches!(
25802 err,
25803 crate::ColumnError::Type(fp_types::TypeError::LossyFloatToInt { .. })
25804 ));
25805 let ok = Column::new(DType::Int64, vec![Scalar::Float64(2.0)]).expect("integer float");
25807 assert_eq!(ok.values(), &[Scalar::Int64(2)]);
25808 }
25809 }
25810
25811 mod rank_searchsorted {
25812 use fp_types::NullKind;
25813
25814 use super::*;
25815
25816 #[test]
25817 fn rank_average_ties_get_midpoint() {
25818 let col = Column::from_values(vec![
25819 Scalar::Float64(10.0),
25820 Scalar::Float64(20.0),
25821 Scalar::Float64(20.0),
25822 Scalar::Float64(30.0),
25823 ])
25824 .expect("col");
25825 let r = col.rank("average", true).expect("rank");
25826 assert_eq!(r.values()[0], Scalar::Float64(1.0));
25827 assert_eq!(r.values()[1], Scalar::Float64(2.5));
25829 assert_eq!(r.values()[2], Scalar::Float64(2.5));
25830 assert_eq!(r.values()[3], Scalar::Float64(4.0));
25831 }
25832
25833 #[test]
25834 fn rank_min_assigns_lowest_tied_rank() {
25835 let col = Column::from_values(vec![
25836 Scalar::Int64(1),
25837 Scalar::Int64(2),
25838 Scalar::Int64(2),
25839 Scalar::Int64(3),
25840 ])
25841 .expect("col");
25842 let r = col.rank("min", true).expect("rank");
25843 assert_eq!(r.values()[1], Scalar::Float64(2.0));
25844 assert_eq!(r.values()[2], Scalar::Float64(2.0));
25845 assert_eq!(r.values()[3], Scalar::Float64(4.0));
25846 }
25847
25848 #[test]
25849 fn rank_max_assigns_highest_tied_rank() {
25850 let col = Column::from_values(vec![
25851 Scalar::Int64(1),
25852 Scalar::Int64(2),
25853 Scalar::Int64(2),
25854 Scalar::Int64(3),
25855 ])
25856 .expect("col");
25857 let r = col.rank("max", true).expect("rank");
25858 assert_eq!(r.values()[1], Scalar::Float64(3.0));
25859 assert_eq!(r.values()[2], Scalar::Float64(3.0));
25860 assert_eq!(r.values()[3], Scalar::Float64(4.0));
25861 }
25862
25863 #[test]
25864 fn rank_first_breaks_ties_by_appearance_order() {
25865 let col =
25866 Column::from_values(vec![Scalar::Int64(5), Scalar::Int64(3), Scalar::Int64(3)])
25867 .expect("col");
25868 let r = col.rank("first", true).expect("rank");
25869 assert_eq!(r.values()[0], Scalar::Float64(3.0));
25871 assert_eq!(r.values()[1], Scalar::Float64(1.0));
25872 assert_eq!(r.values()[2], Scalar::Float64(2.0));
25873 }
25874
25875 #[test]
25876 fn rank_dense_has_no_gaps() {
25877 let col = Column::from_values(vec![
25878 Scalar::Int64(1),
25879 Scalar::Int64(2),
25880 Scalar::Int64(2),
25881 Scalar::Int64(3),
25882 ])
25883 .expect("col");
25884 let r = col.rank("dense", true).expect("rank");
25885 assert_eq!(r.values()[0], Scalar::Float64(1.0));
25886 assert_eq!(r.values()[1], Scalar::Float64(2.0));
25887 assert_eq!(r.values()[2], Scalar::Float64(2.0));
25888 assert_eq!(r.values()[3], Scalar::Float64(3.0));
25889 }
25890
25891 #[test]
25892 fn rank_null_inputs_stay_null() {
25893 let col = Column::from_values(vec![
25894 Scalar::Float64(1.0),
25895 Scalar::Null(NullKind::NaN),
25896 Scalar::Float64(2.0),
25897 ])
25898 .expect("col");
25899 let r = col.rank("average", true).expect("rank");
25900 assert_eq!(r.values()[0], Scalar::Float64(1.0));
25901 assert!(r.values()[1].is_missing());
25902 assert_eq!(r.values()[2], Scalar::Float64(2.0));
25903 }
25904
25905 #[test]
25906 fn rank_descending_reverses_assignment() {
25907 let col =
25908 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
25909 .expect("col");
25910 let r = col.rank("min", false).expect("rank");
25911 assert_eq!(r.values()[0], Scalar::Float64(3.0));
25912 assert_eq!(r.values()[1], Scalar::Float64(2.0));
25913 assert_eq!(r.values()[2], Scalar::Float64(1.0));
25914 }
25915
25916 #[test]
25917 fn rank_invalid_method_errors() {
25918 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25919 let err = col.rank("bogus", true).unwrap_err();
25920 assert!(matches!(err, crate::ColumnError::Type(_)));
25921 }
25922
25923 #[test]
25924 fn searchsorted_left_finds_first_insertion() {
25925 let col = Column::from_values(vec![
25926 Scalar::Int64(1),
25927 Scalar::Int64(2),
25928 Scalar::Int64(2),
25929 Scalar::Int64(5),
25930 ])
25931 .expect("col");
25932 assert_eq!(col.searchsorted(&Scalar::Int64(2), "left").unwrap(), 1);
25933 assert_eq!(col.searchsorted(&Scalar::Int64(0), "left").unwrap(), 0);
25934 assert_eq!(col.searchsorted(&Scalar::Int64(6), "left").unwrap(), 4);
25935 }
25936
25937 #[test]
25938 fn searchsorted_right_finds_last_insertion() {
25939 let col = Column::from_values(vec![
25940 Scalar::Int64(1),
25941 Scalar::Int64(2),
25942 Scalar::Int64(2),
25943 Scalar::Int64(5),
25944 ])
25945 .expect("col");
25946 assert_eq!(col.searchsorted(&Scalar::Int64(2), "right").unwrap(), 3);
25947 }
25948
25949 #[test]
25950 fn searchsorted_rejects_invalid_side() {
25951 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25952 let err = col.searchsorted(&Scalar::Int64(0), "middle").unwrap_err();
25953 assert!(matches!(err, crate::ColumnError::Type(_)));
25954 }
25955
25956 #[test]
25957 fn searchsorted_rejects_missing_needle() {
25958 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
25959 let err = col
25960 .searchsorted(&Scalar::Null(NullKind::NaN), "left")
25961 .unwrap_err();
25962 assert!(matches!(err, crate::ColumnError::Type(_)));
25963 }
25964
25965 #[test]
25966 fn searchsorted_treats_trailing_nulls_as_greater() {
25967 let col = Column::from_values(vec![
25968 Scalar::Int64(1),
25969 Scalar::Int64(2),
25970 Scalar::Null(NullKind::NaN),
25971 ])
25972 .expect("col");
25973 assert_eq!(col.searchsorted(&Scalar::Int64(3), "left").unwrap(), 2);
25975 }
25976
25977 #[test]
25978 fn searchsorted_values_left_returns_positions_column() {
25979 let col = Column::from_values(vec![
25980 Scalar::Int64(1),
25981 Scalar::Int64(2),
25982 Scalar::Int64(2),
25983 Scalar::Int64(5),
25984 ])
25985 .expect("col");
25986 let positions = col
25987 .searchsorted_values(
25988 &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(6)],
25989 "left",
25990 )
25991 .expect("searchsorted");
25992 assert_eq!(positions.dtype(), DType::Int64);
25993 assert_eq!(
25994 positions.values(),
25995 &[Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(4)]
25996 );
25997 }
25998
25999 #[test]
26000 fn searchsorted_values_right_returns_positions_column() {
26001 let col = Column::from_values(vec![
26002 Scalar::Int64(1),
26003 Scalar::Int64(2),
26004 Scalar::Int64(2),
26005 Scalar::Int64(5),
26006 ])
26007 .expect("col");
26008 let positions = col
26009 .searchsorted_values(
26010 &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(6)],
26011 "right",
26012 )
26013 .expect("searchsorted");
26014 assert_eq!(
26015 positions.values(),
26016 &[Scalar::Int64(0), Scalar::Int64(3), Scalar::Int64(4)]
26017 );
26018 }
26019
26020 #[test]
26021 fn searchsorted_values_rejects_invalid_side() {
26022 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
26023 let err = col
26024 .searchsorted_values(&[Scalar::Int64(0)], "middle")
26025 .unwrap_err();
26026 assert!(matches!(err, crate::ColumnError::Type(_)));
26027 }
26028
26029 #[test]
26030 fn searchsorted_values_rejects_missing_needles() {
26031 let col = Column::from_values(vec![Scalar::Int64(1)]).expect("col");
26032 let err = col
26033 .searchsorted_values(&[Scalar::Null(NullKind::NaN)], "left")
26034 .unwrap_err();
26035 assert!(matches!(err, crate::ColumnError::Type(_)));
26036 }
26037
26038 #[test]
26039 fn searchsorted_with_sorter_uses_argsort_permutation() {
26040 let col = Column::from_values(vec![
26041 Scalar::Int64(5),
26042 Scalar::Int64(1),
26043 Scalar::Int64(2),
26044 Scalar::Int64(2),
26045 ])
26046 .expect("col");
26047 let sorter = col.argsort();
26048 assert_eq!(
26049 col.searchsorted_with_sorter(&Scalar::Int64(2), "left", &sorter)
26050 .unwrap(),
26051 1
26052 );
26053 assert_eq!(
26054 col.searchsorted_with_sorter(&Scalar::Int64(2), "right", &sorter)
26055 .unwrap(),
26056 3
26057 );
26058 assert_eq!(
26059 col.searchsorted_with_sorter(&Scalar::Int64(6), "left", &sorter)
26060 .unwrap(),
26061 4
26062 );
26063 }
26064
26065 #[test]
26066 fn searchsorted_values_with_sorter_returns_positions_column() {
26067 let col = Column::from_values(vec![
26068 Scalar::Int64(5),
26069 Scalar::Int64(1),
26070 Scalar::Int64(2),
26071 Scalar::Int64(2),
26072 ])
26073 .expect("col");
26074 let sorter = col.argsort();
26075 let positions = col
26076 .searchsorted_values_with_sorter(
26077 &[Scalar::Int64(0), Scalar::Int64(2), Scalar::Int64(6)],
26078 "left",
26079 &sorter,
26080 )
26081 .expect("searchsorted");
26082 assert_eq!(
26083 positions.values(),
26084 &[Scalar::Int64(0), Scalar::Int64(1), Scalar::Int64(4)]
26085 );
26086 }
26087
26088 #[test]
26089 fn searchsorted_with_sorter_rejects_length_mismatch() {
26090 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
26091 let err = col
26092 .searchsorted_with_sorter(&Scalar::Int64(1), "left", &[0])
26093 .unwrap_err();
26094 assert!(matches!(
26095 err,
26096 crate::ColumnError::LengthMismatch { left: 2, right: 1 }
26097 ));
26098 }
26099
26100 #[test]
26101 fn searchsorted_with_sorter_rejects_duplicate_or_oob_indices() {
26102 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2)]).expect("col");
26103 let duplicate = col
26104 .searchsorted_with_sorter(&Scalar::Int64(1), "left", &[0, 0])
26105 .unwrap_err();
26106 assert!(matches!(
26107 duplicate,
26108 crate::ColumnError::InvalidSorter { .. }
26109 ));
26110
26111 let out_of_bounds = col
26112 .searchsorted_with_sorter(&Scalar::Int64(1), "left", &[0, 2])
26113 .unwrap_err();
26114 assert!(matches!(
26115 out_of_bounds,
26116 crate::ColumnError::InvalidSorter { .. }
26117 ));
26118 }
26119 }
26120
26121 mod value_counts {
26122 use fp_types::NullKind;
26123
26124 use super::*;
26125
26126 #[test]
26127 fn value_counts_default_drops_missing_and_sorts_descending() {
26128 let col = Column::from_values(vec![
26129 Scalar::Int64(3),
26130 Scalar::Int64(1),
26131 Scalar::Null(NullKind::NaN),
26132 Scalar::Int64(3),
26133 Scalar::Int64(2),
26134 Scalar::Int64(1),
26135 Scalar::Int64(3),
26136 ])
26137 .expect("col");
26138
26139 let (values, counts) = col.value_counts().expect("value_counts");
26140 assert_eq!(
26141 values.values(),
26142 &[Scalar::Int64(3), Scalar::Int64(1), Scalar::Int64(2)]
26143 );
26144 assert_eq!(
26145 counts.values(),
26146 &[Scalar::Int64(3), Scalar::Int64(2), Scalar::Int64(1)]
26147 );
26148 }
26149
26150 #[test]
26151 fn value_counts_sort_false_preserves_first_seen_order() {
26152 let col = Column::from_values(vec![
26153 Scalar::Int64(2),
26154 Scalar::Int64(1),
26155 Scalar::Int64(2),
26156 Scalar::Int64(3),
26157 Scalar::Int64(1),
26158 ])
26159 .expect("col");
26160
26161 let (values, counts) = col
26162 .value_counts_with_options(false, false, false, true)
26163 .expect("value_counts");
26164 assert_eq!(
26165 values.values(),
26166 &[Scalar::Int64(2), Scalar::Int64(1), Scalar::Int64(3)]
26167 );
26168 assert_eq!(
26169 counts.values(),
26170 &[Scalar::Int64(2), Scalar::Int64(2), Scalar::Int64(1)]
26171 );
26172 }
26173
26174 #[test]
26175 fn value_counts_dropna_false_includes_missing_bucket() {
26176 let col = Column::from_values(vec![
26177 Scalar::Utf8("a".into()),
26178 Scalar::Null(NullKind::NaN),
26179 Scalar::Utf8("a".into()),
26180 Scalar::Null(NullKind::Null),
26181 ])
26182 .expect("col");
26183
26184 let (values, counts) = col
26185 .value_counts_with_options(false, true, false, false)
26186 .expect("value_counts");
26187 assert_eq!(values.values()[0], Scalar::Utf8("a".into()));
26188 assert!(values.values()[1].is_missing());
26189 assert_eq!(counts.values(), &[Scalar::Int64(2), Scalar::Int64(2)]);
26190 }
26191
26192 #[test]
26193 fn value_counts_normalize_uses_returned_total() {
26194 let col = Column::from_values(vec![
26195 Scalar::Float64(1.0),
26196 Scalar::Float64(2.0),
26197 Scalar::Float64(1.0),
26198 Scalar::Null(NullKind::NaN),
26199 ])
26200 .expect("col");
26201
26202 let (values, counts) = col
26203 .value_counts_with_options(true, true, false, true)
26204 .expect("value_counts");
26205 assert_eq!(
26206 values.values(),
26207 &[Scalar::Float64(1.0), Scalar::Float64(2.0)]
26208 );
26209 assert_eq!(counts.dtype(), DType::Float64);
26210 assert_eq!(
26211 counts.values(),
26212 &[Scalar::Float64(2.0 / 3.0), Scalar::Float64(1.0 / 3.0)]
26213 );
26214 }
26215
26216 #[test]
26217 fn python_mod_f64_handles_infinity_divisor() {
26218 use crate::python_mod_f64;
26219
26220 assert_eq!(python_mod_f64(5.0, f64::INFINITY), 5.0);
26221 assert_eq!(python_mod_f64(-5.0, f64::INFINITY), f64::INFINITY);
26222 assert_eq!(python_mod_f64(5.0, f64::NEG_INFINITY), f64::NEG_INFINITY);
26223 assert_eq!(python_mod_f64(-5.0, f64::NEG_INFINITY), -5.0);
26224 assert_eq!(python_mod_f64(0.0, f64::INFINITY), 0.0);
26225 assert!(python_mod_f64(0.0, f64::NEG_INFINITY).is_sign_negative());
26226 assert_eq!(python_mod_f64(-0.0, f64::INFINITY), 0.0);
26227 assert_eq!(python_mod_f64(-0.0, f64::NEG_INFINITY), -0.0);
26228 assert!(python_mod_f64(f64::NAN, f64::INFINITY).is_nan());
26229 assert!(python_mod_f64(f64::NAN, f64::NEG_INFINITY).is_nan());
26230 assert!(python_mod_f64(f64::INFINITY, f64::INFINITY).is_nan());
26231 assert!(python_mod_f64(f64::NEG_INFINITY, f64::NEG_INFINITY).is_nan());
26232 }
26233
26234 #[test]
26235 fn python_floor_div_f64_handles_infinite_operands() {
26236 use crate::python_floor_div_f64;
26237
26238 assert_eq!(python_floor_div_f64(5.0, f64::INFINITY), 0.0);
26239 assert_eq!(python_floor_div_f64(-5.0, f64::INFINITY), -1.0);
26240 assert_eq!(python_floor_div_f64(5.0, f64::NEG_INFINITY), -1.0);
26241 assert_eq!(python_floor_div_f64(-5.0, f64::NEG_INFINITY), 0.0);
26242 assert_eq!(python_floor_div_f64(0.0, f64::INFINITY), 0.0);
26243 assert!(python_floor_div_f64(-0.0, f64::INFINITY).is_sign_negative());
26244 assert!(python_floor_div_f64(0.0, f64::NEG_INFINITY).is_sign_negative());
26245 assert_eq!(python_floor_div_f64(-0.0, f64::NEG_INFINITY), 0.0);
26246 assert!(python_floor_div_f64(f64::INFINITY, 2.0).is_nan());
26247 assert!(python_floor_div_f64(f64::NEG_INFINITY, -2.0).is_nan());
26248 assert!(python_floor_div_f64(f64::INFINITY, f64::INFINITY).is_nan());
26249 }
26250
26251 #[test]
26252 fn histogram_counts_values_in_bins() {
26253 let col = Column::from_values(vec![
26254 Scalar::Float64(0.5),
26255 Scalar::Float64(1.5),
26256 Scalar::Float64(2.5),
26257 Scalar::Float64(1.2),
26258 Scalar::Float64(2.8),
26259 ])
26260 .unwrap();
26261 let edges = vec![0.0, 1.0, 2.0, 3.0];
26262 let counts = col.histogram(&edges).unwrap();
26263 assert_eq!(
26264 counts.values(),
26265 &[
26266 Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(2), ]
26270 );
26271 }
26272
26273 #[test]
26274 fn histogram_auto_creates_bins() {
26275 let col = Column::from_values(vec![
26276 Scalar::Float64(1.0),
26277 Scalar::Float64(2.0),
26278 Scalar::Float64(3.0),
26279 Scalar::Float64(4.0),
26280 ])
26281 .unwrap();
26282 let (counts, edges) = col.histogram_auto(3).unwrap();
26283 assert_eq!(counts.len(), 3);
26284 assert_eq!(edges.len(), 4);
26285 assert!((edges[0] - 1.0).abs() < 1e-10);
26286 assert!((edges[3] - 4.0).abs() < 1e-10);
26287 }
26288
26289 #[test]
26290 fn histogram_auto_constant_values_extends_range() {
26291 let col = Column::from_values(vec![
26292 Scalar::Float64(5.0),
26293 Scalar::Float64(5.0),
26294 Scalar::Float64(5.0),
26295 ])
26296 .unwrap();
26297 let (counts, edges) = col.histogram_auto(2).unwrap();
26298 assert_eq!(counts.len(), 2);
26299 assert!(edges[0] < 5.0);
26300 assert!(edges[2] > 5.0);
26301 }
26302
26303 #[test]
26304 fn hanning_window_shape() {
26305 let win = Column::hanning(5).unwrap();
26306 assert_eq!(win.len(), 5);
26307 assert!((win.values()[0].to_f64().unwrap()).abs() < 1e-10);
26309 assert!((win.values()[4].to_f64().unwrap()).abs() < 1e-10);
26310 assert!((win.values()[2].to_f64().unwrap() - 1.0).abs() < 1e-10);
26312 }
26313
26314 #[test]
26315 fn hamming_window_shape() {
26316 let win = Column::hamming(5).unwrap();
26317 assert_eq!(win.len(), 5);
26318 let v0 = win.values()[0].to_f64().unwrap();
26320 assert!(v0 > 0.07 && v0 < 0.09);
26321 }
26322
26323 #[test]
26324 fn bartlett_window_triangular() {
26325 let win = Column::bartlett(5).unwrap();
26326 assert_eq!(win.len(), 5);
26327 assert!((win.values()[0].to_f64().unwrap()).abs() < 1e-10);
26329 assert!((win.values()[4].to_f64().unwrap()).abs() < 1e-10);
26330 assert!((win.values()[2].to_f64().unwrap() - 1.0).abs() < 1e-10);
26332 }
26333
26334 #[test]
26335 fn convolve_full_mode() {
26336 let a = Column::from_values(vec![
26337 Scalar::Float64(1.0),
26338 Scalar::Float64(2.0),
26339 Scalar::Float64(3.0),
26340 ])
26341 .unwrap();
26342 let v = Column::from_values(vec![Scalar::Float64(1.0), Scalar::Float64(1.0)]).unwrap();
26343 let result = a.convolve(&v, "full").unwrap();
26344 assert_eq!(result.len(), 4);
26346 assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26347 assert!((result.values()[1].to_f64().unwrap() - 3.0).abs() < 1e-10);
26348 assert!((result.values()[2].to_f64().unwrap() - 5.0).abs() < 1e-10);
26349 assert!((result.values()[3].to_f64().unwrap() - 3.0).abs() < 1e-10);
26350 }
26351
26352 #[test]
26353 fn geomspace_creates_geometric_progression() {
26354 let col = Column::geomspace(1.0, 1000.0, 4).unwrap();
26355 assert_eq!(col.len(), 4);
26356 assert!((col.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26357 assert!((col.values()[1].to_f64().unwrap() - 10.0).abs() < 1e-10);
26358 assert!((col.values()[2].to_f64().unwrap() - 100.0).abs() < 1e-10);
26359 assert!((col.values()[3].to_f64().unwrap() - 1000.0).abs() < 1e-10);
26360 }
26361
26362 #[test]
26363 fn nan_to_num_replaces_special_values() {
26364 let col = Column::from_values(vec![
26365 Scalar::Float64(1.0),
26366 Scalar::Float64(f64::NAN),
26367 Scalar::Float64(f64::INFINITY),
26368 Scalar::Float64(f64::NEG_INFINITY),
26369 ])
26370 .unwrap();
26371 let result = col.nan_to_num().unwrap();
26372 assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26373 assert!((result.values()[1].to_f64().unwrap() - 0.0).abs() < 1e-10);
26374 assert_eq!(result.values()[2].to_f64().unwrap(), f64::MAX);
26375 assert_eq!(result.values()[3].to_f64().unwrap(), f64::MIN);
26376 }
26377
26378 #[test]
26379 fn nan_to_num_with_values_matches_replacement_oracle_am707() {
26380 fn next(seed: &mut u64) -> u64 {
26383 *seed = seed
26384 .wrapping_mul(3935559000370003845)
26385 .wrapping_add(2691343689449507681);
26386 *seed
26387 }
26388
26389 fn replacement(seed: &mut u64) -> f64 {
26390 let raw = (next(seed) % 200_001) as i64 - 100_000;
26391 raw as f64 / 23.0
26392 }
26393
26394 fn expected_value(value: &Scalar, nan: f64, posinf: f64, neginf: f64) -> f64 {
26395 match value {
26396 Scalar::Float64(v) if v.is_nan() => nan,
26397 Scalar::Float64(v) if *v == f64::INFINITY => posinf,
26398 Scalar::Float64(v) if *v == f64::NEG_INFINITY => neginf,
26399 Scalar::Float64(v) => *v,
26400 Scalar::Null(_) => nan,
26401 other => panic!("unexpected value in oracle: {other:?}"),
26402 }
26403 }
26404
26405 let mut seed = 0xa070_7a7e_0f11_ca1e_u64;
26406 for case in 0..260 {
26407 let nan = replacement(&mut seed);
26408 let posinf = replacement(&mut seed);
26409 let neginf = replacement(&mut seed);
26410 let len = (next(&mut seed) % 67 + 1) as usize;
26411 let mut values = Vec::with_capacity(len);
26412
26413 for _ in 0..len {
26414 let selector = next(&mut seed) % 13;
26415 let raw = (next(&mut seed) % 1_000_001) as i64 - 500_000;
26416 let frac = (next(&mut seed) % 10_000) as f64 / 10_000.0;
26417 values.push(match selector {
26418 0 => Scalar::Null(NullKind::NaN),
26419 1 => Scalar::Float64(f64::NAN),
26420 2 => Scalar::Float64(f64::INFINITY),
26421 3 => Scalar::Float64(f64::NEG_INFINITY),
26422 _ => Scalar::Float64(raw as f64 / 31.0 + frac),
26423 });
26424 }
26425
26426 let input = Column::from_values(values.clone()).expect("column");
26427 let result = input
26428 .nan_to_num_with_values(nan, posinf, neginf)
26429 .expect("nan_to_num_with_values");
26430 assert_eq!(result.dtype(), DType::Float64);
26431 assert_eq!(result.values().len(), values.len());
26432
26433 for (pos, (before, after)) in values.iter().zip(result.values()).enumerate() {
26434 let expected = expected_value(before, nan, posinf, neginf);
26435 match after {
26436 Scalar::Float64(got) => assert_eq!(
26437 *got, expected,
26438 "case={case} pos={pos}: got {got}, expected {expected}"
26439 ),
26440 other => panic!("case={case} pos={pos}: expected Float64, got {other:?}"),
26441 }
26442 }
26443 }
26444 }
26445
26446 #[test]
26447 fn rint_rounds_to_nearest_even() {
26448 let col = Column::from_values(vec![
26449 Scalar::Float64(0.5),
26450 Scalar::Float64(1.5),
26451 Scalar::Float64(2.5),
26452 Scalar::Float64(3.5),
26453 ])
26454 .unwrap();
26455 let result = col.rint().unwrap();
26456 assert!((result.values()[0].to_f64().unwrap() - 0.0).abs() < 1e-10);
26458 assert!((result.values()[1].to_f64().unwrap() - 2.0).abs() < 1e-10);
26459 assert!((result.values()[2].to_f64().unwrap() - 2.0).abs() < 1e-10);
26460 assert!((result.values()[3].to_f64().unwrap() - 4.0).abs() < 1e-10);
26461 }
26462
26463 #[test]
26464 fn ldexp_multiplies_by_power_of_two() {
26465 let col = Column::from_values(vec![
26466 Scalar::Float64(1.0),
26467 Scalar::Float64(2.0),
26468 Scalar::Float64(0.5),
26469 ])
26470 .unwrap();
26471 let result = col.ldexp(3).unwrap(); assert!((result.values()[0].to_f64().unwrap() - 8.0).abs() < 1e-10);
26473 assert!((result.values()[1].to_f64().unwrap() - 16.0).abs() < 1e-10);
26474 assert!((result.values()[2].to_f64().unwrap() - 4.0).abs() < 1e-10);
26475 }
26476
26477 #[test]
26478 fn modf_splits_integer_and_fraction() {
26479 let col = Column::from_values(vec![
26480 Scalar::Float64(3.5),
26481 Scalar::Float64(-2.25),
26482 Scalar::Float64(1.0),
26483 ])
26484 .unwrap();
26485 let (frac, int) = col.modf().unwrap();
26486 assert!((frac.values()[0].to_f64().unwrap() - 0.5).abs() < 1e-10);
26487 assert!((int.values()[0].to_f64().unwrap() - 3.0).abs() < 1e-10);
26488 assert!((frac.values()[1].to_f64().unwrap() - (-0.25)).abs() < 1e-10);
26489 assert!((int.values()[1].to_f64().unwrap() - (-2.0)).abs() < 1e-10);
26490 assert!((frac.values()[2].to_f64().unwrap() - 0.0).abs() < 1e-10);
26491 assert!((int.values()[2].to_f64().unwrap() - 1.0).abs() < 1e-10);
26492 }
26493
26494 #[test]
26495 fn spacing_returns_ulp() {
26496 let col = Column::from_values(vec![
26497 Scalar::Float64(1.0),
26498 Scalar::Float64(-1.0),
26499 Scalar::Float64(0.0),
26500 ])
26501 .unwrap();
26502 let result = col.spacing().unwrap();
26503 let s1 = result.values()[0].to_f64().unwrap();
26505 assert!(s1 > 0.0 && s1 < 1e-15);
26506 let s_neg1 = result.values()[1].to_f64().unwrap();
26508 assert!((s1 - s_neg1).abs() < 1e-20);
26509 assert_eq!(result.values()[2].to_f64().unwrap(), f64::from_bits(1));
26511 }
26512
26513 #[test]
26514 fn frexp_decomposes_floats() {
26515 let col = Column::from_values(vec![
26516 Scalar::Float64(4.0),
26517 Scalar::Float64(0.5),
26518 Scalar::Float64(-8.0),
26519 Scalar::Float64(0.0),
26520 ])
26521 .unwrap();
26522 let (mant, exp) = col.frexp().unwrap();
26523 assert!((mant.values()[0].to_f64().unwrap() - 0.5).abs() < 1e-10);
26525 assert_eq!(exp.values()[0].to_i64().unwrap(), 3);
26526 assert!((mant.values()[1].to_f64().unwrap() - 0.5).abs() < 1e-10);
26528 assert_eq!(exp.values()[1].to_i64().unwrap(), 0);
26529 assert!((mant.values()[2].to_f64().unwrap() - (-0.5)).abs() < 1e-10);
26531 assert_eq!(exp.values()[2].to_i64().unwrap(), 4);
26532 assert!((mant.values()[3].to_f64().unwrap() - 0.0).abs() < 1e-10);
26534 assert_eq!(exp.values()[3].to_i64().unwrap(), 0);
26535 }
26536
26537 #[test]
26538 fn nextafter_returns_adjacent_floats() {
26539 let col = Column::from_values(vec![
26540 Scalar::Float64(0.0),
26541 Scalar::Float64(1.0),
26542 Scalar::Float64(1.0),
26543 ])
26544 .unwrap();
26545 let toward = Column::from_values(vec![
26546 Scalar::Float64(1.0),
26547 Scalar::Float64(2.0),
26548 Scalar::Float64(0.0),
26549 ])
26550 .unwrap();
26551 let result = col.nextafter(&toward).unwrap();
26552 assert_eq!(result.values()[0].to_f64().unwrap(), f64::from_bits(1));
26554 let r1 = result.values()[1].to_f64().unwrap();
26556 assert!(r1 > 1.0 && r1 < 1.0 + 1e-15);
26557 let r2 = result.values()[2].to_f64().unwrap();
26559 assert!(r2 < 1.0 && r2 > 1.0 - 1e-15);
26560 }
26561
26562 #[test]
26563 fn isneginf_isposinf_detect_infinities() {
26564 let col = Column::from_values(vec![
26565 Scalar::Float64(f64::NEG_INFINITY),
26566 Scalar::Float64(f64::INFINITY),
26567 Scalar::Float64(1.0),
26568 Scalar::Float64(f64::NAN),
26569 ])
26570 .unwrap();
26571 let neginf = col.isneginf().unwrap();
26572 let posinf = col.isposinf().unwrap();
26573 assert_eq!(neginf.values()[0], Scalar::Bool(true));
26574 assert_eq!(neginf.values()[1], Scalar::Bool(false));
26575 assert_eq!(neginf.values()[2], Scalar::Bool(false));
26576 assert_eq!(neginf.values()[3], Scalar::Bool(false));
26577 assert_eq!(posinf.values()[0], Scalar::Bool(false));
26578 assert_eq!(posinf.values()[1], Scalar::Bool(true));
26579 assert_eq!(posinf.values()[2], Scalar::Bool(false));
26580 assert_eq!(posinf.values()[3], Scalar::Bool(false));
26581 }
26582
26583 #[test]
26584 fn exp2_computes_power_of_two() {
26585 let col = Column::from_values(vec![
26586 Scalar::Float64(0.0),
26587 Scalar::Float64(1.0),
26588 Scalar::Float64(3.0),
26589 Scalar::Float64(-1.0),
26590 ])
26591 .unwrap();
26592 let result = col.exp2().unwrap();
26593 assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26594 assert!((result.values()[1].to_f64().unwrap() - 2.0).abs() < 1e-10);
26595 assert!((result.values()[2].to_f64().unwrap() - 8.0).abs() < 1e-10);
26596 assert!((result.values()[3].to_f64().unwrap() - 0.5).abs() < 1e-10);
26597 }
26598
26599 #[test]
26600 fn sinc_computes_sinc_function() {
26601 let col = Column::from_values(vec![
26602 Scalar::Float64(0.0),
26603 Scalar::Float64(1.0),
26604 Scalar::Float64(0.5),
26605 ])
26606 .unwrap();
26607 let result = col.sinc().unwrap();
26608 assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26610 assert!(result.values()[1].to_f64().unwrap().abs() < 1e-10);
26612 let expected = 2.0 / std::f64::consts::PI;
26614 assert!((result.values()[2].to_f64().unwrap() - expected).abs() < 1e-10);
26615 }
26616
26617 #[test]
26618 fn logaddexp_computes_stable_log_sum() {
26619 let x = Column::from_values(vec![
26620 Scalar::Float64(0.0),
26621 Scalar::Float64(1.0),
26622 Scalar::Float64(-1000.0),
26623 ])
26624 .unwrap();
26625 let y = Column::from_values(vec![
26626 Scalar::Float64(0.0),
26627 Scalar::Float64(2.0),
26628 Scalar::Float64(-1000.0),
26629 ])
26630 .unwrap();
26631 let result = x.logaddexp(&y).unwrap();
26632 assert!((result.values()[0].to_f64().unwrap() - std::f64::consts::LN_2).abs() < 1e-10);
26634 let expected1 = (1.0_f64.exp() + 2.0_f64.exp()).ln();
26636 assert!((result.values()[1].to_f64().unwrap() - expected1).abs() < 1e-10);
26637 let expected2 = -1000.0 + std::f64::consts::LN_2;
26639 assert!((result.values()[2].to_f64().unwrap() - expected2).abs() < 1e-8);
26640 }
26641
26642 #[test]
26643 fn logaddexp2_computes_stable_log2_sum() {
26644 let x = Column::from_values(vec![Scalar::Float64(0.0), Scalar::Float64(1.0)]).unwrap();
26645 let y = Column::from_values(vec![Scalar::Float64(0.0), Scalar::Float64(1.0)]).unwrap();
26646 let result = x.logaddexp2(&y).unwrap();
26647 assert!((result.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26649 assert!((result.values()[1].to_f64().unwrap() - 2.0).abs() < 1e-10);
26651 }
26652
26653 #[test]
26654 fn roll_shifts_elements_circularly() {
26655 let col = Column::from_values(vec![
26656 Scalar::Int64(1),
26657 Scalar::Int64(2),
26658 Scalar::Int64(3),
26659 Scalar::Int64(4),
26660 Scalar::Int64(5),
26661 ])
26662 .unwrap();
26663 let r1 = col.roll(2).unwrap();
26665 assert_eq!(r1.values()[0].to_i64().unwrap(), 4);
26666 assert_eq!(r1.values()[1].to_i64().unwrap(), 5);
26667 assert_eq!(r1.values()[2].to_i64().unwrap(), 1);
26668 let r2 = col.roll(-2).unwrap();
26670 assert_eq!(r2.values()[0].to_i64().unwrap(), 3);
26671 assert_eq!(r2.values()[1].to_i64().unwrap(), 4);
26672 assert_eq!(r2.values()[2].to_i64().unwrap(), 5);
26673 let r3 = col.roll(0).unwrap();
26675 assert_eq!(r3.values()[0].to_i64().unwrap(), 1);
26676 let r4 = col.roll(5).unwrap();
26677 assert_eq!(r4.values()[0].to_i64().unwrap(), 1);
26678 }
26679
26680 #[test]
26681 fn trim_zeros_removes_leading_trailing() {
26682 let col = Column::from_values(vec![
26683 Scalar::Int64(0),
26684 Scalar::Int64(0),
26685 Scalar::Int64(1),
26686 Scalar::Int64(2),
26687 Scalar::Int64(0),
26688 ])
26689 .unwrap();
26690 let r1 = col.trim_zeros("fb").unwrap();
26692 assert_eq!(r1.len(), 2);
26693 assert_eq!(r1.values()[0].to_i64().unwrap(), 1);
26694 assert_eq!(r1.values()[1].to_i64().unwrap(), 2);
26695 let r2 = col.trim_zeros("f").unwrap();
26697 assert_eq!(r2.len(), 3);
26698 assert_eq!(r2.values()[0].to_i64().unwrap(), 1);
26699 let r3 = col.trim_zeros("b").unwrap();
26701 assert_eq!(r3.len(), 4);
26702 assert_eq!(r3.values()[3].to_i64().unwrap(), 2);
26703 }
26704
26705 #[test]
26706 fn around_rounds_to_decimals() {
26707 let col = Column::from_values(vec![
26708 Scalar::Float64(1.234),
26709 Scalar::Float64(5.678),
26710 Scalar::Float64(3.5),
26711 ])
26712 .unwrap();
26713 let r1 = col.around(2).unwrap();
26715 assert!((r1.values()[0].to_f64().unwrap() - 1.23).abs() < 1e-10);
26716 assert!((r1.values()[1].to_f64().unwrap() - 5.68).abs() < 1e-10);
26717 assert!((r1.values()[2].to_f64().unwrap() - 3.5).abs() < 1e-10);
26718 let r2 = col.around(0).unwrap();
26720 assert!((r2.values()[0].to_f64().unwrap() - 1.0).abs() < 1e-10);
26721 assert!((r2.values()[1].to_f64().unwrap() - 6.0).abs() < 1e-10);
26722 let col2 = Column::from_values(vec![
26724 Scalar::Float64(15.0),
26725 Scalar::Float64(24.0),
26726 Scalar::Float64(35.0),
26727 ])
26728 .unwrap();
26729 let r3 = col2.around(-1).unwrap();
26730 assert!((r3.values()[0].to_f64().unwrap() - 20.0).abs() < 1e-10);
26731 assert!((r3.values()[1].to_f64().unwrap() - 20.0).abs() < 1e-10);
26732 assert!((r3.values()[2].to_f64().unwrap() - 40.0).abs() < 1e-10);
26733 }
26734
26735 #[test]
26736 fn around_uses_numpy_half_even_ties() {
26737 let col = Column::from_values(vec![
26741 Scalar::Float64(0.5),
26742 Scalar::Float64(1.5),
26743 Scalar::Float64(2.5),
26744 Scalar::Float64(3.5),
26745 Scalar::Float64(-2.5),
26746 ])
26747 .unwrap();
26748 let r = col.around(0).unwrap();
26749 let got: Vec<f64> = r.values().iter().map(|v| v.to_f64().unwrap()).collect();
26750 assert_eq!(got, vec![0.0, 2.0, 2.0, 4.0, -2.0]);
26751
26752 let tens = Column::from_values(vec![
26754 Scalar::Float64(15.0),
26755 Scalar::Float64(25.0),
26756 Scalar::Float64(35.0),
26757 ])
26758 .unwrap();
26759 let rt = tens.around(-1).unwrap();
26760 let gott: Vec<f64> = rt.values().iter().map(|v| v.to_f64().unwrap()).collect();
26761 assert_eq!(gott, vec![20.0, 20.0, 40.0]);
26762
26763 assert_eq!(
26765 col.around(0).unwrap().values(),
26766 col.round(0).unwrap().values()
26767 );
26768 }
26769
26770 #[test]
26771 fn unwrap_removes_phase_discontinuities() {
26772 use std::f64::consts::PI;
26773 let col = Column::from_values(vec![
26774 Scalar::Float64(0.0),
26775 Scalar::Float64(PI * 0.9),
26776 Scalar::Float64(-PI * 0.9), Scalar::Float64(0.0),
26778 ])
26779 .unwrap();
26780 let result = col.unwrap(None).unwrap();
26781 assert!((result.values()[0].to_f64().unwrap() - 0.0).abs() < 1e-10);
26783 assert!((result.values()[1].to_f64().unwrap() - PI * 0.9).abs() < 1e-10);
26785 let v2 = result.values()[2].to_f64().unwrap();
26787 let v1 = result.values()[1].to_f64().unwrap();
26788 assert!((v2 - v1).abs() < PI); }
26790 }
26791
26792 #[test]
26795 fn column_has_nulls_detects_missing_values() {
26796 let col_with_null = Column::from_values(vec![
26797 Scalar::Int64(1),
26798 Scalar::Null(NullKind::Null),
26799 Scalar::Int64(3),
26800 ])
26801 .unwrap();
26802 assert!(col_with_null.has_nulls());
26803
26804 let col_no_null =
26805 Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
26806 .unwrap();
26807 assert!(!col_no_null.has_nulls());
26808 }
26809
26810 #[test]
26811 fn column_promote_to_nullable_upgrades_dtype() {
26812 let col = Column::new(
26813 DType::Int64,
26814 vec![
26815 Scalar::Int64(1),
26816 Scalar::Null(NullKind::Null),
26817 Scalar::Int64(3),
26818 ],
26819 )
26820 .unwrap();
26821 assert_eq!(col.dtype(), DType::Int64);
26822 assert!(col.has_nulls());
26823
26824 let promoted = col.promote_to_nullable();
26825 assert_eq!(promoted.dtype(), DType::Int64Nullable);
26826 assert_eq!(promoted.len(), 3);
26827 }
26828
26829 #[test]
26830 fn column_promote_to_nullable_noop_without_nulls() {
26831 let col = Column::from_values(vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)])
26832 .unwrap();
26833 let promoted = col.promote_to_nullable();
26834 assert_eq!(promoted.dtype(), DType::Int64);
26836 }
26837
26838 #[test]
26839 fn column_with_dtype_changes_metadata() {
26840 let col = Column::new(DType::Int64, vec![Scalar::Int64(42)]).unwrap();
26841 let changed = col.with_dtype(DType::Int64Nullable);
26842 assert_eq!(changed.dtype(), DType::Int64Nullable);
26843 assert_eq!(changed.values()[0], Scalar::Int64(42));
26844 }
26845
26846 #[test]
26847 fn nullable_int64_from_scalars_preserves_storage() {
26848 use super::ColumnData;
26849 let values = vec![Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)];
26850 let data = ColumnData::from_scalars(&values, DType::Int64Nullable);
26851 assert!(matches!(&data, ColumnData::Int64(_)));
26852 if let ColumnData::Int64(arr) = data {
26853 assert_eq!(arr.as_ref(), [1, 2, 3]);
26854 }
26855 }
26856
26857 #[test]
26858 fn scalar_int64_cache_arc_provenance_is_shared() {
26859 let col = Column::new(
26860 DType::Int64,
26861 vec![Scalar::Int64(10), Scalar::Int64(20), Scalar::Int64(30)],
26862 )
26863 .unwrap();
26864 assert!(matches!(&col.data, Some(ColumnData::Int64(_))));
26865 let Some(ColumnData::Int64(cached)) = &col.data else {
26866 return;
26867 };
26868 let source = col.as_i64_arc().expect("all-valid Int64 source");
26869 assert!(Arc::ptr_eq(cached, &source));
26870
26871 let cloned = col.clone();
26872 assert!(matches!(
26873 &cloned.values,
26874 ScalarValues::LazyAllValidInt64 { .. }
26875 ));
26876 let ScalarValues::LazyAllValidInt64 { data, .. } = &cloned.values else {
26877 return;
26878 };
26879 assert!(Arc::ptr_eq(cached, data));
26880 }
26881
26882 #[test]
26883 fn int64_dense_cycle_witness_is_exact_and_cached_uza0466() {
26884 let col = Column::new(
26885 DType::Int64,
26886 vec![
26887 Scalar::Int64(5),
26888 Scalar::Int64(6),
26889 Scalar::Int64(7),
26890 Scalar::Int64(5),
26891 Scalar::Int64(6),
26892 Scalar::Int64(7),
26893 Scalar::Int64(5),
26894 ],
26895 )
26896 .unwrap();
26897 let witness = col
26898 .int64_dense_cycle_witness()
26899 .expect("dense cycle should certify");
26900 assert_eq!(witness.start, 5);
26901 assert_eq!(witness.period, 3);
26902 assert_eq!(witness.len, 7);
26903 assert_eq!(witness.offset_count_for_key(5), Some((0, 3)));
26904 assert_eq!(witness.offset_count_for_key(6), Some((1, 2)));
26905 assert_eq!(witness.offset_count_for_key(7), Some((2, 2)));
26906 assert_eq!(witness.offset_count_for_key(8), None);
26907
26908 let again = col
26909 .int64_dense_cycle_witness()
26910 .expect("cached dense cycle should be reusable");
26911 assert_eq!(again, witness);
26912 }
26913
26914 #[test]
26915 fn bool_affine_selection_witness_is_exact_and_cached_uza0478() {
26916 let scalar_built = Column::new(
26917 DType::Bool,
26918 vec![
26919 Scalar::Bool(true),
26920 Scalar::Bool(false),
26921 Scalar::Bool(true),
26922 Scalar::Bool(false),
26923 Scalar::Bool(true),
26924 ],
26925 )
26926 .unwrap();
26927 assert!(matches!(
26928 &scalar_built.values,
26929 ScalarValues::LazyAllValidBool { .. }
26930 ));
26931 assert_eq!(
26932 scalar_built.bool_affine_selection_witness(),
26933 Some(BoolAffineSelectionWitness {
26934 start: 0,
26935 step: 2,
26936 len: 3,
26937 })
26938 );
26939 assert_eq!(
26940 scalar_built.bool_affine_selection_witness(),
26941 Some(BoolAffineSelectionWitness {
26942 start: 0,
26943 step: 2,
26944 len: 3,
26945 })
26946 );
26947
26948 let typed_built = Column::from_bool_values(vec![false, true, false, true, false]);
26949 assert_eq!(
26950 typed_built.bool_affine_selection_witness(),
26951 Some(BoolAffineSelectionWitness {
26952 start: 1,
26953 step: 2,
26954 len: 2,
26955 })
26956 );
26957
26958 let non_affine = Column::from_bool_values(vec![true, false, false, true, true]);
26959 assert_eq!(non_affine.bool_affine_selection_witness(), None);
26960
26961 let nullable = Column::from_values(vec![
26962 Scalar::Bool(true),
26963 Scalar::Null(NullKind::Null),
26964 Scalar::Bool(true),
26965 ])
26966 .unwrap();
26967 assert_eq!(nullable.bool_affine_selection_witness(), None);
26968 }
26969
26970 #[test]
26971 fn int64_dense_cycle_witness_rejects_gaps_and_nulls_uza0466() {
26972 let gapped = Column::new(
26973 DType::Int64,
26974 vec![
26975 Scalar::Int64(5),
26976 Scalar::Int64(6),
26977 Scalar::Int64(8),
26978 Scalar::Int64(5),
26979 ],
26980 )
26981 .unwrap();
26982 assert_eq!(gapped.int64_dense_cycle_witness(), None);
26983
26984 let nullable = Column::new(
26985 DType::Int64,
26986 vec![
26987 Scalar::Int64(5),
26988 Scalar::Null(NullKind::Null),
26989 Scalar::Int64(7),
26990 ],
26991 )
26992 .unwrap();
26993 assert_eq!(nullable.int64_dense_cycle_witness(), None);
26994 }
26995
26996 #[test]
26997 fn typed_all_valid_constructors_keep_single_typed_backing() {
26998 let ints = Column::from_i64_values(vec![1, 2, 3]);
26999 assert_eq!(ints.dtype(), DType::Int64);
27000 assert!(ints.validity.all());
27001 assert!(ints.data.is_none());
27002 assert_eq!(ints.as_i64_slice(), Some([1, 2, 3].as_slice()));
27003 assert_eq!(
27004 ints.values(),
27005 &[Scalar::Int64(1), Scalar::Int64(2), Scalar::Int64(3)]
27006 );
27007
27008 let floats = Column::from_f64_values(vec![1.5, -0.0, f64::INFINITY]);
27009 assert_eq!(floats.dtype(), DType::Float64);
27010 assert!(floats.validity.all());
27011 assert!(floats.data.is_none());
27012 assert_eq!(
27013 floats.as_f64_slice().map(|values| {
27014 values
27015 .iter()
27016 .map(|value| value.to_bits())
27017 .collect::<Vec<_>>()
27018 }),
27019 Some(vec![
27020 1.5f64.to_bits(),
27021 (-0.0f64).to_bits(),
27022 f64::INFINITY.to_bits()
27023 ])
27024 );
27025 assert_eq!(
27026 floats.values(),
27027 &[
27028 Scalar::Float64(1.5),
27029 Scalar::Float64(-0.0),
27030 Scalar::Float64(f64::INFINITY)
27031 ]
27032 );
27033 }
27034
27035 #[test]
27036 fn from_values_float64_fast_path_preserves_surface() {
27037 let nan = f64::from_bits(0x7ff8_0000_0000_1234);
27038 let column = Column::from_values(vec![
27039 Scalar::Float64(1.5),
27040 Scalar::Float64(-0.0),
27041 Scalar::Float64(f64::INFINITY),
27042 Scalar::Float64(nan),
27043 ])
27044 .expect("homogeneous float64 column");
27045
27046 assert_eq!(column.dtype(), DType::Float64);
27047 assert!(column.data.is_none());
27048 assert!(column.validity.get(0));
27049 assert!(column.validity.get(1));
27050 assert!(column.validity.get(2));
27051 assert!(!column.validity.get(3));
27052 let bits = column
27053 .values()
27054 .iter()
27055 .map(|value| match value {
27056 Scalar::Float64(value) => Some(value.to_bits()),
27057 _ => None,
27058 })
27059 .collect::<Vec<_>>();
27060 assert_eq!(
27061 bits,
27062 vec![
27063 Some(1.5f64.to_bits()),
27064 Some((-0.0f64).to_bits()),
27065 Some(f64::INFINITY.to_bits()),
27066 Some(nan.to_bits()),
27067 ]
27068 );
27069
27070 let mixed = Column::from_values(vec![
27071 Scalar::Float64(1.0),
27072 Scalar::Null(NullKind::NaN),
27073 Scalar::Float64(3.0),
27074 ])
27075 .expect("mixed float/null fallback");
27076 assert_eq!(mixed.dtype(), DType::Float64);
27077 assert_eq!(
27078 mixed.values(),
27079 &[
27080 Scalar::Float64(1.0),
27081 Scalar::Null(NullKind::NaN),
27082 Scalar::Float64(3.0),
27083 ]
27084 );
27085
27086 let empty = Column::from_values(Vec::new()).expect("empty fallback");
27087 assert_eq!(empty.dtype(), DType::Null);
27088 assert!(empty.values().is_empty());
27089 }
27090
27091 #[test]
27092 fn repeated_slice_int64_column_matches_eager_materialization() {
27093 let lazy = Column::from_i64_repeated_slices(
27094 vec![10, 11, 12, 20, 21],
27095 vec![(0, 3), (3, 2), (0, 3)],
27096 );
27097 let eager = Column::from_i64_values(vec![10, 11, 12, 20, 21, 10, 11, 12]);
27098
27099 assert_eq!(lazy.dtype(), DType::Int64);
27100 assert!(lazy.validity.all());
27101 assert_eq!(lazy.len(), eager.len());
27102 assert_eq!(lazy.as_i64_slice(), eager.as_i64_slice());
27103 assert_eq!(lazy.values(), eager.values());
27104 assert_eq!(lazy, eager);
27105 }
27106
27107 #[test]
27108 fn nullable_repeated_slices_store_sparse_invalid_ranges() {
27109 let segments: Arc<[(usize, usize)]> = Arc::from(vec![(0, 2), (usize::MAX, 3), (2, 1)]);
27110 let column =
27111 Column::from_f64_nullable_repeated_slices_shared(vec![1.0, 2.0, 3.0], segments, 6);
27112
27113 assert_eq!(column.dtype(), DType::Float64);
27114 assert!(column.validity.words.is_empty());
27115 assert_eq!(
27116 column.validity.invalid_ranges.as_deref(),
27117 Some(&[(2, 3)][..])
27118 );
27119 assert_eq!(
27120 column.values(),
27121 &[
27122 Scalar::Float64(1.0),
27123 Scalar::Float64(2.0),
27124 Scalar::Null(NullKind::NaN),
27125 Scalar::Null(NullKind::NaN),
27126 Scalar::Null(NullKind::NaN),
27127 Scalar::Float64(3.0),
27128 ]
27129 );
27130 }
27131
27132 #[test]
27133 fn nullable_repeated_slices_accept_precomputed_sparse_validity() {
27134 let segments: Arc<[(usize, usize)]> =
27135 Arc::from(vec![(0, 1), (usize::MAX, 1), (usize::MAX, 1), (1, 1)]);
27136 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2)]), 4);
27137 let column = Column::from_f64_nullable_repeated_slices_shared_with_sparse_validity(
27138 vec![4.0, -2.0],
27139 segments,
27140 validity,
27141 4,
27142 );
27143
27144 assert_eq!(
27145 column.values(),
27146 &[
27147 Scalar::Float64(4.0),
27148 Scalar::Null(NullKind::NaN),
27149 Scalar::Null(NullKind::NaN),
27150 Scalar::Float64(-2.0),
27151 ]
27152 );
27153 assert_eq!(
27154 column.validity.invalid_ranges.as_deref(),
27155 Some(&[(1, 2)][..])
27156 );
27157 }
27158
27159 #[test]
27160 fn nullable_repeat_values_store_sparse_invalid_ranges() {
27161 let run_valid: Arc<[bool]> = Arc::from(vec![true, false, true]);
27162 let run_lens: Arc<[usize]> = Arc::from(vec![2, 3, 1]);
27163 let column = Column::from_f64_nullable_repeat_values_run_lengths(
27164 vec![7.0, 0.0, -9.0],
27165 run_valid,
27166 run_lens,
27167 6,
27168 );
27169
27170 assert_eq!(column.dtype(), DType::Float64);
27171 assert!(column.validity.words.is_empty());
27172 assert_eq!(
27173 column.validity.invalid_ranges.as_deref(),
27174 Some(&[(2, 3)][..])
27175 );
27176 assert_eq!(
27177 column.values(),
27178 &[
27179 Scalar::Float64(7.0),
27180 Scalar::Float64(7.0),
27181 Scalar::Null(NullKind::NaN),
27182 Scalar::Null(NullKind::NaN),
27183 Scalar::Null(NullKind::NaN),
27184 Scalar::Float64(-9.0),
27185 ]
27186 );
27187 }
27188
27189 #[test]
27190 fn nullable_repeat_values_accept_precomputed_sparse_validity() {
27191 let run_valid: Arc<[bool]> = Arc::from(vec![true, false, true]);
27192 let run_lens: Arc<[usize]> = Arc::from(vec![1, 2, 1]);
27193 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(1, 2)]), 4);
27194 let column = Column::from_f64_nullable_repeat_values_run_lengths_with_sparse_validity(
27195 vec![8.0, 0.0, -4.0],
27196 run_valid,
27197 run_lens,
27198 validity,
27199 4,
27200 );
27201
27202 assert_eq!(
27203 column.values(),
27204 &[
27205 Scalar::Float64(8.0),
27206 Scalar::Null(NullKind::NaN),
27207 Scalar::Null(NullKind::NaN),
27208 Scalar::Float64(-4.0),
27209 ]
27210 );
27211 assert_eq!(
27212 column.validity.invalid_ranges.as_deref(),
27213 Some(&[(1, 2)][..])
27214 );
27215 }
27216
27217 #[test]
27218 fn nullable_repeated_positions_i64_as_f64_matches_tape_materialization_uza0461() {
27219 let source: Arc<[i64]> = Arc::from(vec![10, 20, 30, 40]);
27220 let positions: Arc<[usize]> = Arc::from(vec![2, 0, 3]);
27221 let segments: Arc<[(usize, usize)]> = Arc::from(vec![(0, 2), (usize::MAX, 1), (2, 1)]);
27222 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(2, 1)]), 4);
27223 let column = Column::from_i64_nullable_repeated_positions_as_f64_with_sparse_validity(
27224 source, positions, segments, validity, 4,
27225 );
27226
27227 assert_eq!(column.dtype(), DType::Float64);
27228 assert_eq!(
27229 column.values(),
27230 &[
27231 Scalar::Float64(30.0),
27232 Scalar::Float64(10.0),
27233 Scalar::Null(NullKind::NaN),
27234 Scalar::Float64(40.0),
27235 ]
27236 );
27237 assert_eq!(
27238 column.validity.invalid_ranges.as_deref(),
27239 Some(&[(2, 1)][..])
27240 );
27241 }
27242
27243 #[test]
27244 fn nullable_repeat_positions_i64_as_f64_matches_run_values_uza0461() {
27245 let source: Arc<[i64]> = Arc::from(vec![7, -3, 11]);
27246 let run_positions: Arc<[usize]> = Arc::from(vec![0, 0, 2]);
27247 let run_valid: Arc<[bool]> = Arc::from(vec![true, false, true]);
27248 let run_lens: Arc<[usize]> = Arc::from(vec![2, 3, 1]);
27249 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(2, 3)]), 6);
27250 let column = Column::from_i64_nullable_repeat_positions_as_f64_with_sparse_validity(
27251 source,
27252 run_positions,
27253 run_valid,
27254 run_lens,
27255 validity,
27256 6,
27257 );
27258
27259 assert_eq!(column.dtype(), DType::Float64);
27260 assert_eq!(
27261 column.values(),
27262 &[
27263 Scalar::Float64(7.0),
27264 Scalar::Float64(7.0),
27265 Scalar::Null(NullKind::NaN),
27266 Scalar::Null(NullKind::NaN),
27267 Scalar::Null(NullKind::NaN),
27268 Scalar::Float64(11.0),
27269 ]
27270 );
27271 assert_eq!(
27272 column.validity.invalid_ranges.as_deref(),
27273 Some(&[(2, 3)][..])
27274 );
27275 }
27276
27277 #[test]
27278 fn dense_cycle_probe_repeat_int64_preserves_probe_order_yq96z() {
27279 let probe = Column::from_i64_values(vec![0, 1, 2, 0, 1]);
27280 let build = Column::from_i64_values(vec![1, 2, 1, 2]);
27281 let probe_witness = probe
27282 .int64_dense_cycle_witness()
27283 .expect("probe dense cycle");
27284 let build_witness = build
27285 .int64_dense_cycle_witness()
27286 .expect("build dense cycle");
27287 let column = Column::from_i64_dense_cycle_probe_repeat(
27288 Arc::from(vec![10, 11, 12, 13, 14]),
27289 probe_witness,
27290 build_witness,
27291 8,
27292 );
27293
27294 assert_eq!(column.dtype(), DType::Int64);
27295 assert!(column.validity.all());
27296 assert_eq!(
27297 column.as_i64_slice(),
27298 Some([10, 11, 11, 12, 12, 13, 14, 14].as_slice())
27299 );
27300 assert_eq!(
27301 column.values(),
27302 &[
27303 Scalar::Int64(10),
27304 Scalar::Int64(11),
27305 Scalar::Int64(11),
27306 Scalar::Int64(12),
27307 Scalar::Int64(12),
27308 Scalar::Int64(13),
27309 Scalar::Int64(14),
27310 Scalar::Int64(14),
27311 ]
27312 );
27313 }
27314
27315 #[test]
27316 fn nullable_dense_cycle_probe_build_int64_preserves_build_ties_yq96z() {
27317 let probe = Column::from_i64_values(vec![0, 1, 2, 0, 1]);
27318 let build = Column::from_i64_values(vec![1, 2, 1, 2]);
27319 let probe_witness = probe
27320 .int64_dense_cycle_witness()
27321 .expect("probe dense cycle");
27322 let build_witness = build
27323 .int64_dense_cycle_witness()
27324 .expect("build dense cycle");
27325 let validity = ValidityMask::from_invalid_ranges(Arc::from(vec![(0, 1), (5, 1)]), 8);
27326 let column = Column::from_i64_nullable_dense_cycle_probe_build_with_sparse_validity(
27327 Arc::from(vec![100, 200, 101, 201]),
27328 probe_witness,
27329 build_witness,
27330 validity,
27331 8,
27332 );
27333
27334 assert_eq!(column.dtype(), DType::Int64);
27335 assert_eq!(
27336 column.validity.invalid_ranges.as_deref(),
27337 Some(&[(0, 1), (5, 1)][..])
27338 );
27339 assert_eq!(
27340 column.values(),
27341 &[
27342 Scalar::Null(NullKind::Null),
27343 Scalar::Int64(100),
27344 Scalar::Int64(101),
27345 Scalar::Int64(200),
27346 Scalar::Int64(201),
27347 Scalar::Null(NullKind::Null),
27348 Scalar::Int64(100),
27349 Scalar::Int64(101),
27350 ]
27351 );
27352 }
27353}